Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Semantic Versioning for Django
I am building a dashboard with Django and want to use semantic versioning on github. However, I am struggling to understand when would be a good time to change major vs. minor vs. patch? Could someone provide some examples? -
Filtering Django models but only the many to many through table
I am trying to list all contact but only the primary address. There is a many to many relationship between Contact and Address with a custom through table that contains additional attributes such as "primary". Below is the core of the models. class Address(models.mode): address1 = models.CharField(max_length=100) ... class Contact(models.model): ... address = models.ManyToManyField(Address, through='ContactAddress') class ContactAddress(models.model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE) address = models.ForeignKey(Address, on_delete=models.CASCADE) address_type = models.ForeignKey(ContactAddressType, on_delete=models.CASCADE) primary = models.BooleanField(default=False) Contact.objects.all() return all the contacts. I loop through them to retrieve contact data: for contact in contact I then loop the addresses in an inner loop: for a in contact.address.all How do i limit the address to just the address with the primary=True on the ContactAddress through table? I still want all contacts, but only the primary address for each contact. I was hoping to filter at the top level where i return all the contact but anything i tried limits the contacts that are returned to just those that have a primary address. I want all contacts but only the primary address for each (or no address if no primary address is set on a contact). -
Pip install in /var/www
So I have this project where I need to write a bash script to build a production server for a Django App in Apache and at some point I need to install all the dependencies inside a virtual environment, the problem is that I cannot run pip install because I need permissions to write into that folder and if I try to do sudo pip install it doesn't recognize the command pip. My folder structure is something like /var /www /app /venv /bin /django /django_app What could be the best approach to solve this problem? -
Django template split a string in two parts
In my Django project i hae to split a string into a template based on a specific char. str1 = "Part1 - Part2" in pure python I would do it like this: part1 = str1.split("-",1)[0] part2 = str1.split("-",1)[1] using django template instead i try: {{ str1|split:'-'|first }} but i give an error: Invalid filter: 'split' Someone can help me for split my variable ina django template and take just the first or second part based on a specific char? So many thanks in advance -
Django How to Post comment on only one List item
I am trying to create django commerce app I am little bit stuck on a thing When I post comment via form I created <form action="{% url 'comment' list_id.id %}" method="POST"> {% csrf_token %} <textarea name="comment" class="inp-cmt" rows="3"></textarea> <input type="submit"> </form> the comment is posted but it post on all of my list page I wanted only on the page where comment is posted my comment section {% if allcomments %} <h1>Comments</h1> <div class="card-cmt"> {%for com in allcomments%} <li style="list-style: none;"> <footer class="post-info"> <span>{{com.user}}</span> <p>{{com.text}}</p> </footer> </li> {% endfor %} </div> {% endif %} my urls urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newlist", views.create_listing, name="new_list"), path("item", views.add_item, name="new_item"), path("listing/<int:list_id>", views.listing, name="listing"), path("delete/<int:item_id>", views.delete_list, name="delete"), path("comment/<int:list_id>", views.comments, name="comment") ] my views for comment and listing def comments(request, list_id): coms = Comments() if request.method == 'POST': coms.user = request.user.username coms.text = request.POST.get('comment') coms.listid = list_id coms.save() return redirect('listing', list_id) else : return redirect('index') def listing(request, list_id): list_item = Listing.objects.get(id=list_id) return render(request, "auctions/listing.html",{ "list_id" : list_item, "allcomments" : Comments.objects.all() }) models class Listing(models.Model): owner = models.CharField(max_length =64,default="N/A") productname = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) description = models.CharField(max_length=999, default="test") date = models.DateField(auto_now_add=True) link = models.CharField(max_length=200, … -
How Automatically Update The Page On a new "question" in Django using AJAX
I'am Working On A Q&A; Web Application. It was completed, but i have noticed a small bug, that is- we have to manually refresh the page in order to get the latest questions posted. But i thought it would be much much better if the page refreshed automatically when a new question was posted. I did hours of research on this, but it didn't solve my problem. Here Are The Reference Links- Django refresh page https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ https://docs.djangoproject.com/en/3.1/ref/contrib/messages/ Using Django How Can I Automatically Update Information on a Template auto refresh url in django I didn't manage to find any useful info for me to fix the bug, that is why i posted this question becuase i thought some help by the community Specifications- OS: Windows 10 Python: 3.7.7 Django: 3.0.8 Here Are The Files For The Project- For Further Code Information Please Visit Here- https://github.com/ahmishra/Django-Q-AND-A-App/tree/master views.py from django.shortcuts import render from django.views import generic as genr from .models import Question, Answer from django.contrib.auth import mixins as mxn from django.urls import reverse_lazy # Create your views here. class HomePage(genr.TemplateView): template_name = 'core/home_page.html' class QuestionListView(genr.ListView): model = Question class QuestionDetailView(genr.DetailView): model = Question def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['answer_list'] = … -
Exception Value:no such table: appname_tablename?
I tried all possibilities for this issue in Django but it's not resolved at. it will not create 0001_initial.py I tried many ways. python manage.py showmigrations python manage.py makemigrations python manage.py migrate -
When adding a new query in Django, the foreign key gets the value NULL
I am still learning programming and currently experimenting with Django. Currently I am trying to build a task manager but when I try to add a new Tasks(def new_tasks) it should be related to TaskGroup, instead the task_group_id is related to NULL and I can't seem to figure out why. I believe the reason is some where in the views.py -> def new_tasks. Any help is gratefully appreciated. The structure: Project 1 Task Group 1 Tasks 1 Task 1 Task 2 Task 3 Tasks 2 Task 4 Task 5 Task Group 2 Tasks 3 Task 6 Project 2 Task Group 3 Tasks 4 Task 7 Task 8 Relating the Task Group to Project works but relating the Tasks to Task Group gives the value NUll. image of database Models.py from django.db import models from django.contrib.auth.models import User class Project(models.Model): """A project the user is working on.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.text class TaskGroup(models.Model): """ Title of a group of tasks """ project = models.ForeignKey(Project, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=True, default='') desc = models.CharField(max_length=300, default='') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """ Return a string … -
Django with Heroku-PostgreSQL database horizontal scaling
The problem background I am working on a Django project, which is using PostgreSQL and is hosted on Heroku(also using heroku-postgres). After some time, the amount of data becomes very big and that slows down the application. I tried replication in order to read from multiple databases, that helped reducing the queue and connection time, but the big table is still the problem. I can split the data based on group of users, different group do not need to interact with each other. I have read into Sharding. But since we use heroku-postgres, it's hard to customize the sharding So I have come up with 2 different ideas below 1. The app cluster with multi-db (Not allowed to embed image yet) Please see the design here We can use the middlewares and database-routers to achieve this But not sure if this is friendly with django 2. The gateway app with multiple sub-apps (Not allowed to embed image yet) Please see the design here This require less effort than the previous design Also possible to set region-based sub-apps in the future My question is: which of the two is more django-friendly and better for scalability in the long run? -
did request.POST['choice'] returns an Integer
I am learning django can you please help me with this selected_choice=question.choice_set.get(pk=request.POST['choice']) ... ... selected_choice.votes+=1; --here the selected_choice is holding a particular choice object but what is the functionality of request.POST['choice]--I'm confused with this -
Not Found: /favicon.ico in django
-I was trying to create a checkout and clearcart button for an ecommerce website using django but after writing some javascript code as below everything works fine except for these two buttons does not appear in my web browser and shows 1-Not Found: /favicon.ico on my pycharm terminal, also says 2-ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [03/Sep/2020 13:44:01] "GET /shop/favicon.ico HTTP/1.1" 500 59 any suggestions please? function updatePopover(cart) { var popStr = ""; popStr = popStr + " Cart for your items in my shopping cart "; var i = 1; for (var item in cart) { popStr = popStr + "" + i + ". "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + cart[item] + ''; i = i + 1; } popStr = popStr + " Checkout Clear Cart " console.log(popStr); document.getElementById('popcart').setAttribute('data-content', popStr); $('#popcart').popover('show'); } -
Serialisers field for validation django rest api
I am validating my json in using serialiser in django, but i don't know what should be used to check datetime and null value. { "start_date": "2020-12-16 00:00:00", #? "end_date": "2020-12-18 23:59:59", #? "daily_budget": null, # ? "daily_budget_imps": 10, #serializers.IntegerField(read_only=True) "enable_pacing": true, #serializers.BooleanField() "lifetime_budget": null, #? "lifetime_budget_imps": 980, #serializers.IntegerField(read_only=True) "lifetime_pacing": false #serializers.BooleanField() } complete json { "name": "VTest_Through_API_Pravin11", "state": "inactive", "budget_intervals": [ { "start_date": "2020-12-16 00:00:00", "end_date": "2020-12-18 23:59:59", "daily_budget": null, "daily_budget_imps": 10, "enable_pacing": true, "lifetime_budget": null, "lifetime_budget_imps": 980, "lifetime_pacing": false }, { "start_date": "2020-12-19 00:00:00", "end_date": "2020-12-20 23:59:59", "daily_budget": null, "daily_budget_imps": 10, "enable_pacing": true, "lifetime_budget": null, "lifetime_budget_imps": 6, "lifetime_pacing": false } ] } In my serializers file i don't know how to validate time fields.Do i have to customisation for it. class BusSerializer(serializers.Serializer): # start_date = # end_date = daily_budget = FloatField(max_value=None, min_value=None,allow_null=True), daily_budget_imps = serializers.IntegerField(read_only=True), enable_pacing = serializers.BooleanField(), lifetime_budget = FloatField(max_value=None, min_value=None,allow_null=True) lifetime_budget_imps = serializers.IntegerField(read_only=True), lifetime_pacing = serializers.BooleanField(), class IoSerializer(serializers.Serializer): name = serializers.CharField() state = serializers.CharField() budget_intervals = BusSerializer(many=True) -
uwsgi socket wrong group applied
Problem: When I run uwsgi --socket racing_app.sock --wsgi-file racing_app/wsgi.py --chmod-socket=664 as my logged in user, the system creates the socket as my user/group. Then nginx is unable to read the file. Things I've tried: I created a group www-data and added nginx to the group as well as added my user which enabled me to create the socket file with the group of www-data, but it still fails read. What does work is manually changing the file group to nginx. Doesn't work srw-rw-r-- 1 david www-data 0 Sep 3 20:06 racing_app.sock Does work srw-rw-r-- 1 david nginx 0 Sep 3 20:06 racing_app.sock -
Permission Denied for media files at AWS S3 with Heroku and Django
In order to let the user upgrade some images in my django project I've decided to use AWS S3 buckets. I've followed a couple of tutorials and everything seems to look fine with my media storage backend because I can see the updated files on my bucket. The problem is that the images aren't been served in the site. When I try to open it a simple XML appears showing an "Access Denied" error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>33BFF888CD1CA014</RequestId> <HostId>UEeWZpvsQzOoIvq9uSz7Xqo7KAFhHmsPsXxEGwxaDW6V1mM2B0EccXSMXj0NXCnbi+VlwlL9d00=</HostId> </Error> Some infos that might be useful: My IAM user is in a group with a AmazonS3FullAccess policy; I've tried to enable public access to my bucket and it didn't work; My bucket is in the us-east-2 region; I updated the bucket CORS configuration according to this heroku tutorial. Any idea on what could be causing this error? Thank you very much! -
Django API Framework - Nested Models View
I'm working on a Django API with the rest framework and i want to GET data of all child classes related to parent and also, the parent data. The only way i can do this right now is with the < depth = 1 > parameter inside the serializers. But the problem with this, is i get the parent data for every child, and i only want it once. I have two nested models, let's say: class Shop(models.Model): name = models.Charfield(max_length=50) address = models.Charfield(max_length=200) def __str__(self): return self.name class Product(models.Model) shop = models.ForeignKey('Shop', on_delete=models.CASCADE , related_name='product') name = models.Charfield(max_length=50) price = models.IntegerField(default=0) Serializers look like this: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'shop', 'pk', 'name', 'price', ] class ShopProductSerializer(serializers.ModelSerializer): product_set = ProductSerializer(many=True) class Meta: model = Shop fields = [ 'shop', 'pk', 'name', 'price', 'product_set', ] so if i add depth=1 to the ProductSerializer i get the repeated Shop Data. I've seen this problem is solved by creating a nested serializer like the second one. But then how do i addapt my API View to work with it? Right now it looks like this: class ProductListView(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): shop = self.kwargs['pk'] products = … -
Topic_id missing even after using get method
topic_id is missing even after using get method . I think it might be the pattern r'topics/(?P<topic_id>\d+)/$' . Heres the code and the error im gettings: urls.py: from django.urls import path , re_path from . import views urlpatterns = [ #Home page path('', views.index, name='index'), path('topics/', views.topics , name='topics'), re_path(r'topics/(?P<topic_id>\d+)/$' , views.topic , name = 'topic'), ] app_name = 'learning_logs' views.py: from django.shortcuts import render from .models import Topic # Create your views here. def index(request): return render(request , 'learning_logs/index.html') def topics(request , topic_id): topics = Topic.objects.order_by('date_added') context = {'topics':topic } return render(request , 'learning_logs/topics.html' , context) def topic(request , topic_id): topic = Topic.objects.get(id = topic_id) entries = topic.entry_set_order_by('-date_added') context = {'topic':topic , 'entries' : entries} return render(request , 'learning_logs/topic.html' , context) error: image -
Many-to-Many relationship in Django
I have the following 3 models: class Platform(models.Model): title = models.CharField(max_length=100, unique=True) class Profile(models.Model): title = models.CharField(max_length=110, unique=True) platform = models.ManyToManyField(Platform) class Register(models.Model): ... profile = models.ManyToManyField(Profile) ... My views.py def info(request): ... registers=Register.objects.all() ... for register in registers: profile= register.profile....??? I need to know the profile or profiles from a query of the Register model is possible? -
Is there a way to remove lines being added to markdown file from django textarea?
When creating an entry such as # Title This is an entry The following file is created # Title This is an entry When I update this file, more spaces are added. I want the spaces to be removed and only show when the user inputs spaces. The code snippets are not the complete files but should provide the relevant code that connects everything together. views.py class NewEntryForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'})) entry = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'})) def create(request): if request.method == "POST": print(request.POST.get('entry')) form = NewEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"].strip() if util.get_entry(title): return render(request, "encyclopedia/create.html", { "form": form, "exists": True, "title": title }) else: entry = form.cleaned_data["entry"] print(entry) util.save_entry(title, entry) return redirect("entry", title=title) else: return render(request, "encyclopedia/create.html", { "form": form, "exists": False }) return render(request, "encyclopedia/create.html", { "form": NewEntryForm(), "exists": False }) create.html {% block body %} <h2>New Entry</h2> <form class="entry-form" action="{% url 'create' %}" method="post"> {% csrf_token %} {{ form }} {% if exists %} <p class="alert alert-danger">Entry '{{ title }}' already exists.</p> {% endif %} <input type="submit" class="btn btn-primary mt-3"> </form> {% endblock %} utils.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title … -
Bad request (400) on Django Localhost
I have the project successfully deployed through AWS. However, I would like to make some changes and experiment on them using localhost:8000/ first before making the changes to AWS server. I set my settings.py to: ALLOWED_HOSTS = ['IP address', 'www.website.com'] to deploy it. Though, I also want to be able to run the server in my local computer so I can experiment it before showing to public. The url is (r^homepage$') When I go to localhost:8000/homepage, it gives a Bad Request (400). I tried many permutations of the urls but nothing works. -
Correctly import NestedViewSetMixins for Django
I am getting an error when I import attempt to import from rest_framework_extensions.mixins import NestedViewSetMixin the error is as follows ImportError: Could not import 'rest_framework_extensions.utils.default_object_cache_key_func' for API setting 'DEFAULT_OBJECT_CACHE_KEY_FUNC'. ImportError: cannot import name 'EmptyResultSet' from 'django.db.models.sql.datastructures' I am not sure why this is happening. I have already installed drf-extensions -
Duplicated entries full of Null for every entry in my sqlite DB table (there are exactly twice what I need), created in Django, how to fix?
Somehow I am getting doubled entries of the name field in the Site table in my sqlite DB. I suspect this is cause by my models.py file, but I can't see where I erred. See the image below for an example. The code I suspect is the problem is in the models.py file that looks like this. from django.db import models class Category(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class States(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class Region(models.Model) : name = models.CharField(max_length=128,null=True) def __str__(self) : return self.name class Iso(models.Model) : name = models.CharField(max_length=2,null=True) def __str__(self) : return self.name class Site(models.Model): name = models.CharField(max_length=128) year = models.IntegerField(null=True) description =models.CharField(max_length=2000,null=True) justification =models.CharField(max_length=2000,null=True) longitude =models.FloatField(max_length=20,null=True) latitude =models.FloatField(max_length=20,null=True) area_hectares =models.FloatField(max_length=20,null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True) state = models.ForeignKey(States, on_delete=models.CASCADE,null=True) region = models.ForeignKey(Region, on_delete=models.CASCADE,null=True) iso = models.ForeignKey(Iso, on_delete=models.CASCADE,null=True) def __str__(self) : return self.name The only other file that is cheifly involved in populating the table from the csv I am importing from is this file import csv # https://docs.python.org/3/library/csv.html # https://django-extensions.readthedocs.io/en/latest/runscript.html # python3 manage.py runscript csv_load from unesco.models import Site, Category, Region, States, Iso def run(): fhand = open('unesco/whc-sites-2018-clean.csv') reader = csv.reader(fhand) next(reader) # Advance past the header Site.objects.all().delete() … -
NameError: name "IntegerField" is not defined
I'm new to Django and I am receiing this error and I am not sure why. Can anyone assist me? Error message: I entered "python3 manage.py makemigrations" in the shell, please look at the hyperlink to view the Error Message -
Django differentiating between user and template condtion
Let's say you are creating a blogsite and you want to add a special feature that the author (of an article) can choose another user who can also edit that article with him. And that user (editor) can also be assigned by other users as editor and he (editor) can publish his own article as well and also choose another user as an editor of his article. And obviously everyone can see each other's blog, just that the edit button can only be accessed by the author and the editor of that article. What will be your method? I tried to create some models named Author, Editor, Blog. Now, I created an one to one relationship between user and author as well as author and editor, then created a many to many relationship between blog and editor and a many to one relationship between blog and author. Then I created a view of blogs objects and rendered it to the template and in template I put a if condition to check if the logged in user is that blog's author or editor, but this condition is not working. views.py -> def blog(request, pk): if request.user.is_authenticated: blogs = Blog.objects.get(id=pk) context = … -
How to make date range filter in Django?
i'd like to let user searching data by picked date range. MY MODEL class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' VIEWS.PY class ExpenseListView(ListView): model = Expense # imported db model paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None \ else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) category = form.cleaned_data['category'] if category: queryset = queryset.filter(category=category) grouping = form.cleaned_data['grouping'] if grouping: queryset = queryset.order_by('date', '-pk') return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), summary_per_year_month=summary_per_year_month(queryset), total_amount_spent=total_amount_spent(), **kwargs) I wish I could make this look & work like that (example from my app, 2 lines of html just to show you what result I want). I don't have a clue how to make it work with everything else, especially I want to include this to my ListView which already have one django form in it. Any thoughts? Maybe you could direct me somehow? Im absolutely confused after researching for whole day without any good result. -
Record AnonymousUsers informations DJANGO
Thanks for your time. Basically i'd like to know if does worth it to record each first request of that ipAddress(user) for day as an anonymous user and save his infos, like country, session period. Or wont be anything as much as Google Analytics does. to explain my self right. i'd like to know if is there anything awesome that i can do by storing each GET request. like on GoogleAds and etc. function to get ip: 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