Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add dynamic data in a demo chart.js file of a django template
I'm using the "start bootstrap4" template for my Django project. I want to edit my own data in the sample chart. I need to change it in the chart-pie-demo.js file I used gspread and pandas to convert my google sheet into a list of dictionaries. My google sheet is shown as the following list: (It's a very long list, so I only list a few lines) mylist= [{'StartDate': '2021-10-02', 'ID': 11773, 'Name': Mike, 'Days':66 }, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 95453, 'Name': Jane, 'Days':65}, {'StartDate': '2021-10-03', 'ID': 15673, 'Name': Mike, 'Days':65}, ... {'StartDate': '2021-10-5', 'ID': 34653, 'Name': Jack, 'Days':63}] The above list is defined in my views.py My chart-pie-demo.js file: var ctx = document.getElementById("myPieChart"); var myPieChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Direct", "Referral", "Social"], datasets: [{ data: [55, 30, 15], backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc'], hoverBackgroundColor: ['#2e59d9', '#17a673', '#2c9faf'], hoverBorderColor: "rgba(234, 236, 244, 1)", }], }, options: { maintainAspectRatio: false, tooltips: { backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, caretPadding: 10, }, legend: { display: false }, cutoutPercentage: 80, }, }); I want to count the number of rows that has "Mike" in name, the … -
Django DateField ordering logic in case of equal DateField values
I'm trying to understand what is the ordering logic of django of DateField in case the dates are equal? I've got a model that has a DateField and DateTimeField (irrelevant fields taken out). class Ad(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateField(default=timezone.now) created_time = models.DateTimeField(default=timezone.now) The ordering for the model is as such: class Meta: ordering = ['-created_time', '-created_at'] Note that previously I didnt have the created_time = models.DateTimeField(default=timezone.now) at all and sorted only via -created_at. I added the additional DateTimeField just for testing purposes and it didnt affect the outcome of the DateField ordering in any way. Here you can see the order how the objects were created in DB: And this is the order how the objects are actually ordered on the ListView page: The slug field in DB can be used as reference in order to understand which object in the template corresponds to which object in the DB. As you can see the first DateTimeField order works as expected, however the ordering by DateField is not the same as the order in the DB. What is more interesting that if I will go to my UpdateView and update the "Summernote" objects content (not messing … -
Internal server error when deployed django project to heroku
I am getting a Internal service error after I had uploaded my project and deployed using heroku . I have tried a lot of times to upload it and it is not working and I don't know why it is so . I am a beginner in django. Please help me . this is my build log after the project was deployed -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.10 To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Using cached install of python-3.9.10 -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory '/tmp/build_4274e684/static' in the STATICFILES_DIRS setting does not exist. 128 static files copied to '/tmp/build_4274e684/staticfiles', 20 unmodified. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 90.4M -----> Launching... Released v12 https://blogging-site-dev.herokuapp.com/ deployed to Heroku this is my setttings.py """ Django settings for bloggingsite project. Generated by 'django-admin startproject' using Django 3.2.2. … -
How to view message created when API request submited in admin view django
I want messages to be shown when a POST method is called (from another source). How can I do that using the messages framework django? I tried using templates and calling the view from the api view but nothing works. I can only log the messages but not view them because I dont have the proper "request". Is there a way to view messages when there is no request specified? Should I maybe use django.shortcuts render? My admin view that handles form: (admin.py) class AdminView(admin.ModelAdmin) [...] And API view that handles the request: (views/api.py) def create(self, request, pk=None): json_data = json.loads(request.body) if json_data['status'] == 201: messages.warning(request ,"test message") return Response(json_data['body'], status = status.HTTP_201_CREATED) So when another source calls POST method (i'm sure it works. The only thing that does not is the messages), I want the admin view to show the message. urls: url(r'^invoices/(?P<pk>[0-9]+)/$', views.InvoiceDetail.as_view(), name='invoice-detail'), base.html: {% block messages %} {% if messages %} <ul class="messagelist">{% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> {% endfor %}</ul> {% endif %} {% endblock messages %} Messages are set just like it is said in https://docs.djangoproject.com/en/4.0/ref/contrib/messages/#module-django.contrib.messages And they work, because I have also … -
Django why getting MultiValueDictKeyError?
here is my code: if request.method == "POST": forms = GoogleAuthFroms(request.POST or None) if forms.is_valid(): code = request.POST["auth_code"] context = { 'forms':forms, } return render(request,'members/security.html',context) This line of code code = request.POST["auth_code"] throwing this error MultiValueDictKeyError at /security/ 'auth_code' -
django_filters recursive filtering
so I have a django filter that looks like this: class ModelFilter(FilterSet): user_name = CharFilter(method="some_method") boss = ModelChoiceFilter(...) My model looks simillar to this: class Employee(Model): username = Charfield(...) boss = ForeignKey("self", ''') So an employee can be the boss of another employee. Now, this filter will return the correct queryset based on what values the user is searching for. Let's say we have three objects: O1= Employee(usename="u1", boss=None) O2= Employee(usename="u2", boss=O1) O3= Employee(usename="u3", boss=O2) If I apply the above mentioned filter on this data, and search for boss=O1 I will get the Object O2 as a result. I want to add a new boolean field in the filter, let's say "with_subordinates", that will return the whole "tree" relationship if it is true. So for instance if I would search for: boss=O1, with_subordinates=True, the resulte should be O2 and O3. Basically, with this new option, the filter should recursively show the employees, of previous employees and so forth. Is there a way to achieve something like this? -
Blocking access to html page while user edits
I have a Django web app for booking golf competition times for members. Once logged in, all users have ability to edit player names for each time. These are then manually reset for the following week after the competition. The issue is if more than 1 user edits at the same time, it will save last instance and others will not realize. I have the list of times, (with 4 name slots each), on one html page with an edit button for each time, which leads to a separate html page for editing those 4 names. Is there anyway of blocking a html page once opened by 1 user? Or a thought I had was to create a button next to "Edit", which changes color and text, (green to red, and "Open" to "Edit in progress" for example), for a set period or until "save" button clicked on update page. Here is the relevant code- Models.py class Post(models.Model): time=models.CharField(max_length=50) player1=models.CharField(max_length=50, default="Player 1") player2=models.CharField(max_length=50, default="Player 2") player3=models.CharField(max_length=50, default="Player 3") player4=models.CharField(max_length=50, default="Player 4") def __str__(self): return self.time Views.py def teetimes(request): posts=Post.objects.all() name=CompNames.objects.get(id=1) return render(request, 'memtees/teetimes.html', {'posts':posts, 'name':name}) def add(request): if request.method=='POST': time=request.POST['time'] player1=request.POST['player1'] player2=request.POST['player2'] player3=request.POST['player3'] player4=request.POST['player4'] Post.objects.create(time=time,player1=player1,player2=player2,player3=player3,player4=player4) messages.success(request,'New Time has been added') … -
how to convert string into RSA privatekey python
i'm building a django social media app, and i'm trying to achieve end-to-end encryption, by using rsa keys. when a user signs up an RSA publickey/privatekey is generated then the private key is symmetrically encrypted and stored in the database. the problem with this when i retrieve the private key it's type is str, which the module rsa can't read. the original type when it was generated was rsa.key.PrivateKey here is a snippet from models.py: class Post(models.Model): privatekey = models.BinaryField() publickey = models.BinaryField() and the signup view: def register(request): if request.method == 'POST': form = UserRegister(request.POST) ver = verification(request.POST) if form.is_valid() and ver.is_valid(): form.username = request.POST.get('username') form.password1 = request.POST.get('password1') form.password2 = request.POST.get('password2') try: form.save() except: messages.warning(request, f'there is an error') return render(request, 'users/register.html', {"form": form}) username = form.cleaned_data.get('username') new_user = authenticate(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],) login(request, new_user) publickey, privatekey = rsa.newkeys(2048) profile = request.user.profile profile.publickey = publickey password = request.POST.get('password1') profile.privatekey = encryption_decryption(str(privatekey), password, 'e') profile.save() response = redirect('complete-profile') privkey = encryption_decryption(request.user.profile.privatekey, password, 'd') response.set_cookie('key', privkey, max_age=None) return response else: form = UserRegister() ver = verification() return render(request, 'users/register.html', {"form": form, 'ver': ver,}) the type problem is in th encryption_decryption function, it's responsible for encryptingthe private key and restoring it (decrypting it) when the … -
Best way to pass the logged in user to the backend in Django
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template? For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in Currently, I manage the My account page as below. navbar.html {% if user.is_authenticated %} <li class=""> <a href="{% url 'account' %}"> <i class='bx bxs-user-detail icon' ></i> <span class="text nav-text">My profile</span> </a> </li> urls.py from django.urls import path, include from . import views urlpatterns = [ path('account', views.account_user, name="account"), ] -
How to improve Django REST response processing time?
In a Django/DRF project, I am trying to improve the performance of an API endpoint that takes in a JSON file and creates model objects in the database from it. This JSON can be very large, spamming hundreds or thousands of entries. The view is using DRF's ViewSet class as the base. I wrote a unit test with a fixture with around 800+ entries (so 800+ model objects) to investigate potential bottlenecks in the flow. By timing a few steps that I thought would be critical I found this: 1) Time to create: 37.771371603012085 2) Time to check objects errors: 52.56421709060669 3) Time to create response: 0.499253511428833 4) Time Django processing response: 81.24804949760437 Time taken: 172.08289170265198 I can't use bulk_create because of multi-table inheritance This is calling full_clean() on each object Serialization of objects is irrelevant After my function return Response(...), all this time is spent on Django's backend How can I improve step 4? I don't understand what takes so long to process the response and spit it back out. -
django web site URLS gets "?next=" randomly after deployed to heroku
after deploying django app on heroku the url after every form submittion or link in site been press resulting with "?next=" inserts into the URL address, i dont understand from where it comes and why heroku keep inserting them in a random way, running the application localy just working perfectly. i've deleted the application from heroku and upload it again, the fault persists. there's no http errors what so ever. if i keep submiting the form eventually will works. for example: pressing the log button in the django admin console results with this URL: https://appname.herokuapp.com/admin/login/?next=/admin/login/admin/, hitting it quite a bit will finnaly make it work with the correct url display: https://mishnayot.herokuapp.com/admin/. switching from heroku postgres to AWS RDS postgres didn't help. help will be very appreciated. -
how to add manytomany fields to filter search in django
I have written a search API for my website in django rest framework. It's an API in which you can set some parameters in the url and get a search result. what I need is to be able to search by genre. What it means is I need the API to be able to do a search like /api/search/?search=1&search_fields=filmGenre. but write now if I send a request to this url I get a FieldKey error with the following message: Related Field got invalid lookup: icontains here is my code: # models.py class Film(models.Model): filmID = models.AutoField(primary_key=True) title = models.CharField(max_length=150) duration = models.PositiveIntegerField() typeOf = models.IntegerField(validators=[MaxValueValidator(3), MinValueValidator(1),]) rating = models.FloatField(default=0, validators=[MaxValueValidator(10), MinValueValidator(0),]) releaseDate = models.DateTimeField(null=True) filmGenre = models.ManyToManyField(Genre) class Genre(models.Model): genreID = models.AutoField(primary_key=True) nameOf = models.CharField(max_length=100, unique=True) # serializers.py class FilmSerializer(serializers.ModelSerializer): class GenreFilmSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('nameOf', 'genreID',) read_only_fields = ('nameOf', 'genreID',) class CelebrityFilmSerializer(serializers.ModelSerializer): class Meta: model = Celebrity fields = ('nameOf', 'celebID',) read_only_fields = ('nameOf', 'celebID',) filmGenre = GenreFilmSerializer(read_only=True, many=True) filmActor = CelebrityFilmSerializer(read_only=True, many=True) filmDirector = CelebrityFilmSerializer(read_only=True, many=True) class Meta: model = Film fields = [ "filmID", "title", "price", "duration", "typeOf", "numberOfFilminoRatings", "filminoRating", "rating", "releaseDate", "detailsEn", "salePercentage", "saleExpiration", "posterURL", "posterDirectory", 'filmGenre', 'filmActor', 'filmDirector' ] # views.py … -
Encrypt Django project
I have a project (django) running in our office in server. There are some people who have access in server. But I want to do something so that other people (who have access in server) can not read, or write, or edit, or do anything in my project (django)'s source code. Server is running using Ubuntu OS. -
django.db.utils.ProgrammingError: column accounts_account.username does not exist
I am getting this error after I was customizing my Customer User Model. and now I get this error when I try to login into the admin panel and when I try to create a superuser. I tried to drop the postgresql database called skincareryland... but am getting an error on the password login... when I try to change the password I get this error.. ERROR: role "postgres" does not exist I also tried going through these steps from an overstack post, but not having any luck fixing the problem... Comment out 'django.contrib.admin' from INSTALLED_APPS in settings.py and comment out # path('admin/', admin.site.urls) in urls.py execute commands: Python manage.py makemigrations appname Python manage.py migrate appname add 'django.contrib.admin' to INSTALLED_APPS in settings.py file and path('admin/', admin.site.urls) in urls.py execute commands again: Python manage.py makemigrations appname Python manage.py migrate appname from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, first_name, last_name, username, email, password=None): if not email: raise ValueError('User must have an email address') if not username: raise ValueError('User must have an username') user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, … -
DoesNotExist at / AllocationDetail matching query does not exist
I know there are a number of questions already on stack overflow related to this issue and I have read them all, but still I am having no success with this issue. I am hoping somebody can help me out with this. C:\Users\Ravokid\Desktop\E-Fund_2\users\views.py, line 73, in home 'money_per_ward' : get_money_per_ward(), C:\Users\Ravokid\Desktop\E-Fund_2\accounting\views.py, line 17, in get_money_per_ward obj = accounting_models.AllocationDetail.objects.all().get(financial_year__start_date=datetime.date.today().year, financial_year__end_date=datetime.date.today().year+1) -
How do I used the map in django
I need for your helps plz.. I need to show heatmap plot to the page by Django in the views heat = sns.heatmap(mcor, annot=True) heat = plt.show() in the page Heat Map{{heat|safe}} but the reslut show the map out the page (new tap) as like image what's problem ? -
django loginview csrftoken fobidden error
I'd like to ask you a question about the Loginview of Django. I'm using the Loginview as it is. There's a problem, but I'll open two browser tabs and leave them open as login pages (the same browser ) When I log in first from one browser tab and log in from another browser tab (both are the same browser), the csrf_token error appears, which is 403 Forbidden error! The way I want to do it is to log in without errors even if I log in from another browser tab if I'm already logged in from one browser tab. Also, I'm trying to solve it using Ajax, but I'm not familiar with it, so I'm having a hard time solving the problem. How should I solve this? -
REST framework's FileField: How can I force using TemporaryUploadedFile
I want to extract and process text from a text document uploaded by the user without actually saving the document. I use Django's REST framework and I want this to happen in the serializer. I get the document from a FileField. Because the text document is likely to be small, it will be wrapped into InMemoryUploadedFile automatically. However, text-extraction modules (e.g. docx2python) need to open files from paths, not from memory. How can I turn an InMemoryUploadedFile into a TemporaryUploadedFile, so I can get a path I use? Or how do I force a particular field (without changing the app settings) to always wrap a file in TemporaryUploadedFile? -
CSRF validation does not work on Django While entegrating with reactjs
even after adding CSRF_TRUSTED_ORIGINS there is an error while post request Origin checking failed - (website name) does not match any trusted origins. -
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view in Django RestFramework
I'm trying to return a response after the execution of loop but I'm getting an error as AssertionError at Data/CurrentRunningActivityForAudit/10 Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` when I added another return response outside the loop it shows the empty array i.e.,.[ ] it's returning empty response ` views.py: def CurrentRunningActivity(UserID): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set = cursor.fetchall() IsActive = 'true' for row in result_set: data = [] data.append({ 'TaskId':row[0], 'TaskName' : row[1], 'Source' : row[2], 'Requester' : row[3], 'type' : row[4], 'IsActive':IsActive, }) return Response(data[0], status=status.HTTP_200_OK) when I move the return response outside the loop it shows as local variable 'data' referenced before assignment -
Filter into Foreign Keys on Django-Rest Datatables
I have a datatable for Order model which contains some fields from User model and is implemented using serializer as following serializers.py # customer order detail serializer class CustomerOrderSerializer(serializers.ModelSerializer): first_name = serializers.ReadOnlyField(source='user.first_name') last_name = serializers.ReadOnlyField(source='user.last_name') def __init__(self, *args, **kwargs): remove_fields = kwargs.pop('remove_fields', None) super(CustomerOrderSerializer, self).__init__(*args, **kwargs) if remove_fields: for field_name in remove_fields: self.fields.pop(field_name) class Meta: model = Order fields = ['id', 'amount', 'order_status', 'created', 'first_name', 'last_name'] read_only_fields = ['issue_date', 'first_name', 'last_name'] In views.py class OrderList(generics.ListAPIView): queryset = Order.objects.order_by('-created') serializer_class = CustomerOrderSerializer I am successfully able to get first_name & last_name fields as in datatable format as shown However, my requirements is to filter/search in datatable on fields first_name & last_name which are from different model User when I try to filter on those fields I get Following error: Cannot resolve keyword 'first_name' into field. Choices are: ..., .., ..., .. Can anyone help me understand, How we can filter on foreign key fields in django-rest datatables -
How to use multiprocessing with Django to create thousands of objects from JSON?
I have an API endpoint on Django REST that accepts a .json file and does some computing on the data to create some "profiles", then does some error and validation checks, and finally returns the response of fail if something went wrong. This json file can be very large, which slows down the process. I can't use Django's bulk_create because the model is an inherited model and bulk create doesn't work in this case. So I am trying to use Python's multiprocessing (correct me if this is not the best approach) to create the model instances and then save in batches. It goes like this: Viewset: create() calls the utils function to loop through the objects in the json file For each object another function actually_create where the model is instantiated These objects are saved in a list (batch) The batches are saved inside a transaction block Even though I have used the same approach for other use cases, I can't get it to work and I don't know why because the traceback is not helpful and I can't set breakpoints when doing multiprocessing. Traceback: Traceback (most recent call last): File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/home/everton/.virtualenvs/venv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", … -
Python Django: How to prevent form field from clearing?
I am working with Python Django and I have this really simple form, consisting of a button and an input field. The problem is that the input field is for some reason cleared after I submit the form. So How can I prevent it from clearing? This is my python file: def index(request): # print(f"its me {os.getcwd()}") txt = request.GET.get("some_txt") if (request.GET.get('mybtn')): print(f"THIS IS THE TEXT VALUE: {txt}") else: print("Has not been clicked") return render(request, "main/index.html") This is the HTML file: <form action="#" method="get"> {% csrf_token %} <input type="text" name="some_txt"> <button type="submit" class="btn btn-primary" value="mybtn" name="mybtn">Submit</button> </form> -
Django JSONField data with integer keys
I want to save a model instance with JSON dict with integer keys, like {2: 3}. But after saving my dict turns into {"2": 3}. Is there any way to save integer keys into JSON? class MyModel(models.Model): data = JSONField("data") record = MyModel.objects.create( data={2: 3}, ) record.refresh_from_db() print(record.data) # > {"2": 3} # And I want record.data == {2: 3} Behavior same for from django.contrib.postgres.fields import JSONField and for modern from django.db.models import JSONField -
Django Complex Association Annotation including Count & Sum
I have the following Django query: queryset = queryset.values( 'ticket_owner_email_address' ).order_by( 'ticket_owner_email_address' ).annotate( ticket_quantity_total=Count('ticket_associated_quantity'), ticket_price_total=Sum('ticket_price') ).values( 'ticket_quantity_total', 'ticket_price_total', 'ticket_owner_email_address' ) which essentially does a lookup on a particular model (Booking) by the 'ticket_owner_email_address'. For each "ticket_owner_email_address" I want to a lookup back on the Booking, but returning fields "some_field" and "some_other_field". Both of these fields can be the same for multiple bookings. As I am doing the Count and Sum, if I try to add these two values to the list, they're either empty or they break the counting / summation commands. I was wondering, what is the best Query expression method for inserting these associated values for the ticket_owner_email_address? I have tried a Subquery with an OuterRef, but unfortunately that doesn't seem to be working (I essentially haven't set it up correctly). Any pro Django ORM tips would be greatly appreciated!