Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there problems in sending data from javascript to django that way?
in the html template <script> const csrf = '{{ csrf_token }}' </script> <script src="{% static 'script.js' %}"></script> in script.js: const form = new FormData() form.append('Name','Vitor') form.append('Age',5) form.append('csrfmiddlewaretoken', csrf); const request = new XMLHttpRequest() request.open('POST','my_form') request.send(form) request.onload = function(){ alert('sucess') } request.onerror = function(){ alert('error') } I would have any problem with bugs and security if i sent data that way -
How to apply a conditional AND statement using Q objects
I have the following model: Contact(models.Model): personal_id = models.CharField() personal_id_type = models.SmallIntegerField() I want to apply a CheckConstraint that ensures an IntegrityError is thrown if personal_id is NOT null AND personal_id_type = 0. In pseudocode: if personal_id != None and personal_id_type == 0: fail I have tried to achieve this with the following Q objects: class Meta: constraints = [ models.CheckConstraint(check=~Q(personal_id__isnull=False) & ~Q(personal_id_type=0), name='personal_id_type_0__personal_id_isnotnull') ] However this results in the following SQL checkL NOT personal_id IS NOT NULL AND NOT (personal_id_type = 0 AND personal_id_type IS NOT NULL) How do I amend this to be simply NOT (personal_id_type = 0 AND personal_id_type IS NOT NULL)? -
Joining Models And Passing To Template
I have multiple related models and on a single page I need to access data from different models on a variety of conditions. Most of this data is accessed without a form as only a few fields need to be manipulated by the user. To give you an idea of how interconnected my Models are: class User(models.Model): first = models.ManyToManyField(First) second= models.ManyToManyField(Second) class First(models.Model): [...] class Second(models.Model): first = models.ManyToManyField(First) class Third(models.Model): first = models.ForeignKey(First) class Fourth(models.Model): user = models.ForeignKey(User) second = models.ForeignKey(Second) third = models.ForeignKey(Third) class Fifth(models.Model): fourth = models.ForeignKey(Fourth) class Sixth(models.Model): fifth = models.ForeignKey(Fifth) I'm having a lot of difficulty passing this data to my template and displaying it in efficiently. I originally displayed it to the user in a horrendous way as I just wanted to see if my data was accessible/displaying properly. This is an example of some of the dodgy code I used to test that my data was being passed properly: {% for second in user.second.all %} {% for first in second.first.all %} [...] {% for fourth in user.fourth.all %} [...] {% if fourth.first_id == first.id and fourth.second_id == second.id %} {% if fourth.checked == True %} [...] {% else %} [...] {% endif … -
sass compile issue with @use and @forward
I've been researching this for hours now and its driving me nuts. I've tried 3 compilers and they all give the same error. Error: no mixin named flex My code: // style.scss @use "mixins" as *; .home { .header { @include flex(column); padding: 20px 10px 0; text-align: center; } } // _mixins.scss @forward "mixins/flex"; @forward "mixins/overlay"; // mixins/_flex.scss @mixin flex($flex-flow: row, $justify-content: center, $align-items: center) { display: flex; justify-content: $justify-content; align-items: $align-items; flex-flow: $flex-flow; } -
I have create a custom query-set paginate using ListView CBV in Django but not able to find objects in pages
Currently stuck with applying pagination to my Django SearchView codes. Basically, paginate_by work on first search page but when i try another page then its generate error Invalid page (2): That page contains no results. How can solve its probe? [urls.py] path('search/',SearchView.as_view(),name='search'), [view.py] class SearchView(ListView): template_name = 'search.html' context_object_name = 'object_list' paginate_by = 2 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('search', None) context['category'] = Category.objects.all() context['slider'] = Slider.objects.all() return context def get_queryset(self): request = self.request query = request.GET.get('search', None) if query is not None: #category_results = Category.objects.search(query) items_results = Item.objects.search(query) # combine querysets queryset_chain = chain( #category_results, items_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a objects list return qs return Item.objects.none() # just an empty query-set as default [search.html] {% if is_paginated %} <ul> {% if page_obj.has_previous %} <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li> {% endif %} <li class="active"> <a href="?page={{ page_obj.number }}">{{ page_obj.number }} </a> </li> {% if page_obj.has_next %} <li><a href="search/?search={{query}}/?page={{ page_obj.next_page_number }}">&raquo;</a></li> {% endif %} </ul> {% endif %} I have read documents of pagination but its not help for me. Thank you stackoverflow community -
Django TestCase Ommiting Some Migrations
For some reason, Django (3.0.7,8) is not running one of my migrations users.0002_customuser_is_service_account when executing a TestCase. It's not failing, it just seems to ignore it. This migration has been applied successfully to my development database, and under normal circumstances, the migrate command seems to detect it without issue. Revert to Initial: python manage.py migrate users 0001 Operations to perform: Target specific migration: 0001_initial, from users Running migrations: Rendering model states... DONE Unapplying users.0002_customuser_is_service_account... OK Re-apply by auto-detecting migration python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, csv_management, reversion, sessions, softdelete, tasks, trades, trades_portal, users Running migrations: Applying users.0002_customuser_is_service_account... OK Migrations in Development Database: But when I attempt to run this simple TestCase, it complains that it cannot find a column. from django.test import TestCase from users.models import CustomUser class TestExists(TestCase): def test_thing(self): CustomUser.objects.all() python manage.py test trades_portal --no-input django.db.utils.ProgrammingError: column "is_service_account" of relation "users_customuser" does not exist LINE 1: ... "email", "is_staff", "is_active", "date_joined", "is_servic... If I look at the test database after the test fails, sure enough, that column does not exist: And looking in the migrations, the migration which adds that column was never run: Here is the migration: # Generated by Django … -
Cannot find problem heroku application error
I have a Django blog. I have recently changed some things. I was on a different computer than usual. I used git commit, then git push. Git push ran an error telling me to do git pull and fetch. I did, then pushed. It worked, but Heroku gave me an application error. Please help! -
Get username in django login_required decorator
In my django views.py, there are 75 functions and for every function, i am using @login_required decorator and I want to capture the username when someone hits corresponding function. I am able to get that by using request.user.username but I have to write this line in all 75 functions which is redundant... Is there a way to get/print username in @login_required decorator itself by default so that I can skip writing the same line in all the functions. Following is the snippet for @login_required decorator. def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator -
Looking for a technical cofounder
I have founded several successful, profitable and sustainable businesses (combined turnover $60M all still running today) and I'm ready to create the next one. Although reasonably technical I am not a developer - my skill is UX, product development and marketing. I have a new business planned that is more ambitious and technical than anything I have attempted before so I need a technical cofounder. A hint is that it is in the no-code category like webflow.com and bubble.io but with a significant difference. The product/service will use a framework, more than likely Angular - although open to considering others React & Vue. Actually, the reality is I'm looking for someone that can make the most informed decision for me. So, I have 2 questions. Is there someone out there that can point me in the right direction to find a technical cofounder who is interested in building this - to be clear I'm not saying for free, I will be raising a significant amount of capital to fund it. What do you think is the best platform to build a new "no-code" web application on that will have long-term support - and why? Please feel free to contact me … -
Showing a file in a new browser window django
I am getting a 404 error when i am trying to show the pdf file in a new browser window when the user pushes a HTML button. I cannot see anything wring with the code.but it is not working. Fist I show and return my path to my pdf Views.py def show_file(response): pdf = open('myapp/faults.pdf', 'rb') response = FileResponse(pdf) return response Urls.py path('show_file', views.show_file), index.html <input type="button" value="Show Report" onclick="window.open('show_file')"> -
AttributeError: 'function' object has no attribute 'copy' django
Im trying to pass in a view of django two different objects: APIView and PasswordResetView: class PasswordReset(APIView, PasswordResetView): email_template_name = 'passreset/password_reset_email.html' html_email_template_name = 'passreset/password_reset_email.html' success_url = reverse_lazy('inicio:password_reset') template_name = 'passreset/password_reset.html' token_generator = PasswordResetToken() But i get the error AttributeError: 'function' object has no attribute 'copy' There is a way to do this without this problem? Thank you! -
Djanog error (DoesNotExist at /admin/ Profile matching query does not exist)
I'm working with someone's code. it's running perfectly on my local machine. I am easily able to create a superuser account. but when I'm trying to log in that account it's showing me these error messages. what should I do? raise self.model.DoesNotExist( timelines.models.Profile.DoesNotExist: Profile matching query does not exist. HTTP GET /admin/ 500 [0.12, 127.0.0.1:52697] -
Django comments under the post
I am studying Django 3. I need your help ... in a small blog, I want to add comments to blog posts, I can’t write 'view.py' need comments to be written under the post and to respond to other comments, I will be glad to any help (sorry if there are errors in the text, I do not know English well =)) What is there at the moment: models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() image = models.ImageField(upload_to='images/', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class CommentPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author_name = models.CharField(max_length=80) author_email = models.EmailField() content = models.TextField() date_create = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('date_create',) def __str__(self): return 'Comment by {} on {}'.format(self.author_name, self.post) view.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post from .forms import CommentPostForm class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' … -
Returning title of DB entries of type "FileField" in django
I am using Django admin to upload files to my websites DB daily. How do i keep track of the names of the files that i have uploaded to the database. because in django admin they just show up as objects1 object2 etc. I want to return my the_file title of the file that I upload. i am trying to show the first 50 characters of the name of the files that i have uploaded. However it is not working for me. I think i am having trouble because it is of type FileField class UploadedFile(models.Model): the_file = models.FileField() def __str__(self): return self.the_file[:50] -
What is the difference between <int:pk> and <pk>?
Say that we are implementing a simple blog with django and that the blog posts are accessible with URLs like /posts/1/, /posts/2/ etc. When we define the path variables in the urlpatterns array, what is the main difference between using path('post/<int:pk>/', ..., ...) and path('post/<pk>/', ..., ...)? Is it just good practice? Are there actual benefits? -
how to operate with values from dictionary in a condtional statement in a django template
in my django template I have a conditional statement which involves value from a dictionary {%if {{y}} > 1 %} color: '#4d0099' {% endif %} where y is a numeric value.i want to apply this if statement on it but i am getting an error of Could not parse the remainder: '{{y}}' from '{{y}}' -
Django Rest Framework vs Swagger View
Using the following serializer with the latest Django version 3.0.7 and Django Rest Framework 3.11.0 we have a very strange behaviour on our API: class UnitSerializer(serializers.ModelSerializer): parent = RecursiveField(allow_null=False) # RecursiveField from https://github.com/heywbj/django-rest-framework-recursive ... class Meta: fields = ('id', ... 'parent', ...) model = Unit depth = 3 When viewing the /api/unit url directly Django throws maximum recursion depth exceeded while calling a Python object as an error, but when showing the same view through swagger it shows everything correctly. I tried to implement our scenario using every answer from this question to avoid the problem, but I encountered it (or other problems) in every solution. How can this be? How can we adjust this to show the same result on both ends? Our goal would be to show the tree structure for each object returned by this call. -
How to filter by categories in django
I have been working on a project in which a user can post its profile so that other people can see his profile, and when a user posts its profile, the user can see other peoples profiles(like in tinder). First i will like to make a pair of questions to be filtered depending on users choice which will be "What are you searching for?" and "What do you like?". In both questions there are just 2 options to choose which are "physics" and "math", depending on users answer they should be able to see just the category they are searching for and post their profile to the category the user selected its profile to be posted. Currently my code can just upload the profiles, but I dont know how will the filtering process look like on the views.py file because I am kind a newbie to django so Please any idea on this filtering process helps;) models.py CATEGORY_CHOICES = ( #I think this choices can help for the filter ('action', 'action'), ('sports', 'sports'), ) class Mates(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True) categories = models.CharField(choices=CATEGORY_CHOICES, default="choose...", max_length=10) #I also think this field will help. req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', … -
runserver_plus for django gives 302 on static files
I'm running manage.py runserver_plus for a django based application, normal runserver works fine but when i use runserver plus all the static files needed by the app give 302. "GET /static/css/base.css?v2.6.6 HTTP/1.1" 302 - "GET /static/bootstrap-3.4.1-dist/css/bootstrap.min.css HTTP/1.1" 302 - "GET /static/font-awesome-4.7.0/css/font-awesome.min.css HTTP/1.1" 302 - "GET /static/jquery-ui-1.12.1/jquery-ui.css HTTP/1.1" 302 - "GET /static/select2-4.0.5/css/select2.min.css HTTP/1.1" 302 - "GET /static/select2-bootstrap-0.1.0-beta.10/select2-bootstrap.min.css HTTP/1.1" 302 - "GET /login/?next=/static/css/base.css%3Fv2.6.6 HTTP/1.1" 200 - "GET /login/?next=/static/bootstrap-3.4.1-dist/css/bootstrap.min.css HTTP/1.1" 200 - "GET /login/?next=/static/font-awesome-4.7.0/css/font-awesome.min.css HTTP/1.1" 200 - "GET /login/?next=/static/jquery-ui-1.12.1/jquery-ui.css HTTP/1.1" 200 - "GET /login/?next=/static/select2-bootstrap-0.1.0-beta.10/select2-bootstrap.min.css HTTP/1.1" 200 - "GET /login/?next=/static/select2-4.0.5/css/select2.min.css HTTP/1.1" 200 - "GET /static/js/jquery-3.4.1.min.js HTTP/1.1" 302 - "GET /login/?next=/static/js/jquery-3.4.1.min.js HTTP/1.1" 200 - "GET /static/jquery-ui-1.12.1/jquery-ui.min.js HTTP/1.1" 302 - "GET /static/bootstrap-3.4.1-dist/js/bootstrap.min.js HTTP/1.1" 302 - "GET /login/?next=/static/jquery-ui-1.12.1/jquery-ui.min.js HTTP/1.1" 200 - "GET /static/select2-4.0.5/js/select2.min.js HTTP/1.1" 302 - "GET /static/clipboard-2.0.4.min.js HTTP/1.1" 302 - "GET /login/?next=/static/bootstrap-3.4.1-dist/js/bootstrap.min.js HTTP/1.1" 200 - "GET /login/?next=/static/select2-4.0.5/js/select2.min.js HTTP/1.1" 200 - "GET /static/js/forms.js?v2.6.6 HTTP/1.1" 302 - "GET /login/?next=/static/clipboard-2.0.4.min.js HTTP/1.1" 200 - "GET /login/?next=/static/js/forms.js%3Fv2.6.6 HTTP/1.1" 200 -``` I have tried changing the BASE_DIR path in settings.py and also changed the STATIC_ROOT and STATIC_URL to see if that fixes the issue. -
How can I setup Django and React on the same port and handle routing?
The Problem Hi! I’m trying to setup my Django-React app but I can’t manage to get both to run in the same port (Django Rest API is in port 8000 and react in 3000) using the react router links and routes. I am using django, djangorestframework, react, react router and react router dom. Please help 🤓😅 Django's API works perfectly for get and post requests and they load perfectly with ListCreateAPIViews Here are some pictures of my files. Let me know if you need any more info. The Pictures Project Structure models.py serializers.py api/urls.py urls.py settings.py -
how can i access to a property of a model in another model which has a many to many relationship with it (in django)
Hey i have a project and in that project i need to get access to a property in this case 'price' from model 'options' but i wanna get that in model 'order' which has a Many To Many relationship with 'options' i try this: class Option(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() class Order(models.Model): option = models.ManyToManyField(Option, blank=True) def get_price(self): price = None if self.option: price = self.option.price return price this hits an error and says many related model has no attribute price -
Django: If value exists in database, pass it as a variable from view to template
I am new to coding and new to Django. I searched stackoverflow for my question but didn't find what I was looking for: What I am trying to do is check if certain values are in my database and if yes, pass it as a variable to the template. The values will be items of a dropdown menu. If I have for example a database with bicycle1 to bicycleN I'd like to check if the value of the attribute "handlebar" of each database-object matches a certain manufacturer. If yes, pass it to the template so it can appear in the dropdown menu to later filter the results. First I thought I should check in the template itself and thought about something like this: bicyle_list.html <ul id='dropdown1' class='dropdown-content'> {% for bicyle in bicycles %} {% with manufacturerA=False %} {% if manufacturerA == False and bicycle.handlebar == "manufacturerA" %} <li><a href="#!">ManufacturerA</a></li> {% manufacturerA=True %} {% endif %} {% endwith %} {% endfor %} But as I understand the template should only contain rendering logic. (Besides, I`d have to use boolean variables in the for-loop, because a manufacturer should only appear once in the dropdown menu even if there are several bicycles with … -
add GeoDjango dependencies on alpine docker
I want to use GeoDjango on alpine docker and should add some dependencies on docker to use postgis database, refers to Django website I have to install by $ sudo apt-get install binutils libproj-dev gdal-bin I found that gdal and gdal-dev have already existed on alpine, so I used RUN apk add gdal gdal-dev but after running this docker-compose exec web python manage.py migrate --noinput Django says that : 'django.contrib.gis.db.backends.postgis' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' How to add GeoDjango dependencies on alpine dockerfile? -
django templates with-tag custom filter
I have a dict of lists containing images. The key is the id of a journey. Now I want to get an image list based on the id so I wrote a filter: @register.filter def dict_value(dict, key): return dict.get(key) Now I want to use this filter but how? This is what I did: {% for journey in journeys %} ... {% with imagelist={{ images|dictvalue:{{journey.id}} }} %} {% if imagelist %} <img class="card-img-top" data-src="" style="height: 225px; width: 100%; display: block;" src="{{imagelist.0.url}}" data-holder-rendered="true"> {% else %} <img class="card-img-top" data-src="" style="height: 225px; width: 100%; display: block;" src="https://via.placeholder.com/348x225.png" data-holder-rendered="true"> {% endif %} {% endwith %} ... {% endfor %} For testing, I want to display the first image if the list is not empty. But I have a problem with the with-tag. How do I do it correctly? -
pycharm django ubuntu20.04 ModuleNotFoundError: No module named 'namedjangofolder'
I have a Pycharm enviroment project where I cloned a backend django repository. when I run the command : python manage.py runserver I get the following error: log error ModuleNotFoundError: No module named 'backend' I am new to django and I dont quite understand why this is happening. I have not really found a good solution. The interpreter seems to be working fine, and I have checked all the paths. If anyone has a solution I would love to know.