Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found 404 django 3
I got the error Page not found (404) when I try to reach the 'contact.html' and 'about.html' page I don't understand why I'm getting this. Here is my code: app/urls.py: urlpatterns = [ path('', views.frontpage, name="frontpage"), path('<slug:slug>/', views.article, name="article"), path('contact/', views.contact, name="contact"), path('about/', views.about, name="about"), # If I write '/about/' that's working but the url is 'http://127.0.0.1:8000/%2Fabout/' and not 'http://127.0.0.1:8000/contact/' as i want. Same issue for contact ] app/views.py: def contact(request): return render(request, 'contact.html') def about(request): return render(request, 'about.html') # Of course the html file are created, they are located in the template folder I'm trying to reach each page with this html code: <a href="{% url 'citrouille:frontage' %}">Home</a> # This is working <a href="{% url 'citrouille:contact' %}">Contact</a> # This is not working <a href="{% url 'citrouille:about' %}">Aboout</a> # This is not working (citrouille is my app's name) Here is the mysite/urls.py (root folder): urlpatterns = [ path('admin/', admin.site.urls), path('', include('citrouille.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have others functions working perfectly such as the article page with the slug. But this two pages doesn't want to show. I'm pretty sure this is a stupid error but i can't point it. Thank you for the help -
How to add an attribute to the form tag itself and not just a field in Django?
I am having trouble stopping bots filling in spam while letting through legit users. I have a honeypot field with autocomplete="off" attribute but it doesn't seem to be working. From what i've read, the best cross browser solution is to add autocomplete="false" to the main form tag itself, e.g. <form autocomplete="false">...</form>. What is the best way to do this in Django? -
Django - create submodels of a model
I want to create submodels(I do not know if this is the correct term to use) of a model. For example, let's say I have a model called Post. But I want this model's fields changable by users. Like users select their Post type. Right now I want to create a two different types: first is a class TextBasedPost(models.Model): title = models.CharField(max_length=100) content = RichTextField() # which has been imported from ckeditor.fields author = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) Other one is a post with only image attachment: class ImageBasedPost(models.Model): title = models.CharField(max_length=100) image_attachment = models.ImageField(default='default.png', upload_to='profile_pics') # there will not be a usage of default.png author = models.ForeignKey(User, on_delete=models.CASCADE) datePosted = models.DateTimeField(default=timezone.now) def crop_image(self): img = Image.open(self.image.path) # Image imported from PIL if img.height > 600 or img.width > 600: output_size = (600,600) img.thumbnail(output_size) img.save(self.image_attachment.path) def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk}) But like you see this is not good way to use since there are same fields and same functions in both models(only one fields and one function is different). But this is not a good practice. So is there a way to do this with better way? -
model obj is returning same object
Hope you are fine i have 2 models class Property(models.Model): .... city = models.ForeignKey(City,on_delete=models.CASCADE) class City(models.Model): img = models.ImageField(upload_to='city/img',blank=True,null=True) name = models.CharField(max_length=200,unique=True) i want to get 3 cities which has most count of properties means i want cities which has most properties so i use this query: city = City.objects.all().order_by("-property")[0:3] but this is not working, because it's returning same value here is the output: <QuerySet [<City: lahore>, <City: lahore>, <City: lahore>]> lahore has the highest count of properties so it's giving me only lahore i want three cities for example city1 , city2 , city3 with highest count of properties -
Is there a preferred way to store user settings in a SQL database
What is the best way to store user settings or preferences? e.g Like an Entity (blog post) with liking or comments disabled. I'm using Django with MariaDB, my currents thoughts are: Store settings as an entity and relate it to the blog post Store the settings as a JSON object in a field within the blog post Store the settings as fields in the 'POST' entity -
Django - Reply a Comment / Comment on Comment modeling
I'm currently trying to setup a reply on comment (comment on comment) function at my Django forum but for some reason the comment reply also needs the post object instead of just a comment where he/she is replying onto. Currently I get the following error if I try to use the comment_answere_new function like shown below: App.models.Comment.post.RelatedObjectDoesNotExist: Comment has no post. views.py def comment_answere_new(request, pk): comment = get_object_or_404(Comment, pk=pk) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment_answere = form.save(commit=False) comment_answere.author = request.user comment_answere.published_date = timezone.now() comment_answere.comment = comment_answere comment_answere.post = comment_answere.comment.post comment_answere.save() messages.success(request, 'Comment reply has been published successfully') return redirect('post_view', pk=comment_answere.comment.post.pk) else: messages.error(request, 'Something went wrong ...') return render(request, 'post_comment_new.html', {'form': form, 'comment': comment}) else: return render(request, 'post_comment_answere_new.html', {'form': form, 'comment': comment}) models.py #Comment Model class Comment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) class Comment_Answere(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False) published_date = models.DateTimeField(auto_now_add=True, null=True) does smb. has a hint for me on how I can get this chain working Post Model <--- Comment Model (Post is ForeignKey) … -
How can i register as school ,collage,course in django?
I am building a site in Django where user can register as school ,collecge,courese but i did not able to do,i have google but no luck can any one hepl me on that thanku -
Django 2.2 Forbidden: /documentation/index.html on Development
I don't know why, but am trying to generate sphnix docus which i did, but serving them has refused whenever i got to http://127.0.0.1:8181/documentation/index.html i get Forbidden: /documentation/index.html HTTP GET /documentation/index.html 403 [0.00, 127.0.0.1:40656] path('documentation/', include('docs.urls')), am using django-docs -
How to Access values from mydata.values() in django?
i am selecting data using django Query.Query is mydata=MyModel.objects.all().values() for newmydata in mydata: return HttpResponse(newmydata .values()) newmydata .values() is printing all my values.its not printing keys.i want to access each values.and also i Want to add some extra values into this (newmydata .values()) array.How to do that? -
How to use vim for python django?
I use pycharm for my django projects but now I am switching to vim so, how to setup django for vim? -
How can I get find the yearly, monthly, and daily avg
I am make a website the tracks all your expenses. And I am making it with Django. So I use Django models to store all the Expenses Here is the Django Model class Expenses(models.Model): user = models.ForeignKey(User, related_name="user_expenses", on_delete=models.CASCADE) date = models.DateTimeField(default=django.utils.timezone.now) item = models.TextField() quantity = models.TextField(default=1) price_per_quantity = models.TextField() total_amount = models.TextField() So I have the expenses the total_amount its the total_price for a expense. So what I want to do is to get the yearly, monthly, and daily expenses avg. How can I do that. -
How to disable automatic URL parameter decoding in Django?
I have a viewset with a retrieve view, which takes one parameter, which is a string url encoded, as it often has '/' in it. Now when I send a request to my local development server with the url encoded (every / replaced by %2F) I get a 404 from my server and in the "Request URL" I see my string but decoded - so it makes sense that there is no such route. The route shows up correctly in this debug view with api/ ^topic/(?P<pk>[^/.]+)/$. This is my viewset: class TopicAPI(viewsets.ViewSet): def retrieve(self, request, pk=None): if '%2F' in pk: pk = pk.replace('%2F', '/') # Data retrival which works (independently tested) return Response(topics) I tried different words and different replacement methods, i.e. '--' instead of '2%F' which works but isn't nearly as stable as url encoding. -
django I want to check special header for every request
I want to check if request contains custom header and if its value is equal to value in setting and reject every request that doesnt pass check I also need to do this foradmin/ too. How can i do it? I have tried overriding dispatch function in View to reject every request that doesn’t pass But this won’t work on admin -
CSRF Token in a django-tables2 form
I want to send parameters unseen to a TemplateView from a form within a django-tables2.table: class CustColumn(tables2.Column): empty_values = list() def render(self, value, record): return mark_safe(f"""<form id="params" action="/product_all/" method="POST"> <button class="btn btn-secondary"> <input type="hidden" name="store_id" value="{record.get_shelf_id}"/> <input type="hidden" name="store_name" value="record.name"/> <span class="fas fa-eye"></span>&nbsp;&nbsp;view</button> </form>""") class ShelfTable(tables2.Table): view = CustColumn(orderable=False) class Meta: model = Product sequence = ("name", "shop", "view") urls.py: path(r"product_all/", views.ProductView.as_view(), name="product-all"), view: class DeviceView(TemplateView): template_name = "gbkiosk/device_all.html" def get_context_data(self, *args, **kwargs): shelf_id = str(kwargs["shelf_id"]) shelf_name = kwargs["shelf_name"] devices = get_devices(shelf_id=shelf_id) bus_numbers = list(set([int(d["bus_number"]) for d in devices ])) context = {"store_id": kwargs["store_id"], "store_name": kwargs["store_name"], return context How would I be able to get the CSRF token into that form of the table? -
Django ORM querying nested models
I want to use django ORM to filter some records from db, I have a model named User which contain a field profile which is another model, When I do the following I get all the users having a profile: users = User.objects.filter(Q(profile__isnull=False)) profile has a field age I want to delete all the users with a profile and age>30. So I looped through all the users with a profile and then checked if their age is > 30. for user in users: if user.profile.age>30: user.delete() Is there a way to use user.profile.age>30 directly in querying? -
how can you make a reference to different models in django
I have an app calendar that looks like this: class Events(models.Model): start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) now I want a calendar event, also a reference to other models (A, B, C, ...). Now you could of course create your own models.ForeignKey for each class: class Events(models.Model): start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) a = models.ForeignKey('A', on_delete=models.CASCADE, blank=True, null=True) b = models.ForeignKey('B', on_delete=models.CASCADE, blank=True, null=True) c = models.ForeignKey('C', on_delete=models.CASCADE, blank=True, null=True) ... but I find that somehow inefficient, as the model has to be adapted again and again for each extension. Therefore, my consideration would be that I create a member for the model itself and a field for the respective id of the model. class Events(models.Model): start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) Table_id = ??? (A, B, C, ...) Model_id = ??? (a1, a2, b1, c3, ...) if I imagine that correctly, each model consists of its own table in the database (or several). Whereby the table entries of model A are then for example a1, a2, a3 ... Therefore I need a reference to the respective table and a reference to the table entry in order to carry out an exact referencing. how should you do that? I've … -
How to provide the correct path of a video file after it is created in django for transcoding. I am getting an error specifying the error in path
Hey guys how to provide the correct path of a video file after it is created in django for transcoding. I am getting an error specifying the error in path. I am quite new to this and not sure how to provide the correct path. This is the code I have for transcoding. def encode_video(video_id): try: video = VideoPost.objects.get(id = video_id) input_file_path = video.path input_file_name = video.title #get the filename (without extension) filename = os.path.basename(input_file_path) # path to the new file, change it according to where you want to put it output_file_name = os.path.join('videos', 'mp4', '{}.mp4'.format(filename)) output_file_path = os.path.join(settings.MEDIA_ROOT, 'videos', output_file_name) for i in range(1): subprocess.call([settings.FFMPEG_PATH, '-i', input_file_path, '-s', '{}x{}'.format(16 /9), '-vcodec', 'mpeg4', '-acodec', 'libvo_aacenc', '-b', '10000k', '-pass', i, '-r', '30', output_file_path]) video.file.name = output_file_name video.save(update_fields=['file']) except: raise ValidationError('Not converted') tasks.py @task(name= 'task_video_encoding') def task_video_encoding(video_id): logger.info('Video Processed Successfully') return encode_video(video_id) models.py class VideoPost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) title = models.TextField(max_length=1000) height = models.PositiveIntegerField(editable=False, null=True, blank=True) width = models.PositiveIntegerField( editable=False, null=True, blank=True) duration = models.FloatField(editable=False, null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted") updated = models.DateTimeField(auto_now_add=True, verbose_name="Date Updated") slug = models.SlugField(blank=True, unique=True, max_length=255) file = VideoField(width_field='width', height_field='height', duration_field='duration', upload_to='videos/') image = models.ImageField(blank=True, upload_to='videos/thumbnails/', verbose_name='Thumbnail image') format_set = GenericRelation(Format) Can anyone … -
In my sbmissions page the user has to get the data which is added by that particular user
I am trying to develop a website using django. In my website there is my submissions page if the user added any data to the website he can edit or delete the data which is added only by him. But my problem is when the user is logged in and viewed the my submissions page the user is getting all the data including which is added by some other users. views.py @login_required def submissions(request): tasks = listing_model.objects.all() form = listing_form() if request.method =='POST': form = listing_form(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('submissions') context = {'tasks':tasks, 'form':form} return render(request, 'submission.html', context) def updateTask(request, pk): task = listing_model.objects.get(id=pk) form = listing_form(instance=task) if request.method == 'POST': form = listing_form(request.POST, request.FILES, instance=task) if form.is_valid(): form.save() return redirect('submissions') context = {'form':form} return render(request, 'updatepg.html', context) def deleteTask(request, pk): item = listing_model.objects.get(id=pk) if request.method == 'POST': item.delete() return redirect('submissions') context = {'item':item} return render(request, 'deletepg.html', context) submission.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block body %} <div class ="container"> <div class="todo-list"> {% for task in tasks %} <div class="item-row"> <div>&nbsp; &nbsp; &nbsp;</div> <a class="btn btn-sm btn-info" href="{% url 'updatepg' task.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'deletepg' task.id %}">Delete</a> <span> {{ task.title … -
Forgot Password using phone number Api django rest framework
I want the user to change the password by verifying OTP through phone numbers. Please help I try a lot but id didn't get it. -
localhost:8000 not working but 127.0.0.1:8000 is django
I'm not sure when it actually happened but I have a django project and when I run my server my app no longer works with localhost and instead works with 127.0.0.1. I had changed my django version to 3.0 to use drf-extensions. I am not sure if when I changed to version 3.0 this occurred but it definitely happened somewhere around this point. Either when I used drf-extensions or when I switched my django version from 3.1 to 3.0. Everything was working fine before that To my understanding they're the same but I'm not sure as to why it is not working. My main issue is not that I can't still work from my 127.0.0.1:8000 but that when I try to run my react server that is running on localhost:3000 my backend gives me this error when trying to do an axios request Exception Value: Incorrect padding I changed the proxy in package.json to be http://127.0.0.1:8000 but still no luck in getting axios to work and still end up with the same error. -
Django admin remove form tag
I am trying to add a form to admin panel in change_list.html with two inputs of type file and button to each line. But there is no form tag on the page. @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('pk', 'upload_excel') def upload_excel(self, instance): href = reverse('admin:upload_excel_view', kwargs=dict(pk=instance.pk)) return format_html(f'''<form action="{href}" enctype="multipart/form-data" method="GET"> <div> <input type="file" value="Upload"> <input type="submit" value="Upload"> </div> </form>''') -
How to send special instructions to Django UpdateView to change custom statuses of a transaction document
In my Django app, I have a requirement where a transaction "document" needs to undergo a change in "statuses" from say, Created to Approved and so on. The documents are marked Created at save when they are first created. Example case Using boolean field and filter at list generation (using Django ListView), the documents which are yet to be Approved are generated where the user is expected to follow the link (on the document number) and browse to the "change" document view where the status field will be filled in and then saved. To achieve this I can create another Django generic UpdateView and carry out the transaction (of approving the document). However, obviously there will be need for additional codes to be maintained. It will get more complex if I have multiple "statuses" to be maintained for the said document. Is there a functionality available in Django whereby I may send a special instruction (using the term for a lack of better word to explain it) through the url to enable the input field for statuses in the update/change form so that user may change the status as needed. PS. Again my question title may not have conveyed the … -
Django template and its paractical use
So I started learning Django about 2 weeks from now and in the Django template you can copy the content of an HTML file to your main HTML, so I think of an idea like this to make it easier for managing the code <!DOCTYPE html> <html lang="en"> <head> {% load static %} {% include 'style_and_cdn.html' %} {% include 'script.html' %} {% include 'navbar.html' %} {% include 'body.html' %} {% block style_and_cdn %} {% endblock %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Testing</title> </head> <body> {% block navbar %} {% endblock %} {% block body %} {% endblock %} {% block script %} {% endblock %} </body> </html> This is the html tree templates style_and_cdn.html script.html navbar.html main.html Is this the practical way of using it or it's unnecessary -
Get client IP using Nginx on EC2 under Elastic Load Balancer
I have an EC2 instance running Nginx + Gunicorn + Django placed under an Elastic Load Balancer. The ELB is enabled for dualstack (IPv4 and IPv6 addresses). I have set the following config in Nginx: proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Within Django views I am trying to get IP address as follows: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip This is returning the private IP of ELB instead of client IP. -
Django-Allauth Social Network Login Failure when clicking the back button
I have an issue when clicking the back button after successfully login in using Google; I get Social Network Login Failure. After replacing the html authentication_error.htmland using {{ auth_error }} I get {'provider': 'google', 'code': 'unknown', 'exception': PermissionDenied()} How I replicate this issue every time: After logging in and clicking the back button, I go back to choose another accounts. Whenever I click on the same account or a different account, I get thrown the errors above. I'd like to mention, I have set my /accounts/login page to action='reauthenticate'. As well as, whenever I reload the page, the user is still signed in. This might be a caching issue, although I'm not sure. Things I have tried. In settings.py, setting AUTH_PARAMS['access_type']='offline', In settings.py, setting SESSION_COOKIE_SECURE = False (momentarily) Any help, or any ideas on how to fix this issue will be much appreciated.