Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am new to django. How to resolve the csrf token missing or incorrect error? I have used render request in views
403 forbidden. CSRF token missing or incorrect. I have already tried from django.views.decorators.csrf import csrf_protect, it doesn't work. I have not used render_to_request either. -
Django-Rest-Framework: Make A PUT Request to API
So I want to make a put request to change the content of a message in my chat/messaging app. class MessageView(viewsets.ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete', 'patch'] queryset = Message.objects.all() serializer_class = MessageSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, rest_framework.filters.OrderingFilter, ) filter_fields = ['room'] class UserMessageView(MessageView): def get_queryset(self): return Message.objects.filter(canview__user=self.request.user) #get def get(self, request): hello_param = request.GET["helloParam"] #post def post(self, request): hello_param = request.POST["helloParam"] #put def put(self, request): hello_param = request.PUT["helloParam"] #patch def patch(self, request): hello_param = request.PATCH["helloParam"] #delete def delete(self, request): hello_param = request.DELETE["helloParam"] This is the error I get: 'Request' object has no attribute 'PUT' - If You have any idea how to fix this please respond! :) Thank you! -
I am trying to import gensim, pandas and numpy in my django project but getting import error
I am getting an import error as i try to import gensim, pandas and numpy in django views. How can I import them. I have installed the libraries in virtual environment. -
Conditional Form Field in Django wizard form
I am using wizard forms in django. I want to create a form field only if answer to some other form field is marked "yes" otherwise I don't want this new form field. How can I do this ? I have tried some other answers but most of them tells about how to mark field required or not but I want to display that field only if answer to other field is "Yes" Django Form Wizard with Conditional Questions In below code I want to display field "Pool2" only if answer to field "Pool" is marked "yes" otherwise I don't want that field. forms.py class ListingForm2(forms.Form): Pool = ( ("Yes","Yes"), ("No","No"), ) Pool = forms.ChoiceField(choices = Pool,label = "Does your property have a pool ?") Pool2 = forms.CharField(required=False) Views.py class ListingWizard(SessionWizardView): template_name = 'listing_form.html' form_list = [ListingForm1,ListingForm2,ListingForm3,ListingForm4] def done(self, form_list, **kwargs): save_data(form.cleaned_data for form in form_list) return render(self.request,'done.html',{ 'form_data' : [form.cleaned_data for form in form_list], }) -
django group by match
I want to group by match name i sorted by rank however i failed to group by match. What should you suggest to me [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] [It looks like your post is mostly code; please add some more details.] (sorry for spam) Now my list; I want like this; html <!-- TABLE --> <div class="table standings"> <!-- TABLE ROW HEADER --> <div class="table-row-header"> <!-- TABLE ROW HEADER ITEM --> <div class="table-row-header-item position"> <p class="table-row-header-title">{{ team.broyale_match.name }}</p> </div> <!-- /TABLE ROW HEADER ITEM --> <div class="table-row-header-item padded"> <p class="table-row-header-title">Maç</p> </div> <div class="table-row-header-item padded"> <p class="table-row-header-title">Sırası</p> </div> </div> <!-- /TABLE ROW HEADER --> {% for team in teams %} <!-- TABLE ROWS --> <div class="table-rows"> <!-- TABLE ROW --> <div class="table-row"> <!-- TABLE ROW ITEM --> <div class="table-row-item position"> <!-- TABLE TEXT --> <p class="table-text">{{ forloop.counter }}</p> <!-- /TABLE TEXT --> <!-- TEAM INFO WRAP --> <div class="team-info-wrap"> <!-- TEAM LOGO --> <img class="team-logo small" src="{% static 'img/flags/' %}{{ team.team.country_code }}.svg" alt="{{ team.team.country_code }}"> <!-- /TEAM LOGO --> <!-- TEAM INFO --> <div class="team-info"> <p class="team-name">{{ team.team.name }}</p> … -
Django Rest Framework Assertion Error: Missing Meta.model attribute
I am trying to implement Rest api using Django framework. But when I click on the url on the default index page it gives me an assertion error at/languages/ Class LanguageSerializer missing meta.model attribute I made all the migrations after changes in models.py but it did nothing urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('languages', views.LanguageView) urlpatterns = [ path('', include(router.urls)) ] models.py from django.db import models class Language(models.Model): name = models.CharField(max_length=50) paradigm = models.CharField(max_length=50) serializers.py from rest_framework import serializers from .models import Language class LanguageSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'name', 'paradigm') views.py from django.shortcuts import render from rest_framework import viewsets from .models import Language from .serializers import LanguageSerializer class LanguageView(viewsets.ModelViewSet): queryset = Language.objects.all() serializer_class = LanguageSerializer I have no clue where am I going wrong -
Why the first row of grid is not showing properly?
I'm trying to achieve infinite-scroll using waypoint and django on backend. <div class="discover_feed infinite-container" style="background-color:transparent;padding-bottom:50px;"> {% for m in result %} <div class="example lazyframe infinite-item" style="margin-left:2%;" > <a class="IfFrrameContainer"href="/p/{{m.id}}"> {% for c in m.postimage_set.all %} {% if forloop.first %} <img src="{{ c.Image.url }}" class="lazy"/> {% endif %} {% endfor %}</a> </div> {% endfor %} </div> {% if result.has_next %}<div><a class="infinite-more-link" href="?page={{ result.next_page_number }}"> </a></div>{% endif %} <script type="text/javascript"> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onAfterPageLoad: function ($items) { $items.each(function() { }); }, onBeforePageLoad:function(){ } }); </script> as you can see, everytime styling does not work for first(or probabaly second) element of the grid. -
Django save with update_fields and POSTGRESQL MVCC
(Sorry for my english it's not my native language) I search on internet but I don't find informations about that, if I look at Heroku Devcenter I have this information: url: https://devcenter.heroku.com/articles/postgresql-concurrency#disadvantages-of-mvcc "This is why an UPDATE actually creates a new row", so if Postgresql actually creates a new row for each update, does it make any sense to use update_fields to increase performance? I will in a few days create a little benchmark to test if there is any performance improvement in using update_fields. -
what is causing this error : invalid literal for int() with base 10
Hello I'm developing a simple posts app using Django I have to models user and post model i'm to get all posts sent to a specific user I got this error message while trying to get the posts invalid literal for int() with base 10: 'user1' these are the models user model email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False)</pre> <b>post model</b> ```python class Post(models.Model): # post structure user = models.CharField(max_length=20, blank=True, default="Anonymous") # sender content = models.TextField(blank=False) date = models.DateTimeField(auto_now_add=True) toUser = models.ForeignKey(MyUser, null=False, on_delete=models.CASCADE) post_id = models.AutoField(primary_key=True)</pre> I'm getting the username variable sent in the URL in this view and trying to get all posts sent to this username def user_posts(request, username): posts = Post.objects.get(toUser=username) return render(request=request, template_name='post/user.html', context={'posts', posts}) -
Delivering Mass Notifications and Messages on a Subscription Model
I am trying to implement a subscription model. If one creator takes an action, subscribers of the creator should receive notifications. I made my model like this: class Notification(models.Model): created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(default=timezone.now, db_index=True) creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_creator') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_receiver') post = models.OneToOneField(forum_models.Post, null=True, on_delete=models.CASCADE, related_name='notification') comment = models.OneToOneField(forum_models.Comment, null=True, on_delete=models.CASCADE, related_name='notification') channels = models.ManyToManyField(forum_models.Channel, related_name='notifications') class Meta: ordering = ['-updated_date', '-id'] It is okay for making a simple notification from a creator to a receiver where a post or a comment is created. However, when I want to notify all the receivers who subscribe creator's channel, there is a problem. I have to create one notification for each receiver every time creator does something. That is what I found from django-notification. I concluded that is a very inefficient way to deliver notifications, so I made another model. class NotificationListner(models.Model): receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='notification_listners_receiver') channel = models.ForeignKey(forum_models.Channel, null=True, on_delete=models.CASCADE, related_name='notification_listners') following = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE, related_name='notification_listeners') notify = models.BooleanField(default=False) A notification listener is created for each receiver for subscribing a channel or a following person. And I query like this: def resolve_notifications(self, info, **kwargs): return models.Notification.objects.filter( Q(Q(channels__notification_listners__receiver=info.context.user) & Q(post__is_null=False) & Q(notify=True)) … -
Unresolved import views in urls.py warning BUT app working
from blog import views (blog beeing my app) prints an unresolved import warning yet the app works properly So I'm just starting at Django and in the tutorial i'm following it is sais that in urls i have to import views wich I did : from blog import views It works, the website displays as intended and even Django prints : "System check identified no issues (0 silenced)." the only problem is that VSC underlines it as an error (the import and everytime I reference views) making it harder to see properly . I looked similar issues on the internet and it seems like what I wrote (from the tutorial) is correct so I have no idea what to do now ... from blog import views urlpatterns=[... path('acceuil', views.home), ] PS : English is not my first language so sorry if there are mistakes :) -
Pylint Django model instance of 'str' has no member
I am using pylint-django for my Django project and one of my models is as follows: class Registration(models.Model): date_added = models.DateTimeField(auto_now_add=True) event = models.ForeignKey(Event, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): first_name = self.user.first_name last_name = self.user.last_name return f'{first_name} {last_name}' Running pylint, I am getting the following warnings: events/models.py:61:21: E1101: Instance of 'str' has no 'first_name' member (no-member) From the readme of pylint-django I understand this is a known issue: "If you reference foreign-key models by their name (as string) pylint-django may not be able to find the model and will report issues because it has no idea what the underlying type of this field is." My question is: what should I do to deal with this? I prefer not to suppress all C0111 warnings. Thank you so much in advance for your help! PS: I am using pylint-django as answered on Using Pylint with Django -
I want to pre-populate a form with a foreign key. I click an add link against supplier and add a review without retyping the supplier
I want to click a link next to the supplier and add a review. I should not be required to retype or select the supplier but just enter review details. However I get an error of MultiValueDictKeyError 'supplier.pk'. The error occurs in the get_initial method and specifically supplier.pk. The form is not opened in this case the title bare shows /review/add/2/ which implies that the supplier id 2 is available I also tried this code which opened the form (has other review fields but not supplier field). I got the error KeyError at /comment/add/5/ 'supplier' ''' I got the error KeyError at /comment/add/5/ 'supplier' with code below ''' class CreateReview(FormView): form_class = AddReviewForm template_name = 'comment_new.html' success_url = reverse_lazy ('supplier_reviews') def form_valid(self, form): supplier = get_object_or_404(Supplier, slug=self.kwargs['supplier']) form.instance.supplier = supplier return super(CreateReview,self).form_valid(form) The link below starts of the process Add a review code of my models and view are provided below class Supplier(models.Model): """Model representing suppliers.""" contact_name = models.CharField(max_length=50) company_name = models.CharField(max_length=100) contact_n01 = models.CharField(max_length=15) contact_n02 = models.CharField(max_length=15) class Review(models.Model): """Model representing members.""" date = models.DateField() comment = models.TextField(max_length=1000) score = models.IntegerField() supplier = models.ForeignKey(Supplier, on_delete=models.SET_NULL, null=True) class CreateReview(FormView): form_class = AddReviewForm template_name = 'comment_new.html' success_url = reverse_lazy ('supplier_details') def … -
Django standings with "through" keyword
I want to sort Teams with rank. However, i failed. First of all, i create a match with lots of teams and then i rate these teams. finally, connect the matches with the game object. (because a game can have 2-3 rounds every round is a match) (don't have any error. Just not come data) [ i want like this] team_name rank xxx 1 xxx 2 xxy 3 views.py game=get_object_or_404(BroyaleGame, tournament__slug=tournamentslug, slug=slug, game__slug=gameslug,) teams=Team.objects.filter( broyalematchteam__broyale_match__broyalegame=game ).annotate( points=F('broyalematchteam__rank') ).order_by( '-rank' ) models.py class BroyaleMatchTeam(models.Model): broyale_match = models.ForeignKey('BroyaleMatch', on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) rank = models.IntegerField(default=40) def __str__(self): return self.broyale_match.name class Meta: verbose_name_plural='Battle Royale Takım vs Takım Rank/Puan' class BroyaleMatch(Match): teams=models.ManyToManyField(Team,through='BroyaleMatchTeam') class Meta: ordering=('-name',) verbose_name='Battle Royale Takım vs Takım Maç' verbose_name_plural='Battle Royale Takım vs Takım Maç' class BroyaleGame(Game): match=models.ManyToManyField(BroyaleMatch) tournament=models.ForeignKey('BroyaleTournament',on_delete=models.CASCADE) -
Django : Stop calling same view if its alredy called
I have a view, and when user click on a button it gets called. But If a user click the button twice it gets called for another even if the first is still executing or running. This produces a problem(if I am correct), and that is : It stops execution for the first one and starts executing for the other. Please Help me so that i can stop this calling of views twice. -
Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P<pk>[0-9]+)/$']
I am getting the following error: Reverse for 'ques_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ques_detail/(?P[0-9]+)/$'] Does anyone know how to solve it? I tried solutions posted on many sites but nothing worked. Someone kindly help. urls.py from django.urls import path from . import views urlpatterns = [ path('logout', views.logout, name='test_logout'), path('register', views.register, name = 'register'), path('', views.welcome, name='welcome'), path('instructions', views.instructions, name = 'instructions'), path('ques_detail/<int:pk>/',views.ques_detail,name='ques_detail') ] views.py def ques_detail(request, pk): ques = get_object_or_404(Questionm, pk=pk) return render(request, 'events/ques_detail.html', {'ques': ques}) instructions.html {% extends 'base.html' %} {% block content %} <div class="register"> <h1>Instructions</h1> </div> <br><br><hr><hr> <ul class="list-group"> <li class="list-group-item">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.</li> <li class="list-group-item">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.</li> <li class="list-group-item">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.</li> <li class="list-group-item">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt.</li> <li class="list-group-item">Massa placerat duis ultricies lacus.</li> <li class="list-group-item">Mattis rhoncus urna neque viverra justo nec ultrices dui sapien. </li> <li class="list-group-item">Sit amet facilisis magna etiam tempor orci eu. </li> <li class="list-group-item">Condimentum mattis pellentesque id nibh tortor id aliquet.</li> <li class="list-group-item">Sit amet commodo nulla facilisi nullam vehicula ipsum a arcu.</li> <li class="list-group-item">Vulputate eu scelerisque … -
How to create custom UserCreationForm and UserChangeForm for CustomUser for admin page?
How to create custom UserChangeForm and UserCreationForm for CustomUser for admin page? my models.py: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17, unique=True, blank=True, null=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] -
Can't save a list of numbers to models using api
im trying to create a list from 1 to 9 using the shell so the user can pick the number of tickets that he can book shell Passenger = list(range(1,10)) Passenger.save() Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'save' #Models.py class Ticket(models.Model): GENDER = ( ('m', 'Male'), ('f', 'Female'), ) trip = models.ForeignKey(Trip, related_name="tickets", null=True, on_delete=models.CASCADE) booking_time = models.DateTimeField(auto_now_add=True, blank=True) first_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) middle_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) last_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False) email = models.EmailField(max_length=70,blank=True, null= True) gender = models.CharField(max_length=1, choices=GENDER) def __str__(self): return "{}".format(self.first_name) #Views.py def trips_page(request, trip_id): trip = get_object_or_404( Trip,pk=trip_id) error = None ticket = None if request.method == 'POST': first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') email = request.POST.get('email') gender = request.POST.get('gender') ticket = Ticket(trip=trip,first_name=first_name, middle_name=middle_name, last_name=last_name, email=email,gender=gender) try: ticket.full_clean() ticket.save() return redirect('tickets',ticket_id=ticket.id) except ValidationError as e: error = dict(e) print(e) context = {'trip' : trip, 'error':error, 'ticket':ticket } return render(request, 'details/trips.html', context) -
Django - TIME_ZONE and timezone.now()
I've the following settings:- TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True Also, I've set auto_now = True in my DateTimeField's. However, the datetime that gets saved in the column in of UTC (ie -5:30 hours). I have set my system date as per the Asia/Kolkata timezone. Also, >>> from django.utils import timezone >>> from datetime import datetime >>> >>> datetime.now() datetime.datetime(2019, 7, 13, 17, 40, 1, 505516) # this is right >>> timezone.now() datetime.datetime(2019, 7, 13, 12, 10, 6, 496772, tzinfo=<UTC>) # this is not what I expect. Why is there a discrepency in timezone.now() even when TIME_ZONE is rightly set?? -
How to limit the number of forgot password send reset email attempts?
I'm using the Django in built forgot password reset form and views. I want to limit the number of reset password email attempts. By default Django allows you to send many reset password email without any limit. -
How to get all ancestors of a Django object when ForeignKey is not self-referencing?
I have a model Person and another model Relation. Before creating a new relation I want to check if this relation is possible or not. This post and some other similar posts provides a solution but for self-referencing models, my model is not self referencing. Django self-recursive foreignkey filter query for all childs class Person(models.Model): identifier = IntegerField(null=True) title = CharField(max_length=100, null=True) def get_all_parent_ids(self): # I want to get all the ancestors of this person # but this method only gets immediate parents right now return [parent.parent.id for parent in self.parenting.all()] def get_all_children_ids(self): # I want to get all the descendants of this person # but this method only gets immediate children right now return [child.children.id for child in self.baby_sitting.all()] class Relation(models.Model): name = CharField(max_length=50, null=True) parent = ForeignKey(Person, on_delete=models.PROTECT, related_name="parenting") children = ForeignKey(Person, on_delete=models.PROTECT, related_name="baby_sitting") class Meta: unique_together = ('parent', 'children') def is_relation_possible(new_parent_id, new_children_id): new_parent_person = Person.objects.get(pk=new_parent_id) all_parents = new_parent_person.get_all_parent_ids() if new_children_id in all_parents: return False else: return True For example: Existing relaions - A to B - B to C - C to D - D to E I want is_relation_possible(E, A) to return False, as E has an ancestor A. Currently it only check immediate parents and … -
Django FactoryBoy TestCase handling nested object creation
I am trying to write TestCase with django factory and this lill bit advance testcase writing.. This is my models.py below: class Author(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') title = models.CharField(max_length=200) body = models.TextField() def __str__ (self): return self.title and this is my tests.py below from django.test import TestCase from library.models import Author, Book import factory # Create factory for model class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = 'author name' class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book author = factory.SubFactory(AuthorFactory) title = 'i am title' body = 'i am body' # Start TestCase here class TestSingleBook(TestCase): def setUp(self): self.author = AuthorFactory.create_batch( 10, name='Jhon Doe' ) self.book = BookFactory.create_batch( author=self.author ) def test_single_book_get(self): # compare here above code, my testcase class is class TestSingleBook(TestCase): i hope you noticed it.. I want to create 10 Author and create 10 book with those 10 Author, and then i will compare it in assertEqual if i create multiple book with single author, i can craft the test easily but i dont want it... My Problem is Nested/Multiple... Create multiple author and then create multiple book with those author... is there anyone who solved … -
URL param in POST
Recently I was task for a small project with one of the following REST API specification METHOD ROUTE POST/PUT /plays/{:uuid} My code class Play(models.Model): id = models.Charfield(primary_key=True,default=None, mx_length=255) allOtherfielshere...... I am using ModelViewSet here from rest_framwork, my question is, is it possible to get the url string, which is the {:uuid} part and pass as the value of id in the model? Also how to set the url? My url for plays looks like this app_name = 'plays' urlpatterns =[ path('', include(router.urls) ] This works will if the data comes from form body or json object, but with url params and form together, is it possible? -
Django(v. 1.11.3 ) HttpResponse not returning the specified reason phrase
In one of my views, called via an XMLHttpRequest, I am trying to return an HttpResponse object with a status code and a reason phrase. When I make a request to that specific view, the response that I get has the specified status code but the phrase that I keep getting is "error" for when returning a 40x response type, an empty string when returning a 20x...instead of the phrase that I specify. from django.http import HttpResponse def auth_validate(request): return HttpResponse(status=401, reason="Login failed") What am I missing or doing wrong? -
Django and CORS policy with multiple allowed hosts
I have a small Django project running on a ubuntu server with NGINX and gunicorn. Everything works great when users visit www.example.com, However, when a user visits example.com instead of www.example.com, this is where it falls apart. I am using some javascript with the fetch command, to get data from my API (Django REST) and it returns: Access to fetch at 'https://www.example.com/builds/apidata/4' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. The easiest solution I have found is to just remove example.com from my ALLOWED_HOSTS in my settings.py file, but then when users forget www. they will be greeted with a 404 error. The CORS error message also states I can change the request mode, but I don't know the security implications of this.. I also tried to use redirection on my domain settings from example.com to www.example.com, but this doesn't seem work either. Any suggestions would be appreciated!