Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'add_comment_to_post' is not a valid view f unction or pattern name
i am new to python and while adding comment option to my djang project while running the post.html file i got this error which says : django.urls.exceptions.NoReverseMatch: Reverse for 'add_comment_to_post' not found. 'add_comment_to_post' is not a valid view f unction or pattern name. and the screenshot of the browser page is [enter image description here][1] and the html code is : <div class="media"> <h3 class="mr-5"><a href="{% url 'posts:for_user' username=post.user.username %}">@{{ post.user.username }}</a></h3> <div class="media-body"> <strong>{{ post.user.username }}</strong> <h5>{{ post.message_html|safe }}</h5> <time class="time"><a href="{% url 'posts:single' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a></time> {% if post.group %} <span class="group-name">in <a href="#">{{ post.group.name }}</a></span> {% endif %} </h5> <div class="media-footer"> {% if user.is_authenticated and post.user == user and not hide_delete %} <a href="{% url 'posts:delete' pk=post.pk %}" title="delete" class="btn btn-simple"> <span class="fa fa-remove text-danger" aria-hidden="true"></span> <span class="text-danger icon-label">Delete</span> </a> {% endif %} </div> </div> </div> <hr> <a class="btn btn-default" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a> {% for comment in post.comments.all %} <a class="btn btn-default" href="{% url 'add_comment_to_post.html' pk=post.pk %}">Add comment</a> <div class="comment"> <div class="date">{{ comment.created_date }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.text|linebreaks }}</p> </div> {% empty %} <p>No comments here yet :(</p> {% endfor %} urls.py file is givenbelow from django.urls import path from . … -
Django Rest Framework: Which 3rd party package is best suited for JWT authentication in a mobile application backend?
I'm starting to build my first mobile application, first I did some tests using the included "rest_framework.authtoken" app but then after reading some online tutorials most people seem to be using other 3rd party packages like: Simple JWT, Django Rest Knox or Django Rest Auth. Which package would be better suited for a mobile application considering that these are my requirements: Regular email and password authentication (with email verification) Oauth2 - Social Media Authentication (Facebook, Instagram, etc.) Token expiration Many thanks! -
What is the best tool to make a simple python web application?
Just took the jump from java to python a few weeks ago in the attempt to start learning web app development (especially back-end). In learning python I created a very simple application that randomly generated color palettes and used tkinter for the GUI. I am ready to take the leap into turning this idea into a web application, but after looking at a few django tutorials, it seems that django is a little too database heavy for what I am trying to build. Any ideas on how I could get this done? Any feedback is greatly appreciated. -
Django 3 Combine Category Class with Dropdown Choices
How do I combine together the category class model with my category choice drop downs a possible other issue problems is some code uses URL other path and one was a class view for a category and the other choice field. It works with out the class Category but I need to now create that to have the post show in a category list view named by the drop down choice field. https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-choices I was able to make a category choice field that I can group by 2 levels not perfect but the only thing possible according to documentation so far. Now when I create a class to do the category views the main list view of each post in that category. I understand my url pattern is wrong WARNINGS: ?: (2_0.W001) Your URL pattern 'category$' [name='category_list'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern 'category/(?P<pk>\d+)/$' [name='category_detail'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). url.py from django.urls import path from . import … -
I am trying to describe the condition of product my site but I am getting TypeError tuple object is not callable
from django.db import models Create your models here. class Product(models.Model): ##contain all product information CONDITION_TYPE = ( ("New" , "New") ("Used" , "Used") ) name = models.CharField(max_length=100) description = models.TextField(max_length=500) condition = models.CharField(max_length=100 , choices=CONDITION_TYPE) price = models.DecimalField(max_digits=10, decimal_places=5) created = models.DateTimeField() -
Why aren't my images being displayed in the same row?
So I'm using bootstrap and I'm wondering what I'm doing wrong here. I'm trying to get my images all in one row, but they are all over the place and my text isn't showing up correctly either. matches.html <div class="container "> <h2>It's a match!</h2> <div class = "row"> <div class="col-4"> <img src="{{ user.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> <div class="col-4"> <img src="{% static 'images/matching_cupid.png' %}" width= "300" height= "300" object-fit = "cover" > <div class="col-4"> <img src="{{ match.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> </div> <p>You and {{ match.username }} like each other!</p> <p><a href="{% url 'dating_app:messages' user.id %}">Start messaging </a></p> <br> <p><a href="{% url 'dating_app:mingle' %}">Keep mingling!</a></p> -
django_crispy_from show only input
HOw to only show the input field in Django crispy form. <div class=""> {{form1.username|as_crispy_field}} </div> how can it only show input field -
How can you filter a Django query's joined tables then iterate the joined tables in one query?
I have table Parent, and a table Child with a foreign key to table Parent. I want to run a query for all Parents, and those Child records whose name is 'Eric'. I run: rs = Parents.objects.filter(child__name='Eric') I then iterate over rs: for record in rs: print(f'Parent name {record.name} child Eric age {record.child.age}') Clearly this doesn't work - I need to access child through the object manager, so I try: for record in rs: print(f'Parent name {record.name}') for child in rs.child_set.all(): print(f'Child Eric age {record.child.age}') Django returns all children's ages, not just children named Eric. I can repeat the filter conditions: for record in rs: print(f'Parent name {record.name}') for child in rs.child_set.filter(name='Eric'): print(f'Child Eric age {record.child.age}') But this means duplicate code (so risks future inconsistency when another dev makes a change to one not the other), and runs a second query on the database. -
error: Unable to find trailer dictionary while recovering damaged file
PyPDF2 fail sometimes with decryption of some PDF files, and I am trying do decrypt them with pikepdf but I am getting this error: Unable to find trailer dictionary while recovering damaged file Any ideas? -
url to path on django
I have been trying to make a like | dislike button on django but the problem I have is that a 404 error pops up because I am using path but the code I am learning from is using url, so can someone help me changing this url to path? url(r'^(?P<postid>\d+)/preference/(?P<userpreference>\d+)/$', postpreference, name='postpreference'), I tryed to change it to path but still didn't worked path('posts/<int:postid>/preference/<int:userpreference>', views.postpreference, name='like_post'), Now this is the html that is supposed to like and dislike <form id="likebutton" method="POST" action="/posts/{{image.id}}/preference/1/"> {% csrf_token %} <input type="hidden"> </form> <form id="dislikebutton" method="POST" action="/posts/{{image.id}}/preference/2/"> {% csrf_token %} <input type="hidden"> </form> -
How do I check for two requirements when logging in using Django?
I know that I can use user.is_authenticated in templates to only display content to authenticated users. However, how can I throw an error if a field that I have is false? The field is "approved" (user.profile.approved). I'm not exactly sure where I might put a decorator to check for this. -
Django Monthly User bills record
I want to store my user's monthly bills record and change bill status individually. I want to generate a list of all user objects for every month with payment status as a field. From there I will change the payment status of users. For example: **January 2020:** user1 : paid user2: paid. **February 2020:** user1 : paid user2: not paid. I can't seem to make a relation between my bill and user models and storing them. -
How to set multiple ParentalKeys to Wagtail TaggedItemBase tag class
I have two different page models (no subclassing, separate apps with only similar fields being common ones like "model name", "id", "parts") , let's say, cars and motorcycles. I'm making a separate page with a table of their parts (which also needs to contain columns like "id" which i assume can be a pk,"web store link", and "used by" which will show all Bike and Car models that use the part); Since they can share a few of the same parts, I want for them to be connected to the same Tag model (instead of having "CarPageTag" and "BikePageTag"); What I've tried so far : I tried to make a separate app for "parts". I figured how to include that class from other app and it works with either car or motorcycle, but not both, because of this error: AssertionError: ParentalKey(['CarsBlogApp.CarDetailPage', 'BikesBlogApp.BikeDetailPage']) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I had a simple solution working in plain Django app via ManyToManyField (but I need the wagtail autofill tag selection page in admin) I looked all over django, wagtail and taggit docs I looked through all youtube tutorials -
Serialize Model from Derived (Abstract) Model
I have the following models: class Address(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) .... class Meta: abstract = True class BillingAddress(Address): is_default = models.BooleanField() ... class Meta: db_table = 'billing_address' I'm trying to build a serializer for BillingAddress: class AddressSerializer(serializers.ModelSerializer): class Meta: abstract = True model = AddressModel class BillingAddressSerializer(AddressSerializer): def to_representation(self, obj): return AddressSerializer(obj, context=self.context).to_representation(obj) class Meta(AddressSerializer.Meta): model = UserBillingAddress fields = ( 'id', 'is_default', ) I keep getting: ValueError: Cannot use ModelSerializer with Abstract Models. How can I build my BillingAddressSerializer to reflect both classes? -
SerializerMethodField: Get field from some other Model
I have a question, can we get field from some some other model model having OneToOneField relion with that field using SerializerMethodField? -
Costumize HTML render of Django form with MultipleChoiceField and the widget CheckboxSelectMultiple
Im creating a Django form that allows to select multiple options (checkbox) and stores a list of characters in the database. The backend works as expected but the frontend renders not nicely. Actually, there are no checkboxes appearing in html. Here what I did in models.py from django.db import models class MyModel(models.Model): field = models.CharField(max_length=70, default='good') In forms.py from django import forms from .models import MyModel CHOICES = ( ('good', 'good'), ('c1', 'c1'), ('c2', 'c2'), ('c3', 'c3'), ('c4', 'c4'), ) class MyForm(forms.ModelForm): field = forms.MultipleChoiceField( choices=CHOICES, widget=forms.CheckboxSelectMultiple, ) class Meta: model = MyModel fields = ['field', ] In views.py from django.contrib import messages from django.shortcuts import render, redirect from .forms import MyForm def new_odontogram(request): my_form = MyForm() if request.method == 'POST': my_form = MyForm(request.POST) if my_form.is_valid(): my_form.save() messages.success(request,'Data stored !') return redirect('index') return render(request, 'my_form_page.html', {'my_form': my_form}) The html code belows acts well for the backend, in my_form_page.html: <form method="post"> {% csrf_token %} {{ my_form.as_p }} <a href="{% url 'index' %}"> <button type="submit">Record</button> </a> </form> However, as I mentioned at the beginning, there are no boxes displayed and I wish to costumize them. So, I read somewhere that there there is some way to loop over the options and add … -
django.template.exceptions.TemplateDoesNotExist: learning_logs\base.html
Just to recap, I'm following along a project from the Python crash course book. And I'm supposed to be deploying the webapp to heroku but it just doesn't work. The problem : django.template.exceptions.TemplateDoesNotExist:learning_logs\base.html I have tried to do various things with my setings.py file but none appear to work: -----------------------SETTINGS.PY------------------------------------- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [r'\learning_logs\templates\learning_logs', r'\users\templates\users',], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Project setup: learning_log: 11_env learning_log: .git learning_log: .... learning_logs: templates: learning_logs: all html files including base.html ... If anyone requires more information to answer the question, please let me know. -
Django 3.0: Getting error for get_absolute_url
I am getting this error: TypeError at /product/177042279214449276022367789942330057699/ product() got an unexpected keyword argument 'id' I am trying to generate detail page of product (book is product). urls.py app_name = 'bookrepo' urlpatterns = [ path('',views.home,name='home'), path('product/',views.product,name='product'), path('product/<id>/', views.product, name='product_detail'), ] template where I am using get_absoulte_url <a href="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn"> <span><i class="fa fa-info-circle"></i></span> View Details </a> views.py def product(request): return render(request, 'bookrepo/product.html') models.py class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField('Title', max_length=255) authors = models.ManyToManyField(Author, related_name='books_written') publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published') price = models.DecimalField('Price', decimal_places=2, max_digits=10) description = models.TextField('Description') upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True) categories = models.ManyToManyField(Category, related_name='book_category') def get_absolute_url(self): return "/product/%i/" % self.id I might be completely wrong with respect to my view and urls. I want to display book details after button in template gets clicked. -
Django class based views form submit 405 method not allowed
I'm trying to make a email submit form in a django app. Coming from Flask though, I'm a bit confused as I'm trying to do this with class based views, but am pretty stuck. I'm currently getting this error but unsure how to make it successfully post Method Not Allowed (POST): /newsletter/ Method Not Allowed: /newsletter/ My models class has this class Newsletter(models.Model): email = models.CharField(max_length=200, unique=True) My forms.py has this from django import forms class NewsletterForm(forms.Form): email = forms.CharField(max_length=200) def send_email(self): # send email using the self.cleaned_data dictionary pass my urls file has this path('newsletter/', views.NewsletterView.as_view(), name='newsletter'), and my form submit in my html is like this <form action="/newsletter/" method="post">{% csrf_token %} <label for="email">Email: </label> <input id="email" type="email" name="email_field" placeholder="email@example.com"> <input type="submit" value="Subscribe"> </form> -
Django models: Unique values for foreign keys
I am building an Instagram like app and trying to make a like model. Each user can like a post however, it should not be possible to like the same post twice. class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) This is my model however, I am able to create 2 identical objects. For example user 1 can have 2 like objects like to post 1. Is there a way to do this? -
How to create ManyToMany object for test cases in Django
I need help with testing models with Many to Many rel. field. First models: class Game(models.Model): name = models.CharField(max_length=150) host = models.CharField(max_length=10) is_played = models.BooleanField(default = False) players_ready = models.IntegerField(default =0) max_players = models.IntegerField(default=4) who_is_ready = models.ManyToManyField(Player) def __str__(self): return self.name class Player(models.Model): name = models.ForeignKey(User,on_delete=models.CASCADE,related_name='player_name') parent= models.CharField(max_length = 10) nick = models.CharField(max_length=10 ) description = models.TextField(max_length = 300, null = True) Test case: from django.test import TestCase, Client from django.urls import reverse from game.models import Game class TestViews(TestCase): def setUp(self): self.client = Client() self.client.login(username='dottore', password='qwerty') def test_join_empty_room(self): game = Game.objects.create() self.join_url_empty = reverse('detail', args=[game.id]) response = self.client.get(self.join_url_empty) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response, "game/detail.html") Test result: FAILED django.db.utils.OperationalError: no such table: game_game_who_is_ready Can someone help me, how to create object with manyToMany for test case? -
Password reset link is not sending using Django. Even it's not showing any error but when I check my email, it's not showing any link here
I'm trying to send the password reset link to gmail but its not sending any link and even not showing any error. How to solve it? urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="blog/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="blog/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="blog/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="blog/password_reset_done.html"), name="password_reset_complete") settings.py EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_HOST_USER='' EMAIL_HOST_PASSWORD='' In EMAIL_HOST_USER I wrote my mail address and in EMAIL_HOST_PASSWORD I wrote my password Kindly help if anyone knows this issue. -
Django Error: UNIQUE constraint failed: scraping_vacancy.title - how can I fix?
Problem! My script worked once and then produces such an error IntegrityError at /index/ UNIQUE constraint failed: scraping_vacancy.title Request Method: GET Request URL: http://127.0.0.1:8000/index/ Django Version: 3.0.5 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: scraping_vacancy.title Exception Location: /Users/dmitrigornakov/Documents/Django/parser/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py in execute, line 396 Python Executable: /Users/dmitrigornakov/Documents/Django/parser/venv/bin/python Python Version: 3.8.2 code source: https://github.com/visualGravitySense/parser Code in views.py file: from django.shortcuts import render from scraping.utils import * from scraping.models import * def home(request): jobs = djinni() city = City.objects.get(name='Kyiv') speciality = Speciality.objects.get(name='Python') v = Vacancy.objects.filter(city=city, speciality=speciality).values('url') url_list = [i['url'] for i in v] for job in jobs: if job['href'] not in url_list: vacancy = Vacancy(city=city, speciality=speciality, url=job['href'], title=job['title'], description=job['descript'], company=job['company']) vacancy.save() return render(request, 'base.html', {'jobs': jobs}) -
How to get file path from user uploaded images, for sending IDs to stripe api not for storing in a database?
I am not too sure if this is possible or not. Using stripes API singing up a user requires an ID picture, front and back, so here is my form for that: class IDuploadForm(forms.Form): id_front = forms.ImageField() id_back = forms.ImageField() here is an example of creating a file in stripe from the API: with open("/path/to/a/file.jpg", "rb") as fp: stripe.File.create( purpose="dispute_evidence", file=fp ) My goal is to not have to store the users images on my own server, as they are ID documents, and just be able to send them right to the stripe API, but I have tried this and get errors from stripes side of things Here is the view I have wrote but does not work(think i am not handling file correctly): class CreateStripeAccount_ID(View): form = IDuploadForm template_name = 'id_upload.html' def get(self, request, *args, **kwargs): form = self.form() return render(request, self.template_name, {'form':form}) def post(self, request, *args, **kwargs): form = IDuploadForm(request.POST, request.FILES) if form.is_valid(): krop = Krop.objects.get(owner=self.request.user) str_acc_id = krop.stripe_acc_id id_front = form.cleaned_data['id_front'] id_back = form.cleaned_data['id_back'] stripe.api_key = settings.STRIPE_TEST_SEC_KEY #file_id_front = stripe.File.create( # purpose='identity_document', # file=id_front # ) #file_id_back = stripe.File.create( # purpose='identity_document', # file=id_back # ) return redirect('home') return redirect('home') -
Django app with tensorflow running very slowly
I have a web app created with django that is using tensorflow to generate compliments and text them to people who sign up for the service. Every time a user submits a number, I'm using subprocess.call() to run a separate script which creates my model and writes the AI-generated compliment to a text file, then the SMS gateway (twilio) uses this txt file for the body of the message. However, after submitting a valid number when it is running the model the app is loading for a very long time, like sometimes it takes 30 seconds or longer before the page stops loading and this is not ideal. Why is this taking so long? Is it because creating the model in tensorflow is just a timely process? And can I do something to speed this up, should I just have it run the code to create the model earlier in the program, or should I just generate a whole bunch of compliments ahead of time and have the SMS gateway draw from that instead? Any advice would be awesome!