Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoModuleName 'channels', but I have installed it. Django
Django version 2.1.5 Channels version 2.1.6 Ubuntu 18.0.4 When I run project in pyCharm, it says: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7f18ecd8eb70> Traceback (most recent call last): File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'channels' The module installed (venv) mercer@mercerPC:~/Documents/comet$ pip list | grep channels channels 2.1.6 Here is the installed_apps: INSTALLED_APPS = [ 'channels', 'chat', 'accounts', 'events', ... ] Also I created the routing file and added ASGI_APPLICATION = 'mysite.routing.application' in settings.py -
How to access pdfs with special characters my Django app?
I have a django app, hosted using nginx and gunicorn. One of the features I have is to generate a PDF on the fly, using xhtml2pdf. I can access the pdfs in a url like /pdf/(id)/, but the issue I have is with the filename. The piece of code that is causing the problem is: # generate the pdf. This function has been tested and is not causing the problem pdf = render_to_pdf(template, data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "cotización_%s.pdf" % (doc_name) content = "inline; filename='%s'" % (filename) response['Content-Disposition'] = content return response From the error log I realized that the issue is the accent on the filename (cotización) File "~/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 182, in handle_request resp.write(item) File "~/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 333, in write self.send_headers() File "~/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 329, in send_headers util.write(self.sock, util.to_bytestring(header_str, "ascii")) File "~/lib/python3.6/site-packages/gunicorn/util.py", line 507, in to_bytestring return value.encode(encoding) UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 176: ordinal not in range(128) On my localhost, I can access the pdfs perfectly. But on my server I get a 502 error. If I remove the 'ó', the problem goes away. So my question is, how can I serve pdfs including accents on the filename? NOTE: The … -
User page permissions updating only when server restarts with Django-CMS
Basically, I am having an issue where, I have a page using rest framework that edits user (I am using the default django user app) permissions by changing the groups or changes other minor infos like name and password. However, when I edit a group of a user, and only when I edit them, for some reason, the user permissions only changes when I restart the django server, allowing the user to view django cms pags that he should not see. After the server restarts all permissions works just fine. I already tried to force the permissions to be refreshed like this: for app in settings.INSTALLED_APPS: create_permissions(apps.get_app_config(app.split(".")[-1])) but it didn't work. I actually have no clue whatsoever what the cause of the issue is, so much that I am not sure what code I could put here, so in doubt I will post the rest user serializer: # -*- coding: utf-8 -*- from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) self.fields['username'].label = u"Usuário" self.fields['password'].label = u"Senha" self.fields['first_name'].label = u"Nome Completo" group_name = serializers.SerializerMethodField() def get_group_name(self, obj): return ", ".join(list(obj.groups.values_list('name',flat=True))) def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user def … -
How to convert a queryset in django to json
I´ve seen his question has been answered multiple times for django < 2.xx, but for the current version I am using (2.1) I´been unable to convert my querysets to a json format. I´ve tried serializer using the django rest framework, but so far the only use I was able to implement is to serialize a model, so when my querysets has results from different models that does not work. This has beeing really annoying, In frameworks as Laravel this is supposed to be pretty simple, I would appreciate any help. -
Replacing Django Template Variable with variable created via Javascript
I am very new to Django and Javascript (< 3 weeks!) and have a question that might be stupid so any help would be greatly appreciated. In my current code, I have a table rendered in HTML with the following code: <table border="1" class="dataframe"> <thead> <tr> <th>{{ results.0.columns.1 }}</th> <th>{{ results.0.columns.1 }} </th> <th>{{ results.0.columns.2 }} </th> <th>{{ results.0.columns.6 }} </th> </tr> </thead> <tbody> {% for row in results.0.values %} <tr> <td> {{row.0}} </td> <td> {{row.1}} </td> <td><img src="{{row.2}}" alt="img" height="150"></td> <td> {{row.6}} </td> </tr> {% endfor %} </tbody> </table> As you can see there are numerous areas where I am referencing a django template variable with the format of {{someDjangoVariable}}. However, I'd like to replace these variables with variables that are created in Javascript. I am using Javascript to take some user input which ultimately changes the view of the table. My Javascript is set up as following: <script> function myFunction() { var index = someNumber var string = `results.${index}.columns.0`; document.getElementById('demo').innerHTML = string; } </script> The string variable created in Javascript results in something that completely mimicks the Django template variable. For example, string = results.0.columns.1. However, I'm unsure as to how to pass this string variable into the … -
How to create a particular profile based on user attribute in Django using signals
I have users that are either 'Company' or 'Applicant', each having different attributes. I want to create either a Company Profile or Applicant Profile on sign-up based on the user attribute. Below is the code I'm using in signals.py and it does not work. @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: if sender != User.is_company: Applicant.objects.create(user=instance) else: Company.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): if instance.is_applicant: instance.applicant.save() else: instance.company.save() -
How to doctor my CPU utilization issue, I am using ubuntu ec2 instance with nginx, uwsgi and django
Hello I am running an EC2 ubuntu instance (3 instances to be exact with a loadbalancer) this morning I realized that all 3 of my instances are running at 100% cpu utilization and that worries me, they're usually running below 40% unless I have scheduled task happening all at once. They are all running nginx, uwsgi, celery, and django. This has never happened to me before so I am not sure how I should approach it. What I have done so far: -Restart instances -Stop and start instances -Unload and reload balancers -Restart supervisorctl Usually these actions would regulate my cpu utilization but this time they just keep shooting back up. Any hints where I should start? -
Like button on the list, press effect is always on first one
My problem is that: I can't display buttons that have already been selected ("vote up" or "vote down") - variables in the view code. When I press the button on the last comment, e.g. "vote up". - the 'vote up' button on the first comment is highlighted - which is not sorted out. The problem may be that this is a list and additionally in a view, where the object is already a Post model. My code is below. Here is models of Post and Comment class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes') votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes') def __str__(self): return self.text def total_vote_up(self): return self.votes_up.count() def total_vote_down(self): return self.votes_down.count() class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = RichTextUploadingField() Here is detail view where I would like to check if comment is liked or not. I pass to context variables. class PostDetail(generic.DetailView, FormMixin): template_name = 'post_detail.html' context_object_name = 'post' model = Post form_class = CommentForm def get_context_data(self, **kwargs): is_voted_up = False is_voted_down = False comments = self.get_object().answers.all() for comment in comments: if answer.votes_up.filter(id=self.request.user.id).exists(): print(answer) is_voted_up = True print(is_voted_up) if answer.votes_down.filter(id=self.request.user.id).exists(): is_voted_down = True context = … -
multiple user authentication
i want to create multiple user authentication there are many groups and each group having multiple user but there is no any signup page admin will add all user, user just login and get its dashboard or homepage. example - groups like - 1. admin 2. saller 3. customer 4. xyz only admin add all user's, if customer group user login than show it's homepage. i have many confusions ... please help me for this task. just give me reference for that, how to do this -
How to set AWS credentials for user www-data for Django app using NGINX
I have a Django app running on a Linux server under NGINX. The "user" for the Django app is www-data. In this app, I try to connect to AWS IOT, and to do that I believe that the AWS boto3 package tries to find the AWS credentials here: ~/.aws/credentials. The problem is that for the user "www-data" there is no such path! When I login to the server (using my real username), and I try to run a script that connects to AWS, it connects just fine. Let's say my username is "joe". There is indeed a file /home/joe/.aws/credentials that contains the correct credentials. This is why the script works fine when I run as user "joe". But when the Django app is running, it doesn't work because there is no login user www-data, ie there is no file /home/www-data/.aws/credentials. I understand that AWS boto3 let's us set an environment variable to specify a non-standard path to the credentials file. This env variable is AWS_CONFIG_FILE. However, I don't know how to set an environment variable in Django for user www-data so that boto3 can now use that environment variable to specify the AWS credentials path. Anyone know how to do … -
How To Update Hidden Field In Django Form
I am trying to figure out the best approach to modifying a hidden django form field. Or if it's even possible. I had my HTML setup to accomplish this very task and it was working perfectly. However, in order to prevent multiple submissions I had to change my HTML and now I am unable to figure out how to pass a value via an HTML button depending on what the user clicks on. Previously, I had two buttons defined as outline below: <button type="submit" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button> <button type="submit" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button> As stated above, this worked perfectly for the purpose of passing a value to an attribute for my model. The value of status was saved as expected depending on which button the user clicked on. Now I have updated the buttons to type="button" in response to this issue that I opened up today...How To Prevent Double Submit With Form Validation I tried using the following code: <button type="button" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button> <button type="button" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button> And then I also changed the status field to {{ status.as_hidden }} in my HTML to get the value. This only works if I hardcode the status value … -
Django distinct returns more records than count
The following shows the distinct count is 2247 In [6]: VirtualMachineResources.objects.all().values('machine', 'cluster') ...: .distinct().count() Out[6]: 2247 But then when I loop through it, it returned way more than it should: In [4]: a = [] ...: for resource in VirtualMachineResources.objects.all().values('mach ...: ine', 'cluster').distinct(): ...: if resource['cluster']: ...: a.append(resource['cluster']) ...: ...: In [5]: len(a) Out[5]: 96953 It's a postgres database. Any ideas? -
Showing empty Data in tables from Database Django
Showing empty data in tables file in html when importing from the models.py Also the number of rows are increasing when increasing with data in Databse Django -
Django Admin Page - Export fields + callable fields
Django Version: 1.11 Python: 2.7 Package: django-import-export I am attempting to export the "callable" fields for a Django Admin page. (Reference: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display) In their example, they have a "callable" for their PersonAdmin list_display. def upper_case_name(obj): return ("%s %s" % (obj.first_name, obj.last_name)).upper() upper_case_name.short_description = 'Name' class PersonAdmin(ExportMixin, admin.ModelAdmin): list_display = (upper_case_name,) For the Resource, I thought I would also be able export the callable field. class PersonResource(resources.ModelResource): class Meta: model = Person fields = ( "first_name", "last_name", "upper_case_name", ) However, I will get Person has no field named "upper_case_name". Is there a way to export callable fields? From the documentation, it does look like you can export fields that do not exist. https://django-import-export.readthedocs.io/en/latest/getting_started.html Their example was: from import_export.fields import Field class BookResource(resources.ModelResource): full_title = Field() class Meta: model = Book def dehydrate_full_title(self, book): return '%s by %s' % (book.name, book.author.name) I replicated this and tried: class PersonResource(resources.ModelResource): upper_case_name = Field() class Meta: model = Person def dehydrate_upper_case_name(self, obj): return ("%s %s" % (obj.first_name, obj.last_name)).upper() I attempted to do the same thing but I would get the error Person has no field named "upper_case_name". Any thoughts? Thanks in advance! -
Post save signal on model takes too long
I have a model called partnershipArm, when a new model is created without the post save signal, it runs really fast. in fact when I populated the databe with just 20 members it was running fine but now I have 1168 members and it timeout everytime. How can I make it run faster. Models.py class PartnershipArm(models.Model): name = models.CharField(max_length = 128) slug = models.SlugField(unique = True, null=True, blank=True) partnershipRecords = models.ManyToManyField(Member, through = 'Partnership') def __str__(self): return self.name def get_absolute_url(self): return reverse('partnership-arms') class Partnership(models.Model): YEAR = [] for r in range((datetime.datetime.now().year), (datetime.datetime.now().year+10)): YEAR.append((r,r)) MONTHS = ( ('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'), ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'), ('November', 'November'), ('December', 'December'), ) member = models.ForeignKey(Member, on_delete=models.CASCADE) partnershipArm = models.ForeignKey(PartnershipArm, on_delete=models.CASCADE, db_index = True) year = models.IntegerField( choices=YEAR, default=datetime.datetime.now().year, db_index = True) month = models.CharField(max_length = 50, choices = MONTHS, null=True, blank=True, db_index = True) week1 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week2 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week3 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) week4 = models.DecimalField(max_digits=10, decimal_places=2, default = 0) total = models.DecimalField(max_digits=10, decimal_places=2, default = 0) def __str__(self): return "{0}_{1}_{2}_{3}".format(self.member, self.partnershipArm, self.year, self.month) def get_absolute_url(self): return reverse('partnership-arms') Signals.py … -
what do referencefield store in mongoengine
What do ReferenceField stores. I mean do it stores ObjectID (or in my case user_id, as it is primary_key for User model). class User(Document): user_id = IntField(primary_key=True) user_name = StringField(max_length=100) user_email = EmailField() class MasterUnit(Document): unit_id = IntField(primary_key=True) unit_name = StringField(max_length=100) unit_user = ReferenceField('User') I am usign POST method for posting data through my api: class MasterUnitList(View): def get(self, request): masterunit = MasterUnit.objects.all().to_json() data = json.loads(masterunit) return JsonResponse(data, safe=False) def post(self, request): data = json.loads(request.body) masterunit = MasterUnit(**data) masterunit.save() return JsonResponse(data, safe=False) My urls.py is path('api/unit', MasterUnitList.as_view(), name='MasterUnitList'), path('api/unit/<int:pk>', MasterUnitDetail.as_view(), name='MasterUnitDetail'), I am using httpie http POST http://127.0.0.1:8000/api/unit unit_id=1 unit_name="Nokia" unit_user="?" What do I pass in unit_user field? -
Changing Color in Django Forms
I want to change in my form the color of the label_suffix. I just want to set the '*' in red and leave the rest black. Is this possible or do i have to change something in my HTML? username = forms.CharField(label="Username",label_suffix='*') -
django DateField model -- unable to find the date differences
I'm unable to find the difference between two dates in my form. models.py: class Testing(models.Model): Planned_Start_Date = models.DateField() Planned_End_Date = models.DateField() Planned_Duration = models.IntegerField(default=Planned_Start_Date -Planned_End_Date) -
How to properly include a form with .save() in my view.py
I'm trying to create a new form in my form.py (AddressForm), but I get an error that says: local variable 'user_AddressForm' referenced before assignment Could someone give me a hand please? The username, password and image works fine, but the address form doesn't have persistent data and gives me the error in my forms.py file: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class AddressForm(forms.Form): address_1 = forms.CharField( label='Address', widget=forms.TextInput(attrs={'placeholder': '1234 Main St'}) ) address_2 = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'}) ) city = forms.CharField() state = forms.ChoiceField(choices=states) zip_code = forms.CharField(label='Zip') class Meta: model = User fields = ['address_1', 'address_2', 'city', 'state', 'zip_code'] in my views.py from django.shortcuts import render, redirect from django.contrib import messages # to display alert messages when the form data is valid from .forms import UserSignUpForm, UserUpdateForm, ProfileUpdateForm, AddressForm from django.contrib.auth.decorators import login_required from django.contrib.auth import update_session_auth_hash @login_required def profile(request): if request.method == 'POST': u_Passform = PasswordChangeForm(request.user, request.POST) if u_Passform.is_valid(): u_Passform.save() update_session_auth_hash(request, u_Passform) messages.success(request, f'Your password was updated successfully. Please log back in') return redirect('profile') u_form = UserUpdateForm(request.POST, instance=request.user) if u_form.is_valid: u_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): … -
Django Generated Timeslots Selector Required is Always true, How to add value>0
I have a booking system in which i enter dates and timeslots available to book. the form gets the timeslots from the date and converts it to the user timezone time. i want the client to select a date and an available timeslot before continuing the form but even with required it doesnt work. i have a model for timeslots and one for event, date+timeslot then a form to make client select available date+timeslot, with a html to find timeslot available for each day html <option value="">{% if time_slots %}Available Slots{% else %}No Slot Available{% endif %}</option> {% for time_set in time_slots %} <option value="{{ time_set.pk }}">{{ time_set.start }} - {{ time_set.end }}</option> {% endfor %} models class TimeSlots(models.Model): start = models.TimeField(null=True, blank=True) end = models.TimeField(null=True, blank=True) class Meta: ordering = ['start'] def __str__(self): return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p")) class Event(models.Model): event_date = models.DateField() start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True) available = models.BooleanField(default=True) class Meta: verbose_name = u'Event' verbose_name_plural = u'Event' def __str__(self): return str(self.event_date) def get_absolute_url(self): url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk]) return u'<a href="%s">%s</a>' % (url, str(self.start)) form class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', … -
Django crispy forms - Set hidden field value
I've got the following django crispy form: class ConsultForm(forms.ModelForm): # Template of Offer Cover Letter, Template of RIGHT OF FIRST REFUSAL class Meta: model = Consults # Your User model fields = [ 'TEMPLATE','EMAIL', 'DATE'] labels = { 'EMAIL' : 'Owner Email', 'DATE' : 'Todays date', # 'captcha': "Enter captcha" } helper = FormHelper() helper.form_method = 'POST' helper.form_action = "/contact/" helper.form_id = 'form' # SET THIS OR BOOTSTRAP JS AND VAL.JS WILL NOT WORK helper.add_input(Submit('Submit', 'Submit', css_class='btn-primary')) helper.layout = Layout( Field('TEMPLATE', type="hidden"), Field('DATE', type="hidden")) I want to pass a value with the hidden field TEMPLATE. I've read https://django-crispy-forms.readthedocs.io/en/latest/api_helpers.html , but can't see how to do this. How can I get this done? -
Django middleware redirect based on user agent
I'm trying to make redirect based on user agent. Right now I have in views.py: class IndexRedirectView(RedirectView): def get_redirect_url(self, *args, **kwargs): user_agent = get_user_agent(self.request) if user_agent.is_pc: return reverse_lazy("main:index") else: return reverse_lazy("main:mobile_index") I check the user agent only on main page, but I need to do this on any page (for any article page, for example) and redirect user to desktop or mobile version of the web-site. How to do it properly? Maybe, by writing own middleware like this: class UserAgentMiddleware(object): def process_request(self, request): if user_agent.is_pc: HttpResponseRedirect('desktop version') else: HttpResponseRedirect('mobile version') Thank you for your help and time! -
apache mod_wsgi + django on aws elasticbeanstalk, c extension modules
I host a django application, which uses various libraries such as numpy, PIL, opencv. After a few working requests (status code 200 OK), the server will crash. I see many errors like: Script timed out before returning headers: wsgi.py After a quick search, and according to this page: https://modwsgi.readthedocs.io/en/develop/user-guides/application-issues.html I think I should add this line: WSGIApplicationGroup %{GLOBAL} I don't quite understand what effect this line has. What is the meaning of "sub interpreters" in this context? The default elastic beanstalk configuration set processes=1 and threads=15. So how does more than one interpreter even exists? Does adding this line have any performance issues? What is the solution here? also specific to aws elasticbeanstalk config. -
name 'Class' is not defined error. Unable to use `Class` imported globally, inside a function
My code: reset.py from doclet.models import * from django.conf import settings from django.db.models import Count, Sum, Q, F from docsocket.utils import broadcast_data, get_bid_room from datetime import datetime from datetime import timedelta def delete_bids(): Bid.objects.all().delete() def delete_buzzers(): Buzzer.objects.all().delete() def delete_winner_data(): WinnerData.objects.all().delete() def reset_bids(): bids = Bid.objects.all() for bid in bids: bid.bid_data.all().delete() delete_winner_data() def set_bids_timing(set_time): bids = Bid.objects.all() for bid in bids: bid.start_date_time = set_time set_time = set_time + timedelta(hours=5) bid.is_active = True bid.is_won = False bid.save() bids[0].is_active=True bids[0].save() def reset_coin_transactions(): CoinTransaction.objects.all().delete() def reset_bonus_coin_transactions(): BonusCoinsTransaction.objects.all().delete() def reset_transactions(): Transaction.objects.all().delete() set_time = datetime.now() + timedelta(minutes=30) #delete_bids() set_bids_timing(set_time) reset_bids() delete_buzzers() #reset_coin_transactions() reset_bonus_coin_transactions() #reset_transactions() print("--done -") execution: python manage.py < shell < app/reset.py the error thrown is: NameError: name 'Bid' is not defined. Why? It works well when I run the code on Windows machine. But not on ubuntu. All the modules installed of the same version on both the machines. -
Difference between Model.function(self) and self.function()
Just a short beginner question. Everything is in the title. In a django model/python class is there any difference between Model.function(self) and self.function() when calling the function ?