Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx : How to serve index.html and static contents with a single internal directive
I want to display my documentation (a single-page application built with React) only after authentication with my backend. My configuration : Nginx acts as a reverse proxy for the backend (Django) and serves static files like single-page-applications. Django, the backend, identifies the user and makes a request to Nginx using X-Accel-Redirect. So I proceed as follows: 1) Authentication on Django views.py def get_doc(request): if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] == 'foo': response = HttpResponse() response['Content-Type'] = '' response['X-Accel-Redirect'] = '/docs-auth/' return response else: return HttpResponse("Wrong password") else: form = PasswordForm() return render(request, 'docs/form.html', {'form': form}) urls.py urlpatterns = [ path('docs/', views.get_doc, name='documentation'), ] 2) Nginx serves the single-page application upstream backend { server web:8000; } server { location = /favicon.ico {access_log off;log_not_found off;} ... location /docs { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://backend; } location /docs-auth/ { internal; alias /home/foo/docs/; index index.html; try_files $uri $uri/ /docs/index.html; } location / { alias /home/foo/landing_page/; error_page 404 /404.html; index index.html; try_files $uri $uri/ =404; } } My problem is that the index.html file is served to the user but then the browser requests to access CSS and Javascript files are blocked because the browser … -
Cannot resolve keyword 'user' into field
I give views.py file & error file picture.Help me to solve the problem. enter image description here -
How to show user posted blog in user profile page as a my post list section in Django 3?
I am a new Django learner. I have created a blog website with two apps blog and user. In the user app, I have created a user profile page with two section user basic information and my post list. When user login and visit his/her profile page, my post list section shows only this user published post else shows you have not published any post yet. Everything is working fine but my post list section shows all of the posts in the blog. I want to show only this user's post, not other users' posts. I think the queryset in the view section needs to be modified but I cannot understand what would be. Here is my code - #Blog App: Post Model class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title #User App: Profile Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) pic = models.ImageField(default='images/default.jpg', upload_to='images') about = models.TextField(blank=True) #User App: views.py from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, ListView from blog.models import Post class UserProfileView(LoginRequiredMixin, ListView): queryset = Post.objects.all() template_name = "profile.html" … -
Custom ModelAdmin filter on calculated field
Example I'm trying to emulate: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filtering_calculated_fields.html FieldError at /admin/gallery/galleryitem/ Cannot resolve keyword 'on_sale' into field. Choices are: content_type, content_type_id, depth, description, direct_sale, direct_sale_extra_description, direct_sale_price, draft_title, expire_at, expired, external_links, first_published_at, formsubmission, gallery_images, go_live_at, group_permissions, has_unpublished_changes, id, index_entries, last_published_at, latest_revision_created_at, live, live_revision, live_revision_id, locked, locked_at, locked_by, locked_by_id, numchild, owner, owner_id, page_ptr, page_ptr_id, path, redirect, revisions, search_description, seo_title, show_in_menus, sites_rooted_here, slug, stock, title, url_path, view_restrictions, workflow_states, workflowpage models.py class GalleryItem(Page): parent_page_types = ['InstallationPage'] description = models.CharField(blank=True, max_length=250) direct_sale = models.BooleanField("On Sale", default=False, help_text="Check this box to list this item for sale directly on your website.") direct_sale_price = models.DecimalField("Sale price, $", blank=True, null=True, max_digits=6, decimal_places=2, help_text="Add more info about this item for the store page only.") direct_sale_extra_description = models.CharField("Addtional sale description (optional)", blank=True, max_length=250, ) stock = models.IntegerField("Number in stock", blank=True, null=True,) def external_sale(self): return bool(self.external_links.count()) def on_sale(self, obj): return obj.external_sale or obj.direct_sale class ExternalLink(Orderable): gallery_item = ParentalKey(GalleryItem, on_delete=models.CASCADE, related_name='external_links', help_text="Add details about the listing, ex. dimensions, framing.") description = models.CharField(blank=True, max_length=250) external_sale_url = models.URLField(blank=True, help_text="Add an external link to sell this.") wagtail_hooks.py class OnSaleFilter(SimpleListFilter): title = 'On Sale' parameter_name = 'on_sale' def lookups(self, request, model_admin): return ( ('Yes', 'Yes'), ('No', 'No'), ) def queryset(self, request, queryset): value = self.value() if value == 'Yes': … -
How to exclude value that is equal to zero while using Django aggregate queries for average or minimum
I have a database table where some of the values in a column for sales are zero. So far my query returns the min of all the values. Sale.objects.all().aggregate(minimum=Min('sale')) I want to exclude the values that are equal to zero while calculating the minimum or the average. So my question is how is that query done? -
Django or Node.js or GoLang for backend developer career?
I'm new in software development and want to become FULL STACK DEVELOPER, what technology should i learn Django or Node.js or GoLang or Angular for backend development so that i can get stable job and career in this area ? -
aadsts50011: the reply url specified in the request does not match the reply urls configured for the application: 'App id'. localhost configuration
I Followed this document for setting up the Microsoft Auth system by stuck up with error aadsts50011 this the image of my App in Azure portal -
Reduce the number of products after customer payment
I have a problem with reducing the amount(number) of products after the end payment of the user. The program I wrote reduces the number of products when the shopping cart is created, but if the user cancels the payment, I will have a problem and the number of products will decrease even though the user has not paid. I am looking for a way to reduce the number of products after payment by the user code -
cant save django model object in database
I use request.POST content to save a model object after creating and authenticating a user. the problem is that my user is created and authed but the model which extends that very users information in database is not saved while no error given. here is my code: @api_view(['POST']) @permission_classes((permissions.AllowAny, )) def login_api(request): post = request.POST user = authenticate( request, username=request.POST['username'], password=request.POST['password'] ) if user: school = school_info.objects.create( school_user=request.user, school_name=post['school_name'], school_manager_name=post['school_manager_name'], school_manager_phone=post['school_manager_phone'], class_count=post['class_count'], students_per_class=post['students_per_class'], daytime_importance=post['daytime_importance'], ) school = school.save() login(request, user) return Response({}, status=200) else: return Response({}, status=401) I tried ModelForms and obj.create().save() too but both of them aren't working. any answer would be appreciated. -
How to structure django models
I'm creating a website where users can post briefs and submit their work for them. The user will submit their design from the corresponding brief page. So far I have Users and Briefs in their own respective tables. Would the best approach be to create a new table which stores the brief id and the users submitted design? My idea is to create a table with user id and brief id as foreign keys and then the work. How would I then filter the table to only show the designs for the brief page the user is viewing. Thanks -
View file after payment in Django
I want to create a file store with the Django framework, but I can not click to download a specific file after paying for it online -
Unable to add data to databse from models forms django
I am trying to send data from django forms to backend sqlite3. But I am unable to do so. I am not also getting any error or warning that help me to sort it out. Here is models.py file from django.db import models GENDER_CHOICES = [ ('Male', 'M'), ('Female', 'F')] class upload(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) phone = models.CharField(max_length=50,null=True) email= models.EmailField(max_length=50,null=True) file=models.FileField(upload_to='uploads/') def __str__(self): return self.name here is forms.py file from django.forms import ModelForm from .models import upload class uploadForm(ModelForm): class Meta: model = upload fields = ['name', 'gender', 'phone', 'email','file'] Here is view.py file from django.shortcuts import render from .forms import uploadForm from django.shortcuts import render def home(request): if request.method == 'POST': form = uploadForm() if form.is_valid(): form=form.save() return HttpResponseRedirect('/') else: form = uploadForm() return render(request,'home.html',{'print':form}) I am unable to understand where is the issue This is how template file look like <form method="post"> {% csrf_token %} {{ print.as_p }} <input type="submit" value="Submit"> </form> -
How to prevent authenticated users from making direct API request (Django rest framework)
When a Django Rest Framework Site is hosted, can authenticated users make direct request to the api .. or does CORS prevent them? -
Django + Discord.py
Hi I just quickly wanted to ask if there's any way I could make a bot panel on a website using discord.py and django, javascript or PHP. I know it might be easier with discord.js but I personally hate discord.js and node in general. -
Django model extra fields added by the user
The model will ask for personnels names and qualifications which are both text fields but the amount of personnel will vary from instance to instance. How can I let the user add a field to the model? Here's my model currently: class ShiftReport(models.Model): work = models.ForeignKey(Work, null=True, on_delete=models.CASCADE) work_description = models.TextField(max_length=500) handover = models.BooleanField(default=False) weather_conditions = models.TextField(max_length=100) start_time = models.DateTimeField() end_time = models.DateTimeField() noms_number = models.TextField(max_length=40) noms_phase_addition_number = models.TextField(max_length=5) personnel_name = models.TextField(max_length=100) personnel_qualifications = models.TextField(max_length=100) personnel_name_2 = models.TextField(max_length=100) personnel_qualifications_2 = models.TextField(max_length=100) I would like to be able to let the user add in as many personnel names and qualifications as they want to. class ShiftReport(models.Model): work = models.ForeignKey(Work, null=True, on_delete=models.CASCADE) work_description = models.TextField(max_length=500) handover = models.BooleanField(default=False) weather_conditions = models.TextField(max_length=100) start_time = models.DateTimeField() end_time = models.DateTimeField() noms_number = models.TextField(max_length=40) noms_phase_addition_number = models.TextField(max_length=5) personnel_name = models.TextField(max_length=100) personnel_qualifications = models.TextField(max_length=100) personnel_count = 1 def add_personnel(self): self.personnel_count += 1 ADDFIELD(personnel_name_{self.personnel_count}) ADDFIELD(personnel_qualifications_{self.personnel_count} Just not too sure on how to implement this. Help! -
how to populate user specific data in django
i have 2 models employee and leave ,where employee is the foreign key in leaves ..i want to display the the leave requests by a specific employee on a page when they log in. here is my code models.py class Employee(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1), MaxValueValidator(24)],default=24) def __str__(self): return self.user.username class Leave(models.Model): employee=models.ForeignKey(Employee,on_delete=models.CASCADE,default="") start_date=models.DateField(auto_now_add=False) end_date=models.DateField(auto_now_add=False) req_date=models.DateTimeField(default=datetime.datetime.now()) STATUS_OPTIONS=( ("Approve","Approve"), ("Pending","Pending"), ("Decline","Decline"), ) approved=models.CharField(max_length=10,choices=STATUS_OPTIONS,default='Pending') def __str__(self): return self.employee.user.username @property def date_diff(self): return (self.start_date - self.end_date).days views.py def home(request): user=request.user u=User.objects.get(username=user) e=Employee.objects.get(user=user.id) leave=Leave.objects.get_or_create(employee=e) print(leave) nofleaves=None if user.is_superuser: pass else: nofleaves=u.employee.no_of_leaves context={'nofleaves':nofleaves,'leave':leave,} return render(request,"leaveApp/home.html",context) -
One Large Model or Multiple Model Inheritance for SQL Performance?
I have a website that allow users to post ads for items they want to sell. The items share some fields and differs in others. you might wanna sell a car or a house. You will have a title, created_date, description, ... etc fields that are shared . But you will have fields for car that aren't used for a house and so on. The type of ads is around 12 ad type like house, car or computer. There are two approaches: To use a base model and inherit it by all other 12 types of ads so will have 13 tables in the DB. To use a single model that have all the fields of all the ads types and will end up with one table and around 70 field (column in the table). The second choice seems easy from Django CRUD side specially when querying and searching all the ads at the same time. What choice is better ? If I go with the second choice would I have any performance issues related to sql ? -
How to filter on Django mantomany field in rest api
I have below Media filter in my django rest api. There is a filter on person_id as shown. Person is a manytomany field in Media model. So one media can have multiple persons. I need to add another filter on Media where I need only those Media’s where there is no entry in Person model. Please advice how do I add that filter. How the GET url will look like. Below url is for person_id. http://10.0.0.238:8000/media?person_id=1 class MediaFilter(filters.FilterSet): """Filters for the MediaViewset endpoint /media """ type = django_filters.CharFilter() category = django_filters.ModelMultipleChoiceFilter( queryset=Category.objects.all(), to_field_name="name", conjoined=True, ) person_id = django_filters.CharFilter(field_name="persons__id", lookup_expr="exact") url = django_filters.CharFilter( field_name="url", lookup_expr="exact") class Meta: model = Media fields = ["type", "category", "person_id", "url"] -
Django database queryset Roll up
I would appreciate if someone can guide me through this please. I am new to Django and trying to figure out a way to import raw data from xls file into Django database. My raw data looks like first table below. And second table shows how I want my database to look like. How do I setup my database so this can be made possible. I have currently setup django-import-export, that brings in the data but as shown in first table. Thanks, Shashank race_date track race prog_num post_pos name 2020-08-09 SAR 1 1 1 Mark 2020-08-09 SAR 1 1A 2 Matt 2020-08-09 SAR 1 3 3 Steve 2020-08-09 SAR 1 4 4 John 2020-08-09 SAR 1 5 5 Eric race_date track race prog_num post_pos name 2020-08-09 SAR 1 1, 1A, 3, 4, 5 1, 2, 3, 4, 5 Mark, Matt, Steve, John, Eric -
Django - InternalError caused by RAISE EXCEPTION in a postgres trigger
I'm new with Django and I need some help, I want to restrict the editing of a model instance, if there's a value in the X field and you try to change any field you get a message. Since I'm using postgres, I thought about using a trigger CREATE OR REPLACE FUNCTION checkear_lb() RETURNS TRIGGER LANGUAGE PLPGSQL AS $$ BEGIN --Check IF not (old.linea_base_id is null) THEN RAISE EXCEPTION 'You can't edit this because'; END IF; RETURN NULL; --I also tried with NEW END; $$ create trigger tarea_con_lb before update on "Desarrollo_tarea" for each row execute procedure checkear_lb(); It works, but I get this InternalError at /admin/Desarrollo/tarea/1/change/ You can't edit this because CONTEXT: función PL/pgSQL checkear_lb() en la línea 5 en RAISE Request Method: POST Request URL: http://127.0.0.1:8000/admin/Desarrollo/tarea/1/change/ Django Version: 3.0.3 Exception Type: InternalError Exception Value: You can't edit this because CONTEXT: función PL/pgSQL checkear_lb() en la línea 5 en RAISE Exception Location: C:\Python38\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: C:\Python38\python.exe Python Version: 3.8.2 Python Path: This is the model's field if it helps class Tarea(models.Model): .... #linea base linea_base = models.ForeignKey('LineaBase', null=True, blank=True, help_text='Linea Base', on_delete=models.SET_NULL) # , on_delete=models.CASCADE This is obviously caused by the trigger, and I was … -
Ajax: how to load div with id?
At the moment it loads data into every div with class "replies" but I want to load only into particular id. How to do this? ajax $(document).ready(function () { $(".showReplies").click(function () { $.ajax({ url: $(this).attr("data-href"), type: 'get', success: function (data) { console.log(data); $('.replies').html(data); } }) }); }); template <button type="button" id="{{ comment.id }}" class="showReplies" data-href="{% url 'comment_replies' comment.id %}">Show replies</button> <div class="replies" id="{{ comment.id }}"> I want to click on the button with id 1 and get data in div with id 1. -
how to remove from a querySet
I'm having issues removing from a queryset certain objects in a certain range like: courses = Course.objects.all().order_by('number') I'd like to exclude courses with number less than 418101. -
How do fix this Django admin look
How do i fix this django admin page layout? -
Remove/ Edit the field tags in UserCreationForm
I used to create signup forms using UserCreationForm often in my projects, but this one particular time when I did use the code below: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] help_texts = { 'username': None, 'email': None, } Even when EmailField is required True, I am unable to change the tags underlined in red. It is very annoying to see this on my page. Please let me know how to remove or edit the text there. -
Parse date string from CSV in Django using localisation (localization)
I currently parse dates from a CSV file and save the values on a "models.DateField". The CSV file has dates in a localised format "d/m/Y" (I'm in the UK). I do this using a function: def parseDate(text): return datetime.datetime.strptime(text, "%d/%m/%Y").date() How can I use a Django function to parse the date strings using the localised settings instead? I have searched around and not found a satisfactory answer. There must be a function to do this in Django as it uses such a conversion on its DateInput widget: from django import forms from app.models import Bar class DateInput(forms.DateInput): input_type = 'date' class Foo(forms.ModelForm): class Meta: model = Bar fields = ['date_fld'] widgets = {'date_fld': DateInput()}