Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I set up local_settings.py when I have postgres specific fields?
I am currently working with a Django application that uses a postgres database. In my local_settings.py, I use a sqlite database for local development per the code below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path.join(SITE_ROOT, 'djlocal.db'), 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Not used with sqlite3. 'PORT': '', # Not used with sqlite3. } } When I run python manage.py migrate I get the following error: ValueError: Cannot quote parameter value <django.contrib.postgres.fields.jsonb.JsonAdapter object at 0x000001A3B7C5B448> of type <class 'django.contrib. postgres.fields.jsonb.JsonAdapter'> Is there any way to allow the application to still work even though there are postgres specific fields? -
DetailView running twice before display
I have a DetailView which is running twice if url hit once views.py class PortfolioDetailedView(DetailView): model = Portfolio slug_field = 'slug' def get_object(self): obj = super().get_object() obj.view_count+=1 obj.save() return get_object() logs while getting data [17/Jul/2020 19:53:18] "GET /portfolio/detail/test2/ HTTP/1.1" 200 14893 [17/Jul/2020 19:53:20] "GET /portfolio/detail/test2/ HTTP/1.1" 200 14893 -
How to call a value of choice list in template from module in Django?
Please help to call all posts' title that have a particular category in my template. This is my code: models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) class Post(models.Model): choices = Category.objects.all().values_list('name', 'name') choice_list = [] first=Priority.objects.all().values_list('prior_name','prior_name') prior_list=[] for i in first: prior_list.append(i) for i in choices: choice_list.append(i) title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) priority=models.CharField(max_length=100,choices=prior_list, null=True) date_posted= models.DateTimeField(default=timezone.now) author =models.ForeignKey(User, on_delete=models.CASCADE) category=models.CharField(max_length=100,choices=choice_list) snippet=models.CharField(max_length=255, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) and here is the views.py. which is incorrect since it just sorts all posts def topics(request): context = { 'posts': Post.objects.all() } return render(request,'blog/list_of_topics.html',context) And this is code from template {% for post in posts %} <ul style=" text-align:center"> <li><a href="{% url 'post-detail' post.id %}">{{post.title}}</a></li> </ul> {% endfor %} I guess i have to write. some kind of condition but i am not sure how to do it, I want to sort all my posts title based on category, which is category variable in Post model Thank you in advance, will appreciate any tips -
Is it possible to layout different shaped and sized grid items for a CSS grid using Django?
So I have 8 columns and half sized rows, so two rows and one column make a perfect square. I have 4 separate shaped and sized block shapes including but not limited to; 2Rx1C (square), 2Rx2C(rectangle), 1Rx2C (vertical rectangle) and 4Rx1C (skinny rectangle);(R==row, C==columns). I need users to be able to post a certain kind of block and to have an algorithm lay these blocks out on a grid so they appear to have been placed there scattered. Is this possible using Django templates where I store the block shape with a style for its position in a template block with all respective positions for that block; and create an array that links the post to their respective block shape. Then using if statements for posts to link the previous list item's block and position to find out where the next block should go? I'll have these posts render in chunks and just repeat the algorithm again with different posts. -
MultiValueDictKeyError at /search/, Why am I getting this error?
I am very beginner at django, And fall onto this error MultiValueDictKeyError, I've got this error earlier, And I solved it after adding the name tag to HTML file, but this time I am not able to figure it out. please help me fix this error views.py from django.shortcuts import render from .models import Post # Create your views here. def main(request): return render(request, "blog/index.html", {"Posts":Post.objects.all()}) def viewpost(request, pk): return render(request, "blog/viewpost.html", {"Posts":Post.objects.get(id = pk)}) def search(request): if request.method == "GET": search = request.GET["search"] for post in Post.objects.all(): if search in post.Title: return render(request, "blog/search.html") else: return render(request, "blog/search.html", { "message": "Not Found" }) search.html I am sorry this file is quite too big but its on the third block. I have commented out that block. {% extends 'blog/layout.html' %} {% load static %} {% block body %} <!-- Page Content --> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8"> <h1 class="my-4">Page Heading <small>Secondary Text</small> </h1> <!-- Blog Post --> {% for post in Posts %} <div class="card mb-4"> <img class="card-img-top" src="http://placehold.it/750x300" alt="Card image cap"> <div class="card-body"> <h2 class="card-title">{{ post.Title }}</h2> <p class="card-text">{{ post.Description }}</p> <a href="#" class="btn btn-primary">Read More &rarr;</a> </div> <div class="card-footer text-muted"> Posted on … -
Django save large files
I'm creating a website where the user is able to upload large files. Around 100-300Mb. I'm using django but I want to know what is the best option to save the files. Should I just add them to my user database? Or should I create a media folder and save the files there. If so then this would mean that I have to save the name of the file in my user database? Please let me know how you would tackle this issue. -
Please help me with Django project
I have a Django project about To do list and I have a problem. I want to delete an element in the home page when user click it and then add it in another page. My index.html template: <div class="icons__tick"><a href="{% url 'completed_tasks'%}"><img src="{% static 'main/images/icons/tick.svg'%}" alt="Completed Task" class="icons__thumb"></a> </div> <form action="{% url 'complete_todo' todo.id%}" method="post"> {% csrf_token%} <button class="complete_button" type="submit" >Completed</button> My urls.py: path('completed_tasks', views.Comp.completed_tasks, name='completed_tasks'), path('complete_todo/<int:todo_id>', views.Comp.complete_todo, name='complete_todo') My views.py: class Comp: completed_todo = Todo.objects.get(id=task_id) def completed_tasks(self): return render(self, 'main/completed_tasks.html') def complete_todo(self, todo_id): global task_id task_id = todo_id completed_todo = Todo.objects.get(id=todo_id) return HttpResponseRedirect('/') So when the user clicks on the "Completed" button I want to from home page delete the element that was clicked and then add it to another page. Hope you'll find some time for my problem, thank you in advance. -
How to put django model form in a ready made template
I have a model form that allows user to post and upload pics. It works normally on a blank template. So now i want to put the put the form in a ready made template that has field for creating posts and upload pics. My models.py: class Post(models.Model): post = models.CharField(max_length=3000) pic = models.ImageField(blank=True) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Forms.py class PostForm(forms.ModelForm): post = forms.CharField(widget=forms.TextInput()) views.py class BaseView(TemplateView): template_name = 'base.html' def get(self, request): form = PostForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) args = {'form': form,'users': users, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() pics = form.cleaned_data['pic'] text = form.cleaned_data['post'] form = PostForm() return redirect('base') args = {'form': form, 'text': text, 'pics':pics} return render(request, self.template_name, args) And in the template i want to use the fields is like this: <div class="create-post"> <div class="row"> <div class="col-md-7 col-sm-7"> <div class="form-group"> <img src="images/users/user-1.jpg" alt="" class="profile-photo-md" /> <textarea name="texts" id="exampleTextarea" cols="30" rows="1" class="form-control" placeholder="Write what you wish"></textarea> </div> </div> <div class="col-md-5 col-sm-5"> <div class="tools"> <ul class="publishing-tools list-inline"> <li><a href="#"><i class="ion-images"></i></a></li> </ul> <button class="btn btn-primary pull-right">Publish</button> </div> </div> </div> </div> help please if you … -
Are Django's auth backend and DRF's token authentication just two approaches to the same thing?
In my django web app, I am currently using a custom AuthBackend class that extends django's BaseBackend, as well as DRF's UserTokenAuthentication. Am I right to think that I only need one of these approaches? Or is there a reason to use django's login() function, even if i am using DRF's token auth? I know it stores the user in the session, so I guess that would make passing and authenticating a token pointless? What's my best approach? Cheers :) -
Django Model Forms with Multi-Level Foreign Keys
I need to create a model form in Django and have the following arbitrary scenario. Real Estates ============ ID ...some extra fields... CityID Cities ====== ID Name Region ====== ID Name Country ======= ID Name What I would like to do is to let user choose the Country first, then Region and lastly the City. (Populate the child category with javascript after user selects the parent category.) However, I don't want to add the 'Region' and 'Country' fields to the 'Real Estate' table. The order of the fields are also important, that is, 1) Country, 2) Region and 3) City. Can you suggest any approach to this? Thanks! -
Best way to migrate CSV files to Django SQL back-end?
I have a directory full of CSV files which I would like to use for the back-end of my Django web-app but I am struggling to populate my Django models with the data from the CSV files. This is because some of the files are .csv join tables connecting the other .csv files in the directory. When I try to map the relationships from the CSV files to the SQL database I always run into problems. Is there a better or more straight forward way of populating these models? -
i want to sum this field called 'amount' using aggragate in django rest framework
am using model manager to sum the field, I want to get the sum of the amount in total_data method am summing the 'amount' field and counting 'item' by date() is filtering items added in a week this is my model.py class ExpenseQueryManager(models.query.QuerySet): def total_data(self): return self.aggregate(Sum('amount'),Count('item')) def by_date(self): now=timezone.now()-timezone.timedelta(days=7) return self.filter(timestamp__week__gte=now.weekday()) class ExpenseManager(models.Manager): def get_queryset(self): return ExpenseQueryManager(self.model,using=self.db) class Expense(models.Model): user=models.ForeignKey(User,default=1,on_delete=models.CASCADE) income = models.IntegerField(default=0) item=models.CharField(max_length=120) amount=models.IntegerField() timestamp = models.DateTimeField(auto_now_add=False, auto_now=True) objects= ExpenseManager() def __str__(self): return self.item this is my serializer.py class ExpenseSerializer(serializers.ModelSerializer): class Meta: model=Expense fields=['id','user','item','amount'] read_only_field=['user'] by_date() and total_data() are methods that am calling from the model manager this is view.py class ExpenseList(mixins.CreateModelMixin,generics.ListAPIView): serializer_class =ExpenseSerializer def get_queryset(self,): qs=Expense.objects.all() x=qs.order_by("-timestamp").by_date() total_amount = qs.total_data() return x def perform_create(self, serializer): serializer.save(user=self.request.user) def post(self,request,*args,**kwargs): return self.create(request,*args,**kwargs) -
Django shell returning memory address not attribute
Sorry for asking this, but I can't find anything on google. I've got this far: p = Project.object.get(id=1) p.update But it shows a memory address when I'm expecting a list. I've tried: p.update() p.update.all() p.update.list p.update.list() p.update[1] What do I need at the end to get it to show me words not a memory address please. In fact can someone point me at some tutorial that covers the shell so I don't keep getting stuck. -
How to create a folder with subfolder for each project created?
How can I create a folder and subfolders each time, I am creating a project. The location of the folders could be located in media ----- Projects |----Project 1 |-----Subfolder 1 | |-----Subfolder 2 | |-----Subfolder 3 | |----Project 2 |-----Subfolder 1 | |-----Subfolder 2 | |-----Subfolder 3 | |----Project 3 |-----Subfolder 1 |-----Subfolder 2 |-----Subfolder 3 views.py def create_project(request): form = ProjectForm(request.POST or None, request.FILES or None) if form.is_valid(): project = form.save(commit=False) project.save() return render(request, 'projects/detail.html', {'project': project}) context = { "form": form, } return render(request, 'projects/create_project.html', context) -
Heroku CI with pytest-django fails - module "doesn't declare an explicit app_label"
I've deployed a Django app and would like to get Heroku CI setup. I have a suite of tests that run locally. On heroku CI test setup succeeds and then the test runner fails with the following error log (abbreviated): ==================================== ERRORS ==================================== ________________________ ERROR collecting test session _________________________ .heroku/python/lib/python3.8/site-packages/_pytest/config/__init__.py:495: in _importconftest return self._conftestpath2mod[key] E KeyError: PosixPath('/app/.heroku/python/lib/python3.8/site-packages/django_dynamic_fixture/tests/conftest.py') During handling of the above exception, another exception occurred: ... .heroku/python/lib/python3.8/site-packages/django/db/models/base.py:112: in __new__ raise RuntimeError( E RuntimeError: Model class django_dynamic_fixture.models_sample_app.Publisher doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. As you can see, this error originates in an imported module (django_dynamic_fixture) which runs fine locally. I think this may be due to how heroku ci is configured and therefore I don't know what I can do to solve this issue. The doesn't declare an explicit app_label... error is probably due to mixing absolute and relative imports, or from a missing django.contrib.sites app in the django settings file. However because the tests run locally, I'm unsure how to proceed. -
Is there anyway to structure data to python list or tuple that is efficient
Is there any way to structure a data fetched from database, currently I use append but it become slow specially when data fetched is more than 1k courses = [] for i in departments: for course in i.course_set.all(): course = [course.name] info_list = [] for year in range(1, 5): info = [year, (['Regular'], ['Irregular'])] info_list.append(info) count = 0 for gender in ['male', 'female']: regular = students.filter(year_level=year, status='regular', course=course).count() irregular = students.filter(year_level=year, status='irregular', course=course).count() info[1][0].append(regular) info[1][1].append(irregular) regular = students.filter(year_level=year, status='regular', course=course).count() irregular = students.filter(year_level=year,status='irregular', course=course).count() info[1][0].append(regular) info[1][1].append(irregular) info[1][2].append(cross) total = regular + irregular count += total info.append(count) program.append(info_list) male = students.filter(gender='male', course=course).count() female = students.filter(gender='female', course=course).count() overall = students.filter(gender=None), course=course).count() program.append(["", "Total", "", male, female, overall, overall]) courses.append(program) I'm not sure if it is the append or the query hits multiple times on the database. After I get it I will use it to output the data to pdf tables -
written whole javascrpit code but add to cart function is not working and no error is being shown
I am working in Django. This is my javascript code, in this hello world is getting printed on console but when I am clicking 'add to cart' then clicked is not getting printed: console.log("Hello world") var updateBtns = document.getElementsByClassName('update-cart') for(var i=0;i<updateBtns.length;i++){ updateBtns[i].addEventListener('click',function(){ var action = this.dataset.action console.log('clicked') }) } This is part of my html code containing button: <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{i.product_name}}</h5> <p class="card-text">{{i.desc}}</p> <button data-product="pr{{i.id}}" data-actions="add" class="btn btn-primary add-btn update-cart">Add to Cart</button> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> </div> {% block js %} <script type="text/javascript" src="{% static 'js/cart.js' %}"></script> {% endblock %} No error are getting printed on running this. Please Help. Thanks in advance. -
Django RF, How to pass user instance for object creation
I am using Django Rest framework+React JS, uses session authentication. When explicitly I pass user id in POST request, it saves in database. let data = { product: 11, quantity: 1, user: 1 }; When remove the user id it fails to save and gives error, let data = { product: 11, quantity: 1 }; How can I mitigate the error ? models.py class Cart(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) The POST function in React let data = { product: 11, quantity: 1, user: 1 }; const endpoint = "/api/CartCreate/11/1/"; apiService(endpoint, "POST", data) //note: api service is like axios with csrftoken view class CartCreate(generics.CreateAPIView): serializer_class = CartSerializer queryset = Cart.objects.all() permission_classes = [IsAuthenticated] def perform_create(self, serializer): user = self.request.user pk = self.kwargs.get("pk") product = Product.objects.get(pk=pk) quantity = self.kwargs.get("quantity") serializer.save(user=user, product=product,quantity=quantity) -
I have a Django Question regarding the command line regarding running python manage.py test
I got this error when I was running the command python manage.py test in the absolute pathname C:\Users\vitorfs\Development\myproject\myproject on the command line which I opened by selecting Run as Admin on Windows. In boards.py, I have the following from django.core.urlresolvers import reverse from django.test import TestCase class HomeTests(TestCase): def test_home_view_status_code(self): url = reverse('home') response = self.client.get(url) self.assertEquals(response.status_code, 200) I am having trouble fixing the error. I followed the tutorial on Django at https://simpleisbetterthancomplex.com/series/2017/09/11/a-complete-beginners-guide-to-django-part-2.html Can you show me what this means and help me fix this error? Just to let you know, I'm learning Python and Django for fun. -
ValueError: too many values to unpack when passing array to include method
I'm trying to pass an array to include method, and it returns an error ValueError: too many values to unpack (expected 3) What's wrong? from django.contrib import admin from django.urls import path, include from apps.management.urls import router as management_router urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('', include([ path('management/', management_router.urls) ])), ] -
Send variables to a template from setting.py
I'm triyng to send two variables from settings.py to a template. At the end of settings.py I've putted that variables: settings.py . . . # MapBox Studio mapbox_user = 'a_string' mapbox_token = 'a_string' Then I've created a context_processors: context_processors.py from django.conf import settings def mapbox_data(request): mapbox_user = settings.mapbox_user mapbox_token = settings.mapbox_token context = { 'user': mapbox_user, 'token': mapbox_token, } return context And at the end I've putted it inside context_processors list: '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 context 'webgis.context_processors.mapbox_data', ], Now I use {{ user }} and {{ token }} inside my template but I see this error: AttributeError: 'Settings' object has no attribute 'mapbox_user' It is the first time that I try to pass data from settings.py to a template. What I've wrong? If I use user and token directly into HTML I can see my map without problems. -
Why Django admin shows different kind of UI interface?
I am new to django, when i created a project and goes to 'url/admin'. It shows the default django admin UI. But now, when i navigate to 'url/admin'. It shows different UI of admin login than default one. I had attached the screenshot of it, how it is looking. Can you please check and tell me how to make this screen to look as default one of django admin screen. Note: Kindly see the url too in screenshot. Why after 'url/admin' more string shown. -
AttributeError: 'tuple' object has no attribute 'get' Django
I'm a beginner learning django i've checked multiple times but didn't findout where its returning tuple instead of dictionary can anyone help. Error Even understanding this error is really daunting for me if anyone explain it would be great forms.py from django import forms from .models import ModelClas class FormClass(forms.ModelForm): passw = forms.CharField(widget=forms.PasswordInput()) repass = forms.CharField(widget=forms.PasswordInput()) def clean(self): super(FormClass, self).clean() inputpass = self.cleaned_data.get('passw') inputrepass = self.cleaned_data.get('repass') if inputpass != inputrepass: raise forms.ValidationError("Password not matched. please type again.") return inputpass, inputrepass class Meta: model = ModelClas fields = '__all__' models.py from django.db import models # Create your models here. class ModelClas(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) email = models.EmailField() mobile = models.IntegerField() passw = models.CharField(max_length=30) repass = models.CharField(max_length=30) views.py def signpage(request): if request.method == 'GET': form = forms.FormClass() if request.method == 'POST': form = forms.FormClass(request.POST) if form.is_valid(): print("Validation Successfull") print("FName :", form.cleaned_data['fname']) print("LName :", form.cleaned_data['lname']) print("Email :", form.cleaned_data['email']) print("Mobile :", form.cleaned_data['mobile']) print("Password :", form.cleaned_data['passw']) print("Re-type Password :", form.cleaned_data['repass']) form.save(commit=True) return HttpResponseRedirect('/accounts/logout') return render(request, 'registration/signup.html', {'form':form}) Error Even understanding this error is really daunting for me if anyone explain it would be great Environment: Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 3.0.6 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
How can i authenticate my extended model from AbstractBaseUser?
I extended my model from Django User Model, but in the database the password isn't encrypted, using the OneToOneField relationship i could authenticate the username and password credentials but i don't know how to authenticate using the AbstractBaseUser way. settings.AUTH_USER_MODEL = 'log.LogUpModel'. from django.contrib.auth.models import AbstractBaseUser from django.db import models # Create your models here. class LogUpModel(AbstractBaseUser): shop = models.CharField(max_length=30, unique=True) owner = models.CharField(max_length=30) description = models.TextField(max_length=150) picture = models.ImageField(upload_to='media/') USERNAME_FIELD = 'shop' def __str__(self): return self.shop -
Docker Compose Up is running while with the same image its not running the image?
docker-compose up working fine. Screenshot attached. docker run testbackend_web:latest Above Command not working with the build Can someone help in the same?