Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have error message " for file changes with StatReloader Exception in thread django-main-thread:"
I have errors in configuration, and when I had been downloading the project from Github that error shown to me when I run the server that problem happened also I tried to create a new project, so the project run. How can I avoid this problem and solve it? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mediumeditor' Traceback (most recent call last): File "C:/xampp/htdocs/athar/manage.py", line 21, in <module> main() File "C:/xampp/htdocs/athar/manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\promi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 599, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) … -
Sending users a password insertion Django Rest Framework
I am using Django Rest Framework and want to be able to send a user a password reset view. It actually comes from a user inviting them into the software but it automatically sets a secure password. I want to be able to send that user an email asking them to change their password. How can I go about this? -
Creating tcp connection to Redis infinite (django, celery, channels)
I'm using Django with Channels 2 and create task With Celery, but when I pass the results of the job to async_to_sync (channel_layer.group_send) ( 'view', {'type': 'view.joke', 'text': joke} ) and look with debug, see the following. [2020-03-31 02:41:09,601: DEBUG/MainProcess] Using selector: SelectSelector [2020-03-31 02:41:09,602: DEBUG/MainProcess] Creating tcp connection to ('127.0.0.1', '6379') At the same time, the task is in progress every 15 seconds, and its result should be displayed on the page, but i have printed the first result, and then Celery freezes. -
Django Migration InternalError 1054 Unknown column
I added an ImageField to an existing item in models.py, I ran makeMigrations and Migrate and yet as a result now if I go to my admin panel I get the below error: InternalError(1054, u"Unknown column 'modelname.picture' in 'field list'") This error goes away if I remove that ImageField. I'm running Django==1.11.26 This is a copy of the feild: picture = models.ImageField(null=True, blank=True, upload_to='images/') Very appreciative of any help on this one. -
Why in javaScript, mySQL timestamp are not converted the same on mobile then on desktop?
I have a ajax request to fetch django data in json. i receive the response and everything is ok, i keep dateTime in my django app as naive date since i don't have to manage timezone. i want date/time to be showed like they are saved. Ok in my javascript, when i do a: console.log(item.fields.timeStamp); I receive: 2020-03-29T21:00:00.143 On both desktop and my iPhone, and that is wath i expect, but when i do that: alert(new Date(item.fields.timeStamp)); I receive: Sun Mar 29 2020 20:05:21 GMT-0400 (heure d’été de l’Est) On my desktop and: Sun Mar 29 2020 16:05:21 GMS-0400 (EDT) And that is totally wrong!! So all timeStamp in my app are totally off on mobile devices. What can be my problem ? -
Handling nested object representations in Django REST Framework
I have some problem with handling nested serializers (DRF). I want to collect data with some structure like this: { 'datetime': xxxxxxx, 'measurements': [ {'int_test': 1, 'char_test': '1'}, {'int_test': 2, ''char_test: '2'} ] } I'm using the documentation (https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects) and i'm looking at (https://medium.com/@raaj.akshar/creating-reverse-related-objects-with-django-rest-framework-b1952ddff1c) and still have the HTTP 400 response: '{"measurements":["This field is required."]}' (201 only when measurement is read_only - it's Logical) models.py class Data(models.Model): datetime = models.DateTimeField() def __str__(self): return 'just testing' class Measurement(models.Model): data = models.ForeignKey(Data, on_delete=models.CASCADE) char_test = models.CharField(max_length=100) test = models.IntegerField(default=0) def __str__(self): return self.char_test serializers.py: class MeasurementSerializer(serializers.ModelSerializer): class Meta: model = Measurement fields = '__all__' class DataSerializer(serializers.ModelSerializer): measurements = MeasurementSerializer(many=True) class Meta: model = Data fields = ['datetime', 'measurements'] def create(self, validated_data): measurement_validated_data = validated_data.pop('measurements') data = Data.objects.create(**validated_data) Measurement.objects.create(data=data, **measurement_validated_data) return data And my simple post request: data = { "datetime": datetime.now(), "measurements": [ {'test': 1, 'char_test': '1'}, {'test': 2, 'char_test': '2'}, ], } r = requests.post( 'http://127.0.0.1:8000/api/', data=data, ) Did I forget something? -
400 Bad Request - django template
I'm trying to add possibility to add product to cart from two places in my Django project. Index view (main page, non-API version in main views file) - in this view this works. This view is in main project view.py file. def index(request): products = Product.objects.all()[:10] products_dict = {'products': products} return render(request, 'products/index.html', products_dict) Template index.html and no problem to redirect to add_item_to_cart view (from application Cart) {% for item in products %} <a href="{% url 'cart:add_item_to_cart' item.id %}" class="btn essence-btn">Add to Cart</a> {% endfor %} Product detail class view (API version in Product application) - in this view this doesn't work class ProductDetail(ListCreateAPIView): template_name = 'products/product_api.html' renderer_classes = [TemplateHTMLRenderer] serializer_class = ProductSerializer def get(self, request, pk): product = get_object_or_404(Product, pk=pk) serializer = ProductSerializer(product) return Response({'serializer': serializer, 'object': product}) Template product_api.html and problem to redirect to add_item_to_cart view. I have receive 400 Bad Request {% for item in products %} <a href="{% url 'cart:add_item_to_cart' object.id %}">Add to Cart</a> {% endfor %} Why the same resource works to first template but doesn't to second? Is it possible to redirect from API view to different app (Cart)? I was able to handle POST request by adding post method and to redirect to … -
{% load static%} {% block content %} {%endblock%} arent being executed properly in my website
{% extends 'budget/base.html' %} {% block content %} <div class="container"> <h1>My Projects</h1> <hr> <div class="row"> {% for project in project_list %} <div class="col s12 md6 xl3"> <div class="card-panel"> <h5>{{ project.name }}</h5> <a href="{% url 'detail' project.slug %}" class="btn">Visit</a> </div> </div> {% empty %} <div class="noproject-wrapper center"> <h3 class="grey-text">Sorry, you don't have any projects, yet.</h3> <a href="{% url 'add' %}" class="btn-large grey"> <i class="material-icons white-text left">add_circle</i> <span class="bold">Add Projects</span> </a> </div> {% endfor %} </div> </div> {% endblock %} if you open the webpage with this it doesn't display what it's supposed to display I checked the code and I don't know what's wrong -
How do i convert WSGIRequest to string
if i pass a parameter to graph_data() and convert it into string in 1st pass of program execution it take a parameter as a string but in 2nd pass it will take parameter as please someone help me in it i want to return a proper graph for graph_data() Note:- if i manually pass String(Stock Name) to web.dataReader() it will return graph, index.html:-Here i want to show graph <img src="{% url "showplt" %}" /> views.py:- import pandas_datareader as web def index(request): if request.method == 'POST': search = request.POST['search'] graph_data(search) def graph_data(request): request_p = str(request) ex = '.NS' st_name = request_p + ex print('STNAME:', st_name) print(type(st_name)) print(type(request_p)) print(type(ex)) df = web.DataReader(st_name, data_source='yahoo', start='2019-01-01', end='2020-03-16') print(df) plt.figure(figsize=(12, 7)) plt.title('Close Price History') plt.plot(df['Close']) plt.xlabel('Date', fontsize=18) plt.ylabel('Close Price in RS', fontsize=18) buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save(buffer, "PNG") pylab.close() response = HttpResponse(buffer.getvalue(), content_type="image/png") return response urls.py:- path('showplt/', views.graph_data, name='showplt'), error(Terminal):- STNAME: <WSGIRequest: GET '/showplt/'>.NS <class 'str'> <class 'str'> <class 'str'> Not Found: /searchicon.png STNAME: RELIANCE.NS <class 'str'> <class 'str'> <class 'str'> Internal Server Error: /showplt/ Traceback (most recent call last): -
issue with html display in Django maybe coming from view.py structure
I am building a django app and i am very not familiar with the frontend stuff. Ultimately i want to build a dashboard but as now I am somewhat struggling with building a view that matches what I want it to display. So far the view class is well transfered to frontend (no error when running the server), but instead of displaying values, it displays black dots. here is attached my html code as well as my view.py <ul> {% for reference in top_sellers_list %} <li><a href="/dashboard/{{ top_sellers_list.reference }}/"> {{top_sellers_list.avg_per_week }}</a></li> {% endfor %} </ul> <ul> {% for reference in classification %} <li><a href="/dashboard/{{ classification.Class }}/"> {{classification.inventory_dollars }}</a></li> {% endfor %} </ul> <ul> {% for reference in anormal %} <li><a href="/dashboard/{{ anormal.reference_anormales }}/"></a></li> {% endfor %} </ul> <ul> {% for reference in negat %} <li><a href="/dashboard/{{ negat.reference_negatives }}/"></a></li> {% endfor %} </ul> <ul> {% for reference in service %} <li><a href="/dashboard/{{ service.reference_service }}/"></a></li> {% endfor %} </ul> from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import top_sellers, Classification, stock_anormal, stock_negatif, niveau_service # Create your views here. def dashboard(request): top_sellers_list = top_sellers.objects.order_by('avg_per_week')[:8] classification = Classification.objects.order_by('Class') anormal = stock_anormal.objects.order_by('reference_anormales') negat = stock_negatif.objects.order_by('reference_negatives') service = niveau_service.objects.order_by('reference_service') context1 = { … -
Accessing Django 3 TextChoices via an exposed API endpoint?
I am using Django 3.0.4 with Django REST Framework 3.11.0 where I have a models.py like: from django.db import models from model_utils.models import TimeStampedModel class SampleModel(TimeStampedModel): class Options(models.TextChoices): FOO = "A" BAR = "B" BAZ = "C" name = models.CharField(default="", max_length=512) options = models.CharField( max_length=2, choices=Options.choices, default=Options.FOO ) I would like to be able to create an API endpoint to return a list of my TextChoices as a tuple. I have a React frontend where I want to create a <select> dropdown with my list of choices. If I can access the list of TextChoices via an API endpoint, I should be good to go. path("api/sample/choices/", views.SampleChoicesListView.as_view(), name="sample_choices") I'm not sure what my views.py needs to look like to make this work... class SampleChoicesListView(generics.ListAPIView): pass -
Django: UNIQUE constraint failed: user.username
I have a problem using Djangos Default user from django.contrib.auth.models but trying to use it with my custom User model, using from django.contrib.auth.models import AbstractUser. So here is my User model: from django.db import models from django.contrib.auth.models import AbstractUser, UserManager as AbstractUserManager # from django.conf import settings from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.db.models.signals import post_save from django.dispatch import receiver class UserManager(AbstractUserManager): pass class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def __str__(self): return "{} {}".format(self.first_name, self.last_name) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: User.objects.set_password(instance.password) and here is my Profile model: from django.db import models from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.contrib.auth import get_user_model User = get_user_model() # https://medium.com/swlh/best-practices-for-starting-a-django-project-with-the-right-user-model-290a09452b88 from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Profile') birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() But before adding User.objects.set_password(instance.password) to my User model, I did it in … -
How do I get an element that is nested within a JSON dictionary?
I got a JSON response using the Spotify API and I'm trying to access the element called 'name' (one says '3 Doors Down' and the other starts with 'Bret Michaels') that seems to be inside the 'items' element but I can't seem to find the solution. This is how I loaded the data: search_results = requests.get(search_url + 'q=' + query + '&type=artist', headers=granted_headers).json() Here is my JSON data: { 'artists': { 'href': 'https://api.spotify.com/v1/search?query=3+doors+down&type=artist&offset=0&limit=20', 'items': [ { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/2RTUTCvo6onsAnheUk3aL9' }, 'followers': { 'href': None, 'total': 2631330 }, 'genres': [ 'alternative metal', 'nu metal', 'pop rock', 'post-grunge' ], 'href': 'https://api.spotify.com/v1/artists/2RTUTCvo6onsAnheUk3aL9', 'id': '2RTUTCvo6onsAnheUk3aL9', 'images': [ { 'height': 640, 'url': 'https://i.scdn.co/image/ead4e883a59d30d8c157385aa531d3fe8e688fc0', 'width': 640 }, { 'height': 320, 'url': 'https://i.scdn.co/image/611a4fd8aaf2637c5894acf65f12e79d75926329', 'width': 320 }, { 'height': 160, 'url': 'https://i.scdn.co/image/f1a1a2c37f2f6d242b1ab7ae3f4d893bf5822095', 'width': 160 } ], 'name': '3 Doors Down', 'popularity': 72, 'type': 'artist', 'uri': 'spotify:artist:2RTUTCvo6onsAnheUk3aL9' }, { 'external_urls': { 'spotify': 'https://open.spotify.com/artist/2kPbQDZvnasPcCuXbq6YQx' }, 'followers': { 'href': None, 'total': 156 }, 'genres': [ ], 'href': 'https://api.spotify.com/v1/artists/2kPbQDZvnasPcCuXbq6YQx', 'id': '2kPbQDZvnasPcCuXbq6YQx', 'images': [ ], 'name': 'Bret Michaels (Featuring Brad Arnold of 3 Doors Down, Chris Cagle, Mark Wills)', 'popularity': 4, 'type': 'artist', 'uri': 'spotify:artist:2kPbQDZvnasPcCuXbq6YQx' } ], 'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total': 4 } } -
Are There OS Difference Concerns Running a Docker Container on Different Operation Systems
I want to migrate a Django project into a Docker container (hoping I have the right term here) so that I can more closely mimic my integration and productions environments. I'm developing the django project on MacOS and my integration server is Ubuntu 18.04 in a droplet on Digital Ocean. I already got bit by forgetting about letter case sensitivity running directly on MacOS. From other questions and answers I've read here, that the container doesn't have its own OS, but relies on the host. Is it possible then to make a Docker container on MacOS behave as if it is running Ubuntu 18.04? For example, will running in a Docker container error out on letter case issue where MacOS won't? IIRC, all linux versions are case sensitive. What about differences between various flavors of Linux? If differences are a concern, can I specify Ubuntu for my container in some fashion? -
How to apply function to field in values_list lookup
My line of code goes: replies = Comment.objects.filter(reply_to__pk__exact=pk).annotate(dates=timesince.timesince('date'))\ .order_by('-dates')\ .values_list("owner__username", "text", "dates", "likes", "owner__customuser__picture") I want the dates column in the result to be transformed by the timesince.timesince function. Instead, it throws an error like so: AttributeError: 'str' object has no attribute 'year' How do I resolve this? -
django: ValidationError with UniqueConstraint on Model.Forms, clean()
I want to get a message (ValidationError) on the form insted the of page with IntegretyError, from the UniqueConstraint. models.py class Solicitacao(models.Model): '''Modelo de solicitação''' solicitante = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, validators=[]) disciplina = models.ForeignKey("Disciplina", on_delete=models.CASCADE, validators=[]) [..some other data...] data_solicitacao = models.DateTimeField( ("Data da solicitação"), auto_now_add=True) class Meta: ordering = ['-data_solicitacao', 'solicitante'] constraints = [ models.UniqueConstraint(fields=['solicitante', 'disciplina'], name='unique_solicitação') ] views.py @login_required def nova_solicitacao(request): if request.method == 'POST': form = SolicitacaoForm(request.user, request.POST) form.instance.solicitante = request.user if form.is_valid(): solicitacao = form.save(commit=False) solicitacao.save() return redirect(reverse_lazy('cc:solicitacoes')) else: form = SolicitacaoForm(request.user) return render(request, 'cc/solicitacao_form.html', {'form': form}) forms.py class SolicitacaoForm(forms.ModelForm): class Meta(): model = Solicitacao fields = ['disciplina', 'justificativa', 'documentos'] def __init__(self, user, *args, **kwargs): super(SolicitacaoForm, self).__init__(*args, **kwargs) if not user.is_staff: curso = user.curso self.fields['disciplina'].queryset = Disciplina.objects.filter(curso=curso) I belive the best approuch would be to writr def clean() but since solicitante isn't one of the fields on the form i couldn't figure how to acess in clean. I also plan to limit to 3 anwsers per user. I plan to use a query basead on the user in the clean field, bu again i couldn't figure how to access it. -
UNIQUE constraint failed or NOT NULL constraint failed - no inbetween
I am working on a project where a user initially registers, then fills in two separate pages of information about their profile ( on the PII and finalPII pages). For whatever reason I have not been able to save this information correctly into my Profile model and always get one of two errors that have to do with the user id: either a UNIQUE constraint failed when I include the line profile.user = request.useror a NOT NULL constraint failed error when I get rid of this line. I am not sure where the middle ground is here and I greatly appreciate any help or advice given. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm, PIIForm, FinalPIIForm from .models import Profile def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return … -
Django model is not saving to Database
I have a very simple model containing just four fields: meeting_date,meeting_hour, participant_name and ```participant_email``. I'm sending email about selected data, hour to participant, it works. But this schedule is not writing to database. Here are my codes: views.py: def index(request): context = { 'schedules': Schedule.objects.all() } participant_name = request.POST.get('name') participant_email = request.POST.get('email') meeting_date = request.POST.get('date') meeting_hour = request.POST.get('hour') subject = 'Görüş' message = 'Hello ' + str(participant_name) + '. \nDate: ' + str(meeting_date) + ' hour ' + str(meeting_hour). from_email = settings.SERVER_EMAIL recipient_list = [participant_email] send_mail(subject, message, from_email, recipient_list) if request.POST.get('participant_email'): Schedule.objects.create( participant_name = request.POST.get('name'), participant_email = request.POST.get('email'), meeting_date = request.POST.get('date'), meeting_hour = request.POST.get('hour') ) return render(request, 'index.html', context) admin.py: class ScheduleAdmin(admin.ModelAdmin): list_display = ['participant_name', 'participant_email', 'is_scheduled', 'meeting_date', 'meeting_hour'] admin.site.register(Schedule, ScheduleAdmin) models.py: class Schedule(models.Model): participiant_name = models.CharField(max_length=100) participiant_email = models.CharField(max_length=100) meeting_date = models.DateField() meeting_hour = models.TimeField() is_scheduled = models.BooleanField(default=False) def __str__(self): return self.meeting_date html: <form action="{% url 'index' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label><br/> <input type="text" name="name" id="name" placeholder="Name"> </div> <div class="form-group"> <label for="email">Email</label><br/> <input type="email" name="email" id="email" placeholder="Email"> </div> <div class="form-group"> <label for="date">Date</label><br/> <input type="date" name="date"> </div> <div class="form-group"> <label for="hour">Saat</label><br/> <select name="hour" id="hour"> <option value="1">Hour</option> <option value="14:00">14:00</option> <option value="15:00">15:00</option> <option value="16:00">16:00</option> <option value="17:00">17:00</option> <option value="18:00">18:00</option> … -
my register model data is not storing in db when i try to create any new user
my register model data is not storing in db when i try to create any new user. also studentID doesn't give any error with AutoField but with IntegerField it gives "UNIQUE constraint failed: user_profile.user" here is my model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) StudentID = models.IntegerField(primary_key=True, verbose_name='SID') Branch = models.CharField(max_length=255, choices=Departments, default="CSE") YearOfStudy = models.IntegerField(default=1) ContactNumber = PhoneField(help_text='Contact phone number') image = models.ImageField(default='default.jpeg', upload_to='profile_pics', blank=True) parentsContactNumber = PhoneField(help_text="Parent's phone number", blank=True) def __str__(self): return self.Branch def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ['StudentID', 'Branch', 'YearOfStudy', 'ContactNumber'] views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) form1 = ProfileCreationForm(request.POST, request.FILES) if form.is_valid() and form1.is_valid(): StudentID = form.cleaned_data.get('StudentID') username = form.cleaned_data.get('username') user_instance = form.save() profile_instance = form1.save(commit=False) profile_instance.user = user_instance profile_instance.save() form1.save(commit=True) return redirect('login') else: form = UserRegisterForm() form1 = ProfileCreationForm() context = { 'form': form, 'form1': form1 } return render(request, 'user/register.html', context) in this code if i write … -
How to push a protectedSource in django-ckeditor?
I am currently using django-ckeditor for a site, It works great, but I need to a some In-article ads (google adsense). After saving a register the code is stripped and I don´t know where or how to set the protectedSource to allow the tag. I have sucessfully allowed script content, but not the ins tag used by google adsense. <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-XXXXXXXXXXXX" data-ad-slot="XXXXXXXXXXX"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> My current CKEDITOR_CONFIGS is like this: CKEDITOR_CONFIGS = { 'custom': { 'toolbar': 'Custom', 'extraAllowedContent':'script ins', 'removePlugins': 'stylesheetparser', #'protectedSource': ['/<ins class=\"adsbygoogle\"\>.*?<\/ins\>/g'], 'toolbar_Custom': [ { 'items': [ 'RemoveFormat', 'PasteFromWord', ] }, { 'items': [ 'Styles', 'Format', 'Bold', 'Italic', 'Underline', ] }, { 'items': [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent' ] }, {'items': ['Blockquote', 'Outdent', 'Indent']}, {'items': ['NumberedList', 'BulletedList']}, { 'items': [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] }, '/', {'items': ['Font', 'FontSize']}, {'items': ['Source']}, {'items': ['Link', 'Unlink']}, {'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Embed']}, {'items': ['Smiley', 'SpecialChar', 'PageBreak', 'Iframe']} ], 'extraPlugins': ','.join([ 'div', 'autoembed', 'embedsemantic', ]), 'embed_provider': '//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}&api_key=abc123', }, 'default': { 'toolbar': 'full', 'removePlugins': 'stylesheetparser', 'allowedContent': True, } } -
Devops on Google Cloud for a complex Django project
I know that any answer to this question might be interpreted as subjective but I am seeking answers from people with a devops and Google Cloud background. I don't have (advanced) experience with Google Cloud and I have none with Kubernetes. I have the following dockerized setup (and Docker Compose ready): Django (app) Redis (redis) RabbitMQ (rabbitmq) Celery (celery &app) Celery beat (celery-beat &app) Elasticsearch (elasticsearch) PostgreSQL (database) My first thought was to decouple each service (I am already using an SQL instance for database) but I don't know what (and how) exactly to choose. Also, decoupling celery and celery-beat from the main app, is not very clear how can I achieve that. I also must take into consideration the CI/CD. Currently I use Gitlab and Google Container Registry to push the image. What I would like to achieve: horizontal scalability make use of docker images decouple Redis, RabbitMQ, PostgreSQL (already decoupled) and Elasticsearch find a way to decouple Celery and Celery Beat from the main Application (maybe deploying the same image ion different instances ?) the solution must NOT involve Kubernetes. -
Python QuickBooks API
I have a problem working with python-quickbooks package, I try to follow the docs: https://pypi.org/project/python-quickbooks/ Here is my code: from django.conf import settings from intuitlib.client import AuthClient from quickbooks import QuickBooks from quickbooks.objects.account import Account auth_client = AuthClient( client_id=settings.QUICKBOOKS_CLIENT_ID, client_secret=settings.QUICKBOOKS_CLIENT_SECRET, environment='sandbox', redirect_uri=settings.QUICKBOOKS_REDIRECT_URI, ) client = QuickBooks( auth_client=auth_client, refresh_token=settings.QUICKBOOKS_REFRESH_TOKEN, company_id=settings.QUICKBOOKS_REALM_ID ) account = Account() account.from_json( { "AccountType": "Accounts Receivable", "Name": "MyJobs" } ) account.save(qb=client) However, this results in error: What am I doing wrong here? -
It dosen't show anything from bd django
It dosen't show anything from bd django, i don't why it's happend ............................................................... from django.shortcuts import render from django.http import HttpResponse from gestionFormulario.models import Personas # Create your views here. def busqueda_personas(request): return render(request, "formulario.html") def buscar(request): if request.GET["Personas"]: #mensaje = " Persona Buscada: %r" %request.GET["Personas"] personas = request.GET["Personas"] Personas_Agregadas = Personas.objects.filter(Nombre__icontains=personas) return render(request, "formulario.html", {"Personas_Agregadas":Personas_Agregadas, "query":Personas}) else: mensaje = "No introduciste nada" return render(request, "formulario.html") return HttpResponse(mensaje) -
Set Session ID Cookie in Nuxt Auth
I have the following set up in my nuxt.config.js file: auth: { redirect: { login: '/accounts/login', logout: '/', callback: '/accounts/login', home: '/' }, strategies: { local: { endpoints: { login: { url: 'http://localhost:8000/api/login2/', method: 'post' }, user: {url: 'http://localhost:8000/api/user/', method: 'get', propertyName: 'user' }, tokenRequired: false, tokenType: false } } }, localStorage: false, cookie: true }, I am using django sessions for my authentication backend, which means that upon a successful login, i will have received a session-id in my response cookie. When i authenticate with nuxt however, i see the cookie in the response, but the cookie is not saved to be used in further requests. Any idea what else i need to be doing? -
How can i run my python program in DJANGO
I have python script of web scraping that fetch given name song from youtube and give me output as in JSON format. it has many field like url,title,thumnail,duration and artist and all these field are stores in JSON file. SO i want to add that script in Django views.py, So how can i implement this. Here is the picture of output.