Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding encode header for REST framework
I am using Django REST framework It returns Content-Type: application/json in header. Normally it works, but some browser needs the precise header such as Content-Type: application/json; charset=utf-8 How can I do this ?? I just return the Response here where should I set the header?? class SmartTagViewSet(viewsets.ModelViewSet): queryset = Mood.objects.all() serializer_class = SmartTagSerializer def list(self,request,*args,**kwargs): objs = SmartTag.objects.all() custom_data = { 'items': SmartTagSerializer(objs, many=True).data } custom_data.update({ 'meta':{"api":"SmartTag"} }) return Response(custom_data) -
order_by date_join in Django
I am displaying user information to the admin dashboard I want to order Users by their join date. and on another page, I want to display only 10 users information which are recently logged in I am filtering user data like this data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)) please help me to do this. Thanks in Advance -
Django: view tracking data with tens-of-thousands of views per day
I have a Django app with a Postgres backend. Users can make posts and view them. "Views" sit around the high-tens-of-thousands to 100K+ per day total. We want to track views so that we can filter out posts users have already seen from their home timeline. In the future, this will also be used for algorithmically surfacing content to users better. My original thought was to store these views as rows in the database as another table: class PostView(models.Model): post = models.ForeignKey(Post) user = models.ForeignKey(User) count = models.IntegerField(default=1) However this would quickly overwhelm the database with hundreds of thousands (or millions) of extra rows in weeks, (which I believe would overwhelm the database? Would or slow it down)? Is there perhaps another way that people typically store this sort of view data? Or is my approach effectively fine? -
Django HTML Create Buttons for Not Null Fields Only
I'm fairly new to Django and couldn't find a way to do this yet. I have a model like this: class Profile(models.Model): user = models.OneToOneField("User", on_delete=models.SET_NULL, null=True) user_name = models.CharField(max_length=50) linkedin = models.URLField(max_length=254, null=True, blank=True) instagram = models.URLField(max_length=254, null=True, blank=True) spotify = models.URLField(max_length=254, null=True, blank=True) On my HTML, I have buttons for each social media field, but I don't want to show them if they are null. How can I create a for loop that will loop through the social media fields only and create buttons for only not null fields? -
How can I Properly use Django Class Based View UserPassesTestMixin in UpdateView
I am working on a Django project where users would have one bank record. And I don't want them to be able to update another one's bank record except their own. I want to use Django UserPassesTestMixin to perform this restriction but I am getting 403 Forbidden error any time I try to access the UpdateView. Here is my Models code: class BankDetails(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) bank = models.CharField(max_length=30, choices=BANK, blank=True, null=True) account = models.CharField(max_length=20, blank=True, default=None, null = True) name = models.CharField(max_length=60, blank=True, null=True) branch = models.CharField(max_length=60, blank=True, null = True) date = models.DateTimeField(auto_now_add=True) Here is Class based views code: from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin, UserPassesTestMixin class UpdateBank(LoginRequiredMixin, UserPassesTestMixin, UpdateView): template_name = 'user/edit_bank.html' model = BankDetails form_class = ApplicantBankForm def get_success_url(self): return reverse_lazy('bank-detail',kwargs={'pk': self.get_object().id}) def test_func(self): return self.get_object().applicant_id == self.request.user.pk class BankDetailView(LoginRequiredMixin, DetailView): template_name = 'user/bank_detail.html' model = BankDetails def get_success_url(self): return reverse_lazy('app-submit', kwargs = {'pk' : self.get_object().id}) Someone should please help. Thanks in anticipation for your answer. -
Django ORM objects.get() Related Questin: Is it legit to use .get() as if it's .filter()?
I often see that, regardless of the model, people often use Model.objects.get(id=id) or .get(product_name=product_name) or .get(cart=my_cart) -- but I now see a piece of code that is using .get() like it's a filter such as .get(product=product, cart=my_cart), is this going to work as intended? -
Django Cookiecutter Database restore
I'm trying to restore the database with the maintenance script provided. But there is a check in the script which doesn't allow me to restore if the user is postgres. Any reason for that ? -
Unable to access request headers in decorator - django 4.0.4
Using class based views. I have a decorator that retrieves headers for verification. However I get this error accessing the request headers in the decorator: Decorator exception 'DetailsView' object has no attribute 'headers' I must emphasize that accessing request headers in the view function works fine. View function: class DetailsView(View): @check_access def get(self, request): res = { 'status': 200, 'response': 'heeaders test.', 'test': 'okay' } return HttpResponse(JsonResponse(res, safe=False), content_type='text/json') Decorator: def check_access(): def decorator(view_function): def wrap(request, *args, **kwargs): try: print("headers", request.headers) return view_function(request, *args, **kwargs) except Exception as e: return HttpResponse('Unauthorized', status=401) return wrap return decorator Kindly assist. Thanks in advance. -
Django rest framework function base view how to get object by string not id
Problem: I trying to path like this --> path('Image/<str>', views.getImage, name='imageCategory'), to get image filter by category --> http://127.0.0.1:8000/Image/TV #-->Model.py from django.db import models class Post(models.Model): Topic = models.CharField(max_length=250, default='') Desc = models.CharField(max_length=750, default='') Link = models.TextField(default='') def __str__(self): return str(self.Topic) class Category(models.Model): categoryName = models.CharField(max_length=50, default='') def __str__(self): return str(self.categoryName) class PostImage(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, null=True, related_name='post_name') category = models.ForeignKey( Category, on_delete=models.CASCADE, null=True, related_name='category_name') images = models.FileField(upload_to='images/') def __str__(self): return str(self.post) #-->Serializer.py from rest_framework.serializers import ModelSerializer from rest_framework import serializers from .models import Post, PostImage class BlogSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' class ImageSerializer(ModelSerializer): topic_link = serializers.CharField(source='post.Link', read_only=True) Category = serializers.CharField(source='category', read_only=True) class Meta: model = PostImage fields = '__all__' #-->view.py from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Post, PostImage from .Serializer import BlogSerializer, ImageSerializer # Create your views here. @api_view(['GET']) def getNames(request): Blog = Post.objects.all() serializer = BlogSerializer(Blog, many=True) return Response(serializer.data) @api_view(['GET']) def getName(request, pk): Blog = Post.objects.get(id=pk) serializer = BlogSerializer(Blog, many=False) return Response(serializer.data) #my problem part @api_view(['GET']) def getImage(request): image = PostImage.objects.get(Category=request.Category) serializer = ImageSerializer(image, many=True) return Response(serializer.data) #-->urls.py from django.urls import path from . import views urlpatterns = [ path('blogs/', views.getNames, name='blog'), path('blogs/<pk>', … -
How to redirect to new blog post in React/Django
I'm building a blog site with React/Django. Here's my basic NewBlog component: import React, {useState} from 'react'; import { Link } from 'react-router-dom'; function NewBlog(props) { const [title, setTitle] = useState('') const [body, setBody] = useState('') function postBlog() { fetch('http://localhost:8000/api/blogs/', { "headers": { "content-type": "application/json", }, "body": JSON.stringify({ "title": title, "author": 1, "body": body }), "method":"POST", }) } return ( <div> <form onSubmit={postBlog}> <textarea className='title' placeholder='title...' onChange={(ev) => setTitle(ev.target.value)} value={title}></textarea> <textarea className='body' placeholder='' onChange={(ev) => setBody(ev.target.value)} value={body}></textarea> <button>POST</button> </form> <div> <Link to='/blog'>BACK</Link> </div> </div> ); } export default NewBlog; This works to POST a new blog, but after I submit the form, I can't figure out how to redirect to that specific blog, which would just be http://localhost:8000/blogs/BLOG_ID. Instead, the form is just cleared, and I have to go <Link to='/blog'>BACK</Link> to the BlogList to see the new blog rendered. Now, I know with Django you can use their form to post a blog, and, once posted, it redirects to that blog_detail. My issue is I don't know how to do that using React on the front end. Is there some kind of Redirect or Route I can use? Also, I'm not sure how I'd even retrieve that just-posted blog's … -
Django Leaflet: Add form fields for latitude and longitude
I am using the django-leaflet package to display the map in the django admin for a PointField. However, I wanted to put fields so that it would be possible to write the latitude and longitude, as an alternative to selecting the point on the map. How can I add these fields to the form? Note: the Django Map Widgets package has the ability to insert coordinates, but I don't want to use it because it requires a key. -
Django FormView dispatch method is called, even though UserPassesTestMixin's test_func() has returned False
I have a class based form view that implements both LoginRequiredMixin and UserPassesTestMixin class BookingCreateView(LoginRequiredMixin, UserPassesTestMixin, FormView): def dispatch(self, request, *args, **kwargs): ... def test_func(self): return is_customer(self.request.user) When I visit the page while logged in as a user that fails the test_func, instead of getting a 404, as a result of a failed test_func, the code in my view's dispatch method is executing... Shouldn't the test_func() be called before dispatch() ? and if the result of test_func() is False, shouldn't view rendering stop at this point? -
Are "required" HTML fields not enforced on Django Admin intermediate pages?
I have the following abbreviated HTML for an intermediate Django admin page: <!DOCTYPE html> {% extends base_url %} {% block content %} <form action="" method="post"> ... <select name="my_name" id="my_id" required> ... </select> ... <input type="hidden" name="action" value="my_action" /> <input type="submit" name="apply" value="Update" /> </form> {% endblock %} However, my required attribute does not seem to work, and clicking "Update" submits the form even if no selection has been made. Am I missing something special about how Django builds intermediate pages? Happy to provide more code if needed, just removed most of it for brevity's sake. -
How can I filter a modelformset_factory?
I have been coding a personal project in which several user can post educational videos (each video has a language, a foreignkey). I tried to implement a function in which a user add a word to a video (or a various words). But I couldn't to filter a modelformset_factory to show only words that have the same video's language. For instance: Below I have a class which its language is 'inglês', I can see it in de 'aula_lingua'. But my combo box shows words that have another languages, for example the word 'test Norsk_noruegues' which has 'noruegues' as its language. But I would like to filter the words and show only words that have the same laguange of the video. enter image description here Models: class Palavra(models.Model): palavra = models.CharField(max_length=40) lingua = models.ForeignKey( Lingua, null=True, blank=True, on_delete=models.CASCADE) class Aula(models.Model): aula = models.CharField(max_length=250) aula_gravada = models.FileField(upload_to='aula/%Y/%m') lingua = models.ForeignKey( Lingua, blank=True, null=True, on_delete=models.CASCADE) class AulaPalavra(models.Model): aula = models.ForeignKey(Aula, on_delete=models.CASCADE) palavra = models.ForeignKey(Palavra, on_delete=models.DO_NOTHING) Formset: PalavraAulaForms = modelformset_factory( models.AulaPalavra, fields=('palavra',), extra=1, ) View: class TesteAdicionaPalavraAula(TemplateView, DetailView): template_name = 'ensino/teste_add_palavra.html' model = Aula def get(self, *args, **kwargs): formset = PalavraAulaForms( queryset=Palavra.objects.filter( lingua=self.get_object().lingua ) ) return self.render_to_response( { 'add_palavra': formset, 'aula': self.get_object(), }, ) … -
Django: how to delete item in one model AND change many to many relationship in another model that was linked to the first model?
This website allows users to select Rolling Stones concerts they've been to. It will add the Concert and the Song to the model from the API if they select it. And Concert.song has a many to many relationship with the user model. If a user removes a concert from their concert list, the songs still appear. I don't necessarily want the song to be deleted because they could have heard the song from another concert. I also don't think it's the best idea to change the user of the song from the usernmae to --- (because null=True). I think my only choice is to change the usersonglist.html template tags somehow? Models.py class Concert(models.Model): venue = models.CharField(max_length=200, null=True) concertid = models.CharField(max_length = 200, null=False, default='didnotsaveproperly') date = models.DateField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=200, null=True) user = models.ForeignKey(USER_MODEL, related_name="concerts", on_delete=models.CASCADE, null=True) song = models.ManyToManyField("Song", blank=True, null=True) def __str__(self): return str(self.concertid) + " " + str(self.venue) + " " + str(self.date) class Song(models.Model): name = models.CharField(max_length = 100, null=True) user = models.ForeignKey(USER_MODEL, related_name="songs", on_delete=models.CASCADE, null=True) def __str__(self): return self.name URLS.py urlpatterns = [ path("", views.display_concerts, name="choose_concerts"), path('add/<str:concertdict>/', views.log_concert_and_song, name='concert_add'), path('userconcerts/', views.ConcertListView.as_view(), name='user_concert_list'), path('<int:pk>/delete/', views.ConcertDeleteView.as_view(), name='delete_concert'), path('usersonglist/', views.SongListView.as_view(), name='user_song_list'), ] Views.py/SongListView for … -
How to get a field from another model which is linked with OneToOne relationship?
I have my main User model with an 'email' field (and other fields). But I created another model called Profile, where I need to pass user's email to it. models.py for user: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() and for profile: class Profile(models.Model): user = models.OneToOneField('authentication.User', on_delete=models.CASCADE) phone_number = models.IntegerField(blank=True, unique=True) is_subscribed = models.BooleanField(default=False) email = ... Task sounds quite simple, but using user.email doesn't seem to work as well as user__email or a user.get_email property. What should I write instead of ... ? -
How to change ON expression in django-orm select_related()
So i have this models class ApplicationForHelp(BaseModel): user = models.ForeignKey(User, related_name="applications", on_delete=models.CASCADE) tags = models.ManyToManyField(TagsForApplication, related_name="applications") title = models.CharField(max_length=50) description = models.TextField() is_anonymous = models.BooleanField(default=False) place = models.TextField(null=True) And user model so if do ApplicationForHelp.objects.filter().select_related('user') what it does : left join ON application.user_id = user.id what i want : left join ON (application.user_id = user.id and application.is_anonymous=False) -
module 'popenv.core' has no attribute 'project'
Trying to assist my friend set up a new Django/Python project remotely. They've set up a virtual environment on their Windows machine using Linux, and it throws the following error when trying to install Django in the project directory: Creating a virtualenv for this project… Using /usr/bin/python3.8 (3.8.10) to create virtualenv… /usr/bin/python3: No module named pipenv.pew Virtualenv location: Installing django… Looking in indexes: https://pypi.python.org/simple Requirement already satisfied: django in /home/[username]/.local/lib/python3.8/site-packages (4.0.4) Requirement already satisfied: backports.zoneinfo; python_version < "3.9" in /home/[username]/.local/lib/python3.8/site-packages (from django) (0.2.1) Requirement already satisfied: asgiref<4,>=3.4.1 in /home/[username]/.local/lib/python3.8/site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in /home/[username]/.local/lib/python3.8/site-packages (from django) (0.4.2) Adding django to Pipfile's [packages]… Creating a virtualenv for this project… Using /usr/bin/python3 (3.8.10) to create virtualenv… /usr/bin/python3: No module named pipenv.pew Virtualenv location: Pipfile.lock not found, creating… Locking [dev-packages] dependencies… 3/dist-packages/pipenv/resolver.py", line 52, in main project = pipenv.core.project AttributeError: module 'pipenv.core' has no attribute 'project' Does anyone have experience with this error and how to resolve it? -
How to assign a link to a certain item in a list in Django?
a created a table in which it contains names for datasets in a column, and the links to view these datasets in another column. My aim is to retrieve the dataset in which it was clicked to be reviewed. Here is the HTML Code <table> <tr> <th>File Name</th> <th>Link</th> {% for files in names %} <tr> <td> {{ files }} </td> <td> <a href="{% url 'single-dataset' id=files %}">View Dataset</a> </td> </tr> {% endfor %} </tr> </table> Single-dataset is the page that will view each dataset separately Here is the Views.py Code def read_datasets(request, id): file = requests.post.objects.get(id=id) path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] file_names = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) file_names.append(files[i]) return render(request,'blog/view_datasets.html',{'dataframes':dataframes_list_html, 'names': file_names}) and finally the urls.py path('view_dataset/', views.read_datasets, name = 'view_dataset'), path('test/', views.one_dataset, name='single-dataset'), I want to click on one of the links that says View Dataset and be able to retrieve the right dataset in the single-dataset page. -
Redirect and Login to Django from External Site
I'm building a signup page for my Django application on an external site. Once a user has completed signup, I create a user and they should be redirected to a Django site and logged in. I'm having trouble redirecting an external user to an authenticated page. Does anyone have any idea how to do this or if it's possible? Thanks! -
PUT Request not Updating data-Django
So I am using Postman to get my request. My GET and POST appear to be working fine. It's only when I go to update the data with PUT that its where I am running into the hiccup. Postman actually sends data back as if the object is being updated, but when I go to check via GET it's the same data as before. I have tried adding the hive data to the serializer.save, but it tells me I'm adding too many parameters. Any help will be greatly appreciated here. models class Inspection(models.Model): hive = models.ForeignKey(Hive, on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) eggs = models.IntegerField() larvae = models.IntegerField() sealed_brood = models.IntegerField() covered_bees = models.IntegerField() nectar_honey = models.IntegerField() pollen = models.IntegerField() pest_spotted = models.CharField(max_length=200) pest_action = models.CharField(max_length=200) notes_concerns = models.CharField(max_length=300) `` **serializers** class InspectionSerializer(serializers.ModelSerializer): class Meta: model = Inspection fields = ['id', 'eggs', 'larvae', 'sealed_brood', 'covered_bees', 'nectar_honey', 'nectar_honey', 'pollen', 'pest_spotted', 'pest_action', 'notes_concerns','user_id','hive','hive_id'] depth = 1 hive_id = serializers.IntegerField(write_only=True) VIEWS @api_view(['GET', 'POST','PUT']) @permission_classes([IsAuthenticated]) def inspection_details(request, pk): hive = get_object_or_404(Hive, pk=pk) inspection = Inspection.objects.filter(hive_id = hive.id, user=request.user) if request.method == "GET": serializer = InspectionSerializer(inspection, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = InspectionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save(user=request.user) return Response(serializer.data,status.HTTP_200_OK) elif request.method == 'PUT': serializer … -
Value does not change in admin dashboard and html template, view function shows the correct one
Value does not change in admin dahboard and html template that has a tag of the value, inrthe view function where the change happens,it print the correct value that was changed (order.status) def chef_order(request): chef = request.user.vendor orders = chef.orders.all() if 'btnform1' in request.POST: orderid = request.POST.get("orderid") order = Order.objects.get(pk=int(orderid)) sts = 'confirmed' order.status = "confirmed" print(order.get_status_display()) -
Special character encoding added - PDF Django
I have a function to create a simple PDF. But when working on special characters, it returns something like that. How do I correctly save characters such as śćźż in my pdf file? Views.py (oficial doc) def some_view_aa(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello AZX AĄĄŻĄ world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') -
Why Django sessions is slow while variable working faster?
I have Django view def load(request): store = request.GET.getlist('store', 'None') text = connetction_local(store[:-1]) for _ in tqdm(range(1), desc='session TEXT'): # globals.text = text request.session['text'] = text for _ in tqdm(range(1), desc='session STORE'): # globals.store = store[:-1] request.session['store'] = store[:-1] return redirect('index') in view i am getting some values store and then create variable text with function. Then put theese variables in request.session to laod from another views and never lost added tqdm to check how long time takes each operation. after that just redirect to another view. But there is some problem what i didn't understand. When i put variables in django sessions then after last request.session['store'] = store[:-1] redirect takes some time 5 - 10 sek, but if i open both globals. and remove sessions, then this process takes less time than with sessions anybody can explain what there is going on? -
problems with get_context_data in ListView (django)
I need to show in a template two models: models.py: class Dimension(TimeStampedModel): level = models.ForeignKey('Level', verbose_name=_('Level'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) class Meta: verbose_name = _('Dimension') verbose_name_plural = _('Dimensions') def __str__(self): return self.name class Subdimension(TimeStampedModel): dimension = models.ForeignKey('Dimension', verbose_name=_('Dimension'), on_delete=models.CASCADE) name = models.CharField(verbose_name=('Name'), max_length=200) active = models.BooleanField(verbose_name=_('Active'), default=True) sort_order = models.PositiveIntegerField(verbose_name=_('sort order'), default=0) objects = managers.SubdimensionManager() class Meta: verbose_name = _('Subdimension') verbose_name_plural = _('Subdimensions') def __str__(self): return self.name and created a ListView of this views.py class DimensionListView(generic.ListView): model = models.Dimension template_name = 'dimension.html' context_object_name = 'dimensions' @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): self.user = self.request.user self.level = self.get_level(pk=kwargs.get('level_pk')) return super(DimensionListView, self).dispatch(request, *args, **kwargs) def get_level(self, pk): level = get_object_or_404(models.Level, pk=pk) return level def get_queryset(self): queryset = super(DimensionListView, self).get_queryset() return queryset.filter(active = True, level = self.level) def get_context_data(self, **kwargs): context = super(DimensionListView, self).get_context_data(**kwargs) context['subdimensions'] = models.Subdimension.objects.filter(active=True, dimension__level=self.level ) return context dimension_list_view = DimensionListView.as_view() I need to created a filter of the same 'dimension' so that in the template show only the subdimensions of that dimension. my template dimension.html: {% include 'base.html'%} {% block content %} <div class="row"> {% for dimension in dimensions %} <div class="col"> <div class="card" style="width: 18rem;"> <a class="">{{dimension.name}}</a> <div …