Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript doesn't create cookies on django server hosted on digitalocean
I have deployed a django server with gunicorn and nginx on digitalocean. I have a cookie consent banner (created as a modal in bootstrap4) and a script which should create a cookie to remeber if you have accepted cookies already, so that the banner doesn't have to show again. JS if (document.cookie.indexOf("CookieBanner=") == -1) { $('#cookieModalCenter').modal('show'); var CookieAccept = document.querySelector("#cookieAccept"); CookieAccept.onclick = function(e) { var cookieDate = new Date(); cookieDate.setTime(new Date().getTime() + 31104000000); document.cookie = "CookieBanner = 1; path=/; secure; expires=" + cookieDate.toUTCString(); }; } What this script does, is it checks if the cookie has already been set and if not it shows the cookie consent banner. If you click on the button with id="cookieAccept" it saves your decision in a cookie. The code worked perfect in development, but now it shows the banner everytime you visit the website, and if I look in the storage with F12, I see that no cookie gets created. Why could this happen? -
Django config Multiple LDAP backend ,how to check logged user from Which LDAP server?
Emm like this ,is my login code from django.contrib.auth import authenticate usergo = authenticate(username=username, password=password) -
Django 2.1 bug? Apache returns template as string
I have updated my server from Django 2.0 to 2.1 and now I have a big issue. The server is responding but the output looks like a python string. If I inspect the code I get it as a python string: b' ... ' What could be wrong? -
What is default django salt? Where I can see it?
What is default Django salt? Where I can see it? I want to migrate to different framework, and can't get valid hash of my password -
Django models use id group as ForeignKey
I am developing one site and need to link table records to group id so I wrote my model for db but when I try to insert foreignkey i receive errors on makemigrations: (fields.E300) Field defines a relation with model 'Group', which is either not installed, or is abstract. and sito_boe.Boe.group_id: (fields.E307) The field sito_boe.Boe.group_id was declared with a lazy reference to 'sito_boe.group', but app 'sito_boe' doesn't provide model 'group' Here is my model. I just searched on web and documentation without luck, Anyone can help me? Here is my code: from django.contrib.auth.models import Group #Group.auth_group class Boe(models.Model): """Model representing an author.""" Name = models.CharField(max_length=100,verbose_name="Nome") Geo_POS = models.CharField(max_length=100,verbose_name="Coordinate") Luogo = models.TextField(verbose_name="Posizione") created_date = models.DateTimeField(default=timezone.now) #group_id = models.CharField(max_length=100,verbose_name="Gruppo") id_boa = models.CharField(max_length=20,unique=True,blank=False,verbose_name="Identificativo boa",help_text='Enter field boaXX') group_id = models.ForeignKey('Group.auth_group', on_delete=models.SET_NULL, null=True) def __str__(self): """String for representing the Model object.""" return self.Name class Meta: ordering = ['Name'] verbose_name_plural = "Boe" def get_absolute_url(self): """Returns the url to access a particular author instance.""" return reverse('listaboe', args=[str(self.id)]) -
Error with AWS S3 + Django, image uploads are stored as XML files in S3
I have uploaded image from Django backend to AWS S3 bucket, it is stored as XML file in AWS and when retrieving image files got error as below, This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>xxx</RequestId> <HostId>xxx</HostId> </Error> Configuration in Django settings.py as below, AWS_ACCESS_KEY_ID = 'xx' AWS_SECRET_ACCESS_KEY = 'xx' AWS_STORAGE_BUCKET_NAME = 'xx' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I have added 'storages' app in Django but did not add any configurations for that. -
Am I able to create a User instance by CBV rather than create a form first? (Django)
Now I used forms.py, models.py , views.py to create a User instance like below and it works: models.py: from django.db import models from django.contrib import auth from django.utils import timezone # Create your models here. class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) views.py: from django.shortcuts import render from django.views import generic from django.urls import reverse,reverse_lazy from . import forms, models from django.contrib.auth import get_user_model # Create your views here. class SignUp(generic.CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "accounts/signup.html" forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() # below code is not necessary, just want to customize the builtin attribtue of # the User class def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" However, I am wondering if I am possible to create a User by editing the views.py like below. views.py: from django.shortcuts import render from django.views import generic from django.urls import reverse,reverse_lazy from . import forms, models from django.contrib.auth import get_user_model # Create your views here. class SignUp(generic.CreateView): model = get_user_model() success_url = reverse_lazy("login") template_name = "accounts/signup.html" fields = ("username", "email","password1","password2") # below is original version # … -
Django Python: Save QR Code when saving model to Amazon S3
I have my Django app configured to upload media files to AWS S3, this works for my uploads fine, what I am trying to do though is generate and save a QR code using python qrcode, but I can't find a way to do this in the docs. It currently saves to Heroku static, which doesn't work as it's only temporary and I have multiple dynos. Here is my model so far: class Car(models.Model): make= models.ForeignKey(Make,on_delete=models.CASCADE) number = models.IntegerField() deleted = models.BooleanField(default=False) qrcode = models.ImageField(upload_to="qrcodes",blank=True,null=True) def save(self, *args, **kwargs): import qrcode qrcode_img = qrcode.make('https://myurl.com/?c=' + str(self.id) + '&make=' + str(self.make.id)) filepath = '/img/tmp/r' + str(self.make.id) + 't' + str(self.id) + '.png' filename = 'r' + str(self.make.id) + 't' + str(self.id) + '.png' buffered = BytesIO() qrcode_img.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() self.qrcode = img_str super(Table, self).save(*args, **kwargs) At the moment it is also ignoring the filename and filepath, only a string gets saved in my database whereas I want the file to upload to S3 and set the link to the file using the file path. Thank you -
Serialize ID and URL at the same time Django Rest Framework
I'm starting with DRF and i would like to serialize both ID and Hyperlinked URL at the same time. Let me define a simple example model: class Account(model.Models): name = models.CharField(max_length=100) active = models.BooleanField() I know that there is a ModelSerializer which represents the object as follows: { "id": 1, "name": "library", "active": true } And there is as well an HyperlinkedModelSerializer which represents the object as follows: { "url": "http://127.0.0.1:8000/core/accounts/1/", "name": "library", "active": true } Intrinsically in the HyperlinkedModelSerializer we can retrieve the row's ID, but what I'm looking for is to get something like this: { "id": 1, "url": "http://127.0.0.1:8000/core/accounts/1/", "name": "library", "active": true } -
Reloading django-flatpickr wiget in a dynamic formset using jquery
In my Django app I have used jQuery to dynamically add new forms to my formsets, using the solution provided by Paolo Bergantino to this question: Dynamically adding a form to a Django formset with Ajax When I add a new form, the pypi django-flatpickr date widget that I have specified to be used for the date input fields in my form: https://pypi.org/project/django-flatpickr/, does not load. Dates cannot be selected and the form cannot be submitted. For reference, the django-flatpickr widget requires the {{ form.media }} tag to be added to the html to render the widget. The tag adds all flatpickr JS/CSS files from CDN. Is there a way of reloading the widget media when clicking the add-form button? I would appreciate any help and advice. Here is my code: forms.py from flatpickr import DatePickerInput ReagentFormset = modelformset_factory( Reagent, fields=('reagent', 'lot_number', 'open_date', 'expiry_date'), extra=1, widgets={ 'open_date': DatePickerInput(), 'expiry_date': DatePickerInput(), } ) Template including js to dynamically add new forms: {% block content %} <div> <h2><strong>Add Reagent Details</strong></h2> <form action="" method="post"> {% csrf_token %} <table class = "table table-striped"> <thead> <tr> <th>Reagent</th> <th>Lot number</th> <th>Open date</th> <th>Expiry date</th> </tr> </thead> <tbody> {{ formset.management_form }} {% for form in formset %} … -
Django: Local variable being picked up as class attribute when using 'Q' Querying
Problem I'm trying to perform 'Q' based querying on a selected Model. I'm receiving the following error, however django appears to pick a local variable up as an attribute of the model. Error AttributeError: 'KanbanBooking' object has no attribute 'week_commencing' View now = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()) week_commencing = now - datetime.timedelta(days=now.weekday()) bookings = KanbanBookingModel.objects.filter(Q(commence_date__gte=week_commencing, commence_date__lte=week_commencing+datetime.timedelta(days=6)), Q(test_cell=cell, status__in=['Allocated','Unallocated','Booked','Processing','Complete'])).order_by('kanban_board_id','kanban_item_position') -
Django Database Not Retrieving The Values Of Drop Down Field's From Site Form?
So I basically have a form in my website. The form fields are only drop-down fields. No text-fields, etc. Once the user fill's in the form and clicks submit, the drop-down values which the user selected are being printed properly in my Command-Prompt as I expect them to come because I first print them in cmd to make sure I am really getting the output which the user entered through the form. The form has 5 drop-down fields. The form is shown to the user in their profile page. Now the problem is that I have created a model in models.py file, which creates the same drop down in the Django database as the form in site. So that I can keep a record of who chose which option. There are 5 drop downs in the database model as well. But when I click on the object model in the database, it shows the drop-down's but the default values of them are not what the user submitted through the site form. The default values of them are just "----" and if I click on the drop-down, then I see the other options as well but the default value of them … -
RuntimeWarning: DateTimeField received a naive datetime while time zone support is active
Here I am writing a middleware to delete objects older than 3 months. The date_before_2_month and datetime_before_2_months is working fine. I haven't tested yet for filtering But in my console it is giving me a runtime warning saying activity_time received a naive datetime. Is this warning a issue(needs to solve) or we can ignore it ? Also does my filter parameters are good for querying the objects from model which are 2 months old ? activity_time in model is DateTimeField(auto_now_add=True) class UserActivityLogDeleteMiddleware(object): # middleware for deleting user activity logs which are older than 2 months def __init__(self, get_response): self.get_response = get_response def __call__(self, request): date_before_2_month = datetime.date.today() - relativedelta(months=2) # converting into datetime datetime_before_2_month = datetime.datetime.combine(date_before_2_month, datetime.time(9, 00, 00)) # deleting logs older than 2 months UserActivityLog.objects.filter(activity_time__lt=datetime_before_2_month).delete() response = self.get_response(request) return response -
Django Excel File Uplaod
views.py def simple_upload(request): if request.method == 'POST': ingredients_resource = IngredientsReource() dataset = Dataset() new_ingredients = request.FILES['myfile'] if not new_ingredients.name.endswith('xlsx'): messages.info(request, 'wrong format') return render(request, 'upload.html') imported_data = dataset.load(new_ingredients.read(),format='xlsx') for data in imported_data: value = Ingredients( data[0], data[1], data[2], data[3] ) value.save() return render(request, 'upload.html') upload.html {% extends 'base.html' %} {% block content %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" role="alert"> <p>{% if message.tags %} {% endif %}{{ message }}</p> </div> {% endfor %} {% endif %} <!DOCTYPE html> <html> <center> <head> <h2>Please Upload Excel file</h2> </head> <body> </body> </html> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit"> Upload</button> </form> </body> </center> {% endblock %} resources.py from import_export import resources from .models import Ingredients class IngredientsReource(resources.ModelResource): class meta: model = Ingredients I'm trying to create a function to upload my excel files to Django admin database. My function is working totally fine however there's a little problem in my html file when I click on upload without choosing a file it gives me MultiValueDictKeyError at /upload/'myfile' error . Instead of this error I want my function to give me "choose a file first " warning. -
Django migration command hanging on Heroku even without actual new migration
We are running our stack on Heroku. We are using Django 2.2 with a Postgres 11 DB. Our build pipeline (Github Actions) pushes to Heroku (git push https://git.heroku.com...) and immediately afterwards runs the migrations (heroku run python manage.py migrate --app heroku-app-name). All of that was working with a Postgres 9.6 database and is still working in our staging environment (Postgres 11). Now with production being on Postgres 11, the django migrate command is just stuck and doesn't produce any output, even so there are no actual migrations to apply. The only differences between our production setup and our staging setup are a follower/slave in production attached to the master DB and "production workload". In order to fix that deployment I have to run a heroku pg:killall -a heroku-app-name heroku restart -a heroku-app-name At this point the migrations task in the build pipeline fails. and afterwards migrations can be applied manually without problems: heroku run python manage.py migrate --app heroku-app-name So for some reason the migrations command is "waiting" for something, some database lock or whatever, yet I cannot put my finger on it. Especially odd for me is the fact that its also stuck where no migrations are to applied. … -
Django forms cleaned
When I click on save button, my form also saves the html elements. My form looks like this: class ProductPropertyForm(forms.ModelForm): class Meta: model = ProductProperty fields = ('name', ) For example if my text is "My input text". The form saves that in the database: "My input text" What would be the solution for this? -
Permission for fields value wagdail
I want to create a permission which will show different values in the field for different groups. @register_snippet class VideoCategory(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class Meta: verbose_name = "Video Category" verbose_name_plural = "Video Categories" ordering = ["name"] class VideoPage(Page): video = EmbedVideoField(default=False) categories = ParentalManyToManyField('video.VideoCategory', blank=True) At the moment all groups see all the categories added as snippet. I would like to have a list of values added as categories snippets but show specific set, in the admin, of them for each user group, is that possible? -
How to solve AWS Elastic Beanstalk error : 100.0 % of the requests are failing with HTTP 5xx
So I tried to deploy my Django project to EB, but keep on getting the health as "Sever" with this error : - 100.0 % of the requests are failing with HTTP 5xx. - Process default has been unhealthy for 1 hour 19 minutes (Target.ResponseCodeMismatch). - Following services are not running: web. When I click the URL of the environment, I get an error saying "502 Bad Gateway : nginx/1.16.1". Also I'm using python 3.7. I'm not sure if this information is sufficient, so please do let me know if you need any further information. Or could it possibly be a DB error? -
Django & Apache on EC2 Linux 2 Hello World
What am I missing? This is my first time trying to use Django. The server that is built into Django will serve the file locally just fine, but I can't get Apache to do the same. The following is what I'm doing from a brand new, clean, Linux 2 instance. sudo yum update sudo yum install -y python3 sudo yum install httpd-devel sudo yum install -y mod_wsgi cd /etc/httpd/modules (verify that mod_wsgi is there) cd /var/www/ sudo mkdir myApp sudo chown ec2-user myApp cd myApp sudo pip3 install virtualenv virtualenv myprojectenv source myprojectenv/bin/activate sudo pip3 install django==2.1.1 django-admin startproject myApp cd myApp python manage.py migrate python manage.py runserver wget http://127.0.0.1:8000/ (works correctly as it should and I receive test page) python manage.py startapp hello cd myApp vim settings.py settings.py: edit this part to look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello.apps.HelloConfig', ] . vim urls.py urls.py: entire file looks like this: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello.urls')), ] . cd .. cd hello vim views.py views.py: entire file looks like this from django.shortcuts import render # Create your views here. # hello/views.py from django.http import … -
Rest API . Help to change ListView
I have some error with Rest API when started Django project. The error is "raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'api.urls' from '/Users/luba/code/library/library_project/api/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." My code: api/views.py from rest_framework import generics from books.models import Book from .serializers import BookSerializer class BookAPIView(generics.ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializer api/urls.py from django.urls import path from .views import BookAPIView urlpattens = [ path('', BookAPIView.as_view()), ] api/serializers.py from rest_framework import serializers from books.models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'subtitle', 'author', 'isbn') books/views.py from django.urls import path from .views import BookListView urlpatterns = [ path('', BookListView.as_view(), name='home'), ] books/views.py from django.views.generic import ListView from .models import Book class BookListView(ListView): model = Book template_name = 'book_list.html' Somebody can explain, in which staff problem with my code.Will be appreciate!!!! -
Django how to receive User object from form input?
I have a custom PasswordResetForm where I need to get the user object from the forms input CharField but sadly I'm not able to successfully accomplish the lookup for the User object: AttributeError: 'PasswordResetForm' object has no attribute 'user' forms.py: class PasswordResetForm(forms.Form): user = forms.CharField(required=True) ... new_password1 = forms.CharField( label=_("New password"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) ... def save(self, commit=True): """Save the new password.""" form_user = self.cleaned_data.get('user') user = User.objects.exclude(pk=self.instance.pk).get(user=form_user) password = self.cleaned_data["new_password1"] user.set_password(password) if commit: user.save() return self.user models.py: class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.CharField(verbose_name='Username', max_length=15, unique=True) ... The line I'm referring to is "user = User.objects.exclude(pk=self.instance.pk).get(user=form_user)" which seems to be wrong here. Can smb. give me a hint how my query has to look like in order to get the User Object by the CharField input? -
Django : How to distinct by DateTimeField with ignoring the second / millisecond difference
In Django, i have a model that look like this: class Foo(models.Model): ... created = models.DateTimeField(default=None) ... And I try to query like: q = Foo.objects.values('created').distinct() So far everything is great. The problem is, if I have records created by a few seconds or milliseconds apart, I want to count them as one record. So only queries created over a minute apart will be retrieved as two separate queries. How to do it? Thanks. -
How to get data from logged users in views.py? (Django social-auth-app-django)
I've successfully logged in my facebook account using Social-Auth-App-Django. Now I need to get my user ID so that I can filter the database using the user's ID but I don't have any idea how to do it. In django template it looks like this {{ user.id }} but I don't know how to get it in views.py Here's my template code for loggin into facebook <a href="{% url 'social:begin' 'facebook' %}" class='btn'> <img src="/static/img/facebook.png" alt=""> Login with Facebook </a> And here's my code in views.py @login_required def home(request): items = Products.objects.filter(product_owner__id=user_id) return render(request, 'seller.html', { "items": items }) user_id is what I actually need. Thanks in advance! -
Python/Django: Subtracting Decimals returns Tuple - why?
In one of my Django Views I am trying to deduct a Decimal from another Decimal as shown below: total_lastyear = Decimal('28418.43227999999980000000000') total_exccy_lastyear = Decimal('25964.96153000001000000000000') ccyeffect_lastyear = total_lastyear - total_exccy_lastyear I expexted to get Decimal('2453.47074999998980000000000') as result but instead i got a tuple (Decimal('2453.47074999998980000000000'),) . I did the same calculation in a Jupyter Notebook and I got the expected Decimal as a result. Does anyone know why this is happening in Django and how I need to change the calculaton in Django to get a Decimal result? -
Unable to install pycurl==7.43.0.5 on AWS Elastic Beanstalk
Hi guys I have been trying to add pycurl on EB running with python 3.7 however when I try to launch my celery app it returns the following errors: "The curl client requires the pycurl library" the command that is being executed is: celery -A sportspot worker -B [2020-06-23 07:36:14,815: CRITICAL/MainProcess] Unrecoverable error: ImportError('The curl client requires the pycurl library.') 2020-06-23 07:36:16,508 P8649 [INFO] Traceback (most recent call last): 2020-06-23 07:36:16,508 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/kombu/asynchronous/http/__init__.py", line 20, in get_client 2020-06-23 07:36:16,508 P8649 [INFO] return hub._current_http_client 2020-06-23 07:36:16,508 P8649 [INFO] AttributeError: 'Hub' object has no attribute '_current_http_client' 2020-06-23 07:36:16,508 P8649 [INFO] 2020-06-23 07:36:16,508 P8649 [INFO] During handling of the above exception, another exception occurred: 2020-06-23 07:36:16,508 P8649 [INFO] 2020-06-23 07:36:16,508 P8649 [INFO] Traceback (most recent call last): 2020-06-23 07:36:16,508 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/worker/worker.py", line 208, in start 2020-06-23 07:36:16,508 P8649 [INFO] self.blueprint.start(self) 2020-06-23 07:36:16,508 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start 2020-06-23 07:36:16,508 P8649 [INFO] step.start(parent) 2020-06-23 07:36:16,508 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/bootsteps.py", line 369, in start 2020-06-23 07:36:16,508 P8649 [INFO] return self.obj.start() 2020-06-23 07:36:16,508 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 318, in start 2020-06-23 07:36:16,509 P8649 [INFO] blueprint.start(self) 2020-06-23 07:36:16,509 P8649 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start 2020-06-23 07:36:16,509 P8649 …