Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF: nested Serializer error on create argument after ** must be a mapping, not str
I have a model that connects a school model and a user model through a foreign key, and on creating if a student is being created I want the user foreign key to be set as the instance and also a school to be chosen by its id however i can't solve this error TypeError at /api/users/student_register/ django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str class User(AbstractBaseUser, PermissionsMixin): .... email = models.EmailField( is_superuser = models.BooleanField(default=False) last_login = models.DateTimeField( _("last login"), auto_now=True, auto_now_add=False) class School(models.Model): PROVINCE = ( ... ) SCHOOLTYPE = ( .... ) name = models.CharField(_("Name"), max_length=150, blank=False, null=True) abbr = models.CharField( _("Abbrivation"), max_length=10, blank=False, null=True) zone = models.CharField( _("Zone"), max_length=50, choices=PROVINCE) Schooltype = models.CharField( _("School type"), max_length=50, choices=SCHOOLTYPE) schoolemail = models.EmailField( _("School email"), max_length=254, blank=False, null=True) editable=False) def __str__(self): return self.name this applied model is what is connecting the user and the student model together and it is what i am using though the nested serializer to create the users class Applied(models.Model): class TYPES(models.TextChoices): STUDENT = "STUDENT", "Student" WORKER = "WORKER", "Worker" type = models.CharField(_("type"), choices=TYPES.choices, max_length=150, blank=False, null=True) user = models.ForeignKey(User, verbose_name=_( "useris"), related_name='useris', on_delete=models.PROTECT, blank=True, null=True) school = models.ForeignKey(School, verbose_name=_( 'school'), related_name="applied", on_delete=models.CASCADE, blank=True, … -
if condition is not working in django post request
I'm check null values from the request but creating record on null after put the condition in views you can check my code. if request.method == 'POST': category_id = request.POST['category_id '] text1 = request.POST['text1'] text2 = request.POST['text2'] text3 = request.POST['text3'] product = Product(category_id=category_id, text=text1) product.save() if text2 is not None: product = Product(category_id=category_id, text=text2) product.save() if text3 is not None: product = Product(category_id=category_id, text=text3) product.save() The text2 and text3 I'm sending null but creating in the database I'm not understanding why these are creating. Thanks -
Django - passing one model to another by pk in link
I'm making a site by using django. It has multiple tests with multiple questions each. I'd like to make question creation form which will have preset question depended on url. it's better explained in comment in views.py That's what I have already done; models class Test(models.Model): name = models.CharField(max_length=200) #questions = models.ManyToManyField(Question) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True) date_posted = models.DateTimeField(auto_now_add = True) def get_questions(self): return self.question_set.all() def __str__(self): return self.name class Question(models.Model): text = models.CharField(max_length=200, null=True) test = models.ForeignKey(Test, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.text urls urlpatterns = [ path('', views.home, name='home'), path('test/<str:pk>/', views.test), path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'), ] forms from django import forms from django.forms import ModelForm from .models import Question, class QuestionCreationForm(ModelForm): class Meta: model = Question fields = '__all__' /// all except test which is set by pk in url views def QuestionCreateView(request, pk): form = QuestionCreationForm() if request.method == 'POST': test = Test.objects.get(id=pk) /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link form = QuestionCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'exam/question_form.html', context) -
I have to determine if model has more than 4 objects or less
If Model has more than 4 than everything works fine. but if there is less than 4 .count() returns 0 posts_num = Post.objects.filter(author__id= self.kwargs["pk"]).count() print(posts_num) if posts_num >= 4: page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:4] else: page_author_post = Post.objects.filter(author__id= self.kwargs["pk"]).order_by('-post_date')[:posts_num] current_user = self.request.user.id context["page_author_post"] = page_author_post -
How to add bootstrap scripts to django admin template?
I want to use some **Boostrap** elements into the **django admin** interface. For that purpose, I have overided the *admin/base.html* template. I want to add the links to bootstrap javascripts (the two lines of code you have to put just before the `` in order to use bootstrap) into that template. As it is out of any `{% block %}` in the original *admin/base.html*, is there a nice way to do that without copying the entire section ? -
Django makemessages : Unexpected translations
Two of my friends and I are using django makemessages to translate our website. When they use it on their PC, everything goes well. However, when I run the command python manage.py makemessages on my PC, it works but many lines in the .po file change when they should not. We all use PyCharm, django 3.1.6 and have the same configurations. I have tried to reinstall them all several times to no avail. I don't understand why makemessages is different on my PC compared to theirs. Some examples : The lines below are added to my django.po file while it concerns variables : #: .\site\views_ajax.py:181 msgid "landfill_hydric_state__name" msgstr "" #: .\site\views_ajax.py:199 msgid "landfill_quality__name" msgstr "" Lines containing a '%' are all modified : "Choice of geology for the \"%(parameter_name)s\" parameter<br>of the " "\"%(study_name)s\" study" Becomes : "Choice of geology for the \"%(parameter_name)s\" parameter<br>of the \"%" "(study_name)s\" study" The line specifying the language moves : "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.4.1\n" Becomes : "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Generator: Poedit 2.4.1\n" An unexpected fuzzy appears on a word that is never … -
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.