Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to add notifications or receive updates on django admin panel?
Is there a way to receive notifications on django admin panel whenever a new post or order is created in django ecommerce or website? I have created my first ecommerce website using django. Is it possible to receive notifications on admin panel whenever a new order is placed? -
Custom template tag and CSRF protection
Django 3.2.6 emails/subscribe.html <form action="{% url 'emails:subscribe_result' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> This works fine: class SubscribeFormView(FormView): template_name = 'emails/subscribe.html' form_class = SubscribeForm success_url = 'emails/thanks/' But this does not: from django import template from django.utils.safestring import mark_safe, SafeString from django.template import Context, Template from django.template.loader import get_template register = template.Library() from emails.forms import SubscribeForm @register.simple_tag def subscribe() -> SafeString: template = get_template("emails/subscribe.html") context = {"form": SubscribeForm(), } result = template.render(context) return mark_safe(result) I get: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. Could you help me understand why custom template tag can't be used here? Maybe a request via AJAX can help? ///////////////////////////// -
Foreign key with multiple models?
I am creating ecommerce website. There are multiple categories. For example, phones, computers and others. I created a model for each of them. In OrderItems I want to foreign key each of them. So, I want to use multiple models in ForeignKey. models.py class Telefon(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi") price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class TV(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TELEFON, default="xiaomi") price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url Product={'Telefon', 'TV'} class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total So, how can I use multiple models in Foreign Key field in my OrderItems model. -
How to upload form with input file using ajax
When i send the <input type='file' src='D:/.../image.png'>'s src throught Ajax to views.py in the views the src is not correct, It appears like D:/fakepath/imag.png the fakepath is some security thing made by browser But how I can upload the form's content when I can't get the path of the file input? -
Django forms.DateTimeField change input type
I want to change forms.DateTimeField input type to "d/m/y H:M". How can I do that? I tried this but didn't work: travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M') Here's my Ticket Model: User = settings.AUTH_USER_MODEL class Ticket(models.Model): from_station = models.CharField(max_length=30) to_station = models.CharField(max_length=30) purchased_on = models.DateTimeField(default=timezone.now) travel_on = models.DateTimeField() customer = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f"Customer:{self.customer.username},From:{self.from_station},To:{self.to_station},Travel on:{self.travel_on},Purchased on:{self.purchased_on}" My TicketForm: from .models import Ticket from django import forms class TicketForm(forms.ModelForm): travel_on = forms.DateTimeField(input_formats='%m/%d/%y %H:%M') class Meta: model = Ticket fields = ('from_station','to_station','travel_on') -
How can I add new URLS to Django 3.2 under /admin?
I am working on upgrading an old Django project to 3.2. Previously, our urls.py for the main project included the following so that the urls from impersonate were below /admin url(r"^admin/", include(admin.site.urls)) url(r"^admin/impersonate/", include("impersonate.urls")), When I update this code to django 3.2, I don't seem to be able to include any urls beneath /admin. The following code: re_path(r"^admin/", admin.site.urls), re_path(r"^admin/impersonate/", include("impersonate.urls")), does not work, but it does work if I modify the impersonate line to: re_path(r"^impersonate/", include("impersonate.urls")), Basically, I want to preserve all of the impersonate urls to be beneath /admin, if this is still possible. I understand that this does not make them require admin permissions, rather this is just to group all the admin views of the project together. I have seen that I can write a custom ModelAdmin also, but this will still move the urls to under /admin/myapp/mymodel/my_view/. I do not want the extra part of the path mymodel here. -
Azure app service SSH connection refused. not using Docker. Django not installing from requirements
I followed the steps in https://docs.microsoft.com/en-us/azure/app-service/tutorial-python-postgresql-app?tabs=bash%2Cclone&pivots=postgres-single-server#4-deploy-the-code-to-azure-app-service to deploy my Django app to Azure. Issues: requirements are not installing so the app is not running. Unsure if this is because I used az webapp up instead of a git branch. I tried SSH in but connection error's out: SSH CONNECTION CLOSE - Error: connect EHOSTUNREACH 172.16.1.3:2222Error: connect EHOSTUNREACH 172.16.1.3:2222Error: Timed out while waiting for handshakeError: connect EHOSTUNREACH 172.16.1.3:2222 there are articles mentioning whitelisting port 2222 to go over 80*, but I can't seem to find where to do this on the portal. Again, I'm not using a docker image so I can't add a config. Used kudu file browser and see that requirements.txt is there and correct. this is the error from log stream: 2021-08-17T15:21:04.475206899Z File "<frozen importlib._bootstrap>", line 677, in _load_unlocked 2021-08-17T15:21:04.475210299Z File "<frozen importlib._bootstrap_external>", line 728, in exec_module 2021-08-17T15:21:04.475213499Z File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2021-08-17T15:21:04.475216699Z File "/home/site/wwwroot/backend/wsgi.py", line 12, in <module> 2021-08-17T15:21:04.475219999Z from django.core.wsgi import get_wsgi_application 2021-08-17T15:21:04.475222999Z ModuleNotFoundError: No module named 'django' -
Django @queryset on json field
select * from. table_name where id = 10 and name = 'xyz' and address::json->>'house_number' like '%"28735": true%'; can someone provide me or help me with how to write Django QuerySet for that. -
Error: The view didn't return an HttpResponse, when trying to send email
I want to manually approve reports for clients after they have agreed to terms. For this I want to email to be sent to myself when client clicks "accept". I get the following error instead: The view accounts.views.TermsView didn't return an HttpResponse object. It returned None instead. Have searched for the same error here, but failed to solve with these. Sorry, new programmer here. views.py class TermsView(TemplateView): template_name = "accounts/terms_of_service.html" ... def post(self, *args, **kwargs): self.request.user.terms_accepted = timezone.now() self.request.user.save(update_fields=["terms_accepted"]) def send_mail(self): messages.add_message( self.request, messages.SUCCESS, _("Thank you! We will contact you as soon as possible."), ) send_terms_agreed_reports(self.request.company, self.request.user) return redirect("stays:dashboard") emails.py def send_terms_agreed_reports(company, user): try: email_subject = "New company wants to use reports" return send_email( settings.TERMS_AGREED_ENABLE_REPORTS, email_subject, "emails/terms_agreed_reports.html", {"company": company.name, "reg_code": company.reg_code, "name": user.name, "email": user.email, "phone": user.phone}, ) except Exception: logger.exception("Could not send message") -
django password form field doesnt look other field.How can i fix it?
Although I specify a class in forms.py, the password fields do not appear as regular as the others. What is the reason for this and how can I fix it. forms.py class registerForm(UserCreationForm): class Meta: model = CustomUserModel fields=("first_name","last_name","email","phone_number","password1","password2") widgets = { "first_name" : TextInput(attrs={"class":"form-control floating"}), "last_name" : TextInput(attrs={"class":"form-control floating"}), "email" : EmailInput(attrs={"class":"form-control floating","type":"email"}), "phone_number" : TextInput(attrs={"class":"form-control floating"}), "password1" : PasswordInput(attrs={"class":"form-control floating"}), "password2" : PasswordInput(attrs={"class":"form-control floating"}), } In my template form looks like this -
How to perform an http post request to a device behind a router using DDNS & Python
For faster prototyping of my code, I would like to provide my laptop address as an endpoint to the http webhook API (Base URL) of the website cloud.thethings.network. For this, I setup a ddns on noip.com and connected my tp-link router with my noip-account. So right now, I have sth. like myneedddns.ddns.com that forwards to my router. I’ve also set port forwarding in my router to access my laptop and reserved a static IP for the laptop: However, I can not provide a format like xxx.ddns.com:801 on thethingsstack. From there I can probably handle how to receive the request with flask or django. How would you approach my goal? -
Unique Class or extend Class or Subclass in Python Django?
Unique Class or extend Class or Subclass in Python Django? In the following situation, I have a feeling I need to ?extend? the Migration class instead of re-stating it in the second module. Or is a child class needed? A goal here: To create a postgres table called venues. There is already a models/venues.py that seems to be set up ok. migrations/0001_initial.py: class Migration(migrations.Migration): initial = True dependencies = [('auth', '0012_alter_user_first_name_max_length'),] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, ...)), ('password', models.CharField(max_length=128, ...)), ... migrations/0002_venue.py: class Migration(migrations.Migration): dependencies = [('app', '0001_initial'),] operations = [ migrations.CreateModel( name='Venue', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True...)), ('name', models.CharField(blank=True ...)), ('address', models.CharField(blank=True...)), ... Help? -
How to obtain a user instance using django rest framework
Perhaps the question is wrongly worded. I created user profile using Django through the following blocks of code: models.py class = Profile (models.Models): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first name = models.CharField(max_length=50) ••• serializer.py class profile_serializer(serializers.ModerlSerializer) class Meta: model = Profile fields = '__all__' views.py class profile_view(generics.ListCreateAPIView) queryset = Profile.objects.all().filter(user=instance) urls.py urlspatterns = [path('profile', profile_view.as_view(), name='user_profile) I definitely do not know how to implement the filter method to ensure that only the logged in user is retrieved. Or is there a better approach to obtain a specific user? If I use Project.objects.all() without the filter I get all the registered user as expected. But I don't know how to retrieve a particular user. -
Problem with progress upload bar using XMLHttpRequest in Django
I have an issue with a progress upload bar in Django when the site is deployed to Heroku, when I click on the upload button the progress bar shows up at 10% then doesn't change or count up to 100%, when the upload is finished, it redirects as instructed in my views.py , the function runs fine locally, but after deploying to heroku it doesn't work. I think it may be something to do with the deployed url using 'https', but not sure and how to fix it? appreciate any help. custom.js function progressBar() { progressBox.classList.remove('not-visible') cancelBox.classList.remove('not-visible') const upload_data = input.files[0] const url = URL.createObjectURL(upload_data) // console.log(upload_data); const fd = new FormData() fd.append('csrfmiddlewaretoken', csrf[0].value) fd.append('track', upload_data) $.ajax({ type: 'POST', enctype: 'multipart/form-data', data: fd, beforeSend: function(){ }, xhr: function(){ const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', e=>{ // console.log(e); if (e.lengthComputable) { const percent = (e.loaded / e.total) * 100; // console.log(percent); progressBox.innerHTML = `<h5 style="text-align:center;">${percent.toFixed(1)}%</h5> <div class="progress" style="height: 30px;"> <div class="progress-bar bg-success" role="progressbar" style="width: ${percent}%" aria-valuenow="${percent}" aria-valuemin="0" aria-valuemax="100"></div> </div>` } }) cancelBtn.addEventListener('click', ()=>{ xhr.abort() progressBox.innerHTML="" cancelBox.classList.add('not-visible') window.location.reload(); }) return xhr; }, success: function(response){ // console.log(response); uploadForm.reset() cancelBox.classList.add('not-visible') }, error: function(error){ console.log(error); }, cache: false, contentType: false, processData: false, }) } -
How to set the default user as the current user object in django?
I have created a mini project called ToDoList App. I have used class based views for create, update and delete functions. There is MyTasks icon on navbar. What do I want? I want to set the default user as the current logged in user. Tasks of one person should not be seen by any another person. I have tried all the solutions but nothing seems to work. Here is my code in models.py file: class MyTasks(models.Model): user = models.ForeignKey(User, on_delete=CASCADE, related_name="mytasks") task_id = models.AutoField(primary_key=True, verbose_name="ID") task_title = models.CharField(max_length=100, default="", help_text="The title of the task", verbose_name="Task Title", blank=False) task_desc = models.TextField(default="", help_text="The description of task", verbose_name="Task Description", blank=False) task_time = models.DateTimeField(default=timezone.now(), verbose_name="Task Date & Time") task_completed = models.BooleanField(default=False, verbose_name="Task Completed") def save(self, *args, **kwargs): self.user = User super(MyTasks, self).save(*args, **kwargs) def __str__(self): return self.task_title When I used the save method to achieve the task, it is showing this error: ValueError: Cannot assign "<class 'django.contrib.auth.models.User'>" Please help me to achieve this task. Any help is much appreciated. -
New records not coming in the list call of Django DRF API using Redis cache
I have a Django REST API, and I am using Redis as the caching backend. Code @method_decorator(cache_page(60*60)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) It caches the data on a get call, but when I insert a new record, that new record is not showing up in the list (Which is coming from cache). Any help? -
Granting access to other class views upon successful authentication Django REST
Here is my API in Django REST. Here is my code: from rest_framework.permissions import IsAuthenticated, AllowAny class CreateItems(generics.CreateAPIView): permission_classes = [IsAuthenticated] queryset = SomeModel.objects.all() serializer_class = SomeSerializer class AuthStatus(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): token = self.request.data['itemsReturnedAuthAPI']['accessToken'] if(token): return Response({"Token":token}) else: return Response({"message":"No Token Found!"}) I have an authentication microservice that I get the JWT Token from for the user in order to have access to the views. In the AuthStatus class I am checking the token. My Question: I want to grant the user access to the CreateItems class, after the token is provided -
Django Rest Framework request unauthorized on all but one address
I'm trying to access django hosted at 192.168.x.x:8000 on a React frontend server on port 5002, when attempting to access the frontend with localhost, 127.0.0.1 or ip's outside of the home network, it gives following result in console: Unauthorized: /api/any_endpoint HTTP POST /api/any_endpoint 401 [0.03, 127.0.0.1:12345] However when accessing trough 192.168.x.x:5002, it just works. the /admin/ endpoint seems to work no matter the ip address (ip_address:8000), so it's either django-rest-framework or React that is causing this issue. I have no idea where to start debugging this, so any comment on what I should check would be appreciated -
Django (1045, "Access denied for user 'root'@'localhost' (using password: NO)")
I have come accross a strange issue, I have deployed a django site to an Ubuntu 20.04 LTS server. The problem is my django app can not connect to the database because It is doesn't using the db connection credentials that have identified in app settings.py. It is using root with no password. But when I can run manage.py db operations without any problem. This is my settings.py 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pplus_db', 'USER': 'pplus_user', 'PASSWORD': 'dfa@4GL-5qQU', 'HOST': 'localhost', 'PORT':'3306', } } This is the screenshot of the error, I'm getting when I'm trying to login -
django.contrib.auth.urls change redirect path
I am coding a basic login and register page app in Django/Python Currently, after someone logs in, it redirects them back to the register page. I am trying to change the redirect path to "home/" Please see the following code: URLS.PY: from django.contrib import admin from django.urls import path , include from accounts import views as v from main import views as views urlpatterns = [ path('admin/', admin.site.urls), path('home/' , views.home , name = 'home'), path('', v.register , name='register'), path('' , include('django.contrib.auth.urls') , name = 'login'), ] Views.py: from django.shortcuts import render , redirect from .forms import RegisterForm # Create your views here. def register(response): if response.method == "POST": form = UserCreationForm(response.POST) if form.is_valid(): form.save() return redirect("/home") else: form = RegisterForm() return render(response, "registration/register.html", {"form":form}) Login.html {% extends "main/base.html"%} {% block title %} Login here {% endblock %} {% load crispy_forms_tags %} {% block content %} <form class="form-group" method="post"> {% csrf_token %} {{ form|crispy }} <p>Don't have an account ? Create one <a href="/register"></a></p> <button type="submit" class="btn btn-success">Login</button> </form> {% endblock %} Register.html {% extends "main/base.html"%} {% block title %}Create an Account{% endblock %} {% load crispy_forms_tags %} {% block content %} <form method="POST" class="form-group"> {% csrf_token %} {{ form|crispy … -
Is it possible to reorder the content_panels in Wagtail admin?
I am creating a Wagtail application where some models inherit fields from a base model. Unfortunately, these base fields are always displayed first in the form generated by Wagtail. For example: class BaseModel(models.Model): some_attribute = models.TextField() class Meta: abstract = True content_panels = [ FieldPanel('some_attribute'), ] @register_snippet class ChildModel(BaseModel): title = models.TextField() content_panels = Page.content_panels + [ FieldPanel('title'), ] In Wagtail admin in the ChildModel editor, some_attribute would be displayed above title now, which is not very intuitive to users. Is there a way to change this behaviour? -
How to generate the staff users activity report in django?
I am building the system in Django rest framework, in which the admin level user will govern the staff users , I need to keep track of staff levels users activity, example: staff user activity such as adding some post or deleting and so on other lots of activities. Is there any package or any good implementation on how it can be achieved ? -
Dynamically filtering fields in formset
I have a view: class SummaryListView(ListView): model = MyModel MyModelFormSet = modelformset_factory( MyModel, fields=('field1', ), formset=BaseMyModelFormSet, ) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) fields = get_fields(self) formset = self.MyModelFormSet(request=self.request) context['formset '] = formset return context def post(self, request, *args, **kwargs): formset = self.MyModelFormSet(request.POST, request=request) if formset.is_valid(): formset.save() return redirect('') I want to pass MyModelFormSet a list of fields to render which I generate with a function get_fields() which takes self as an argument. Now, I can place MyModelFormSet inside get_context_data, but then how do I access it from post? Or can I pass MyModelFormSet a variable from inside the get_context_data? -
Django: Add objects.all.count() to aggregate?
I've been searching how to add X.objects.all().count() result to an existing aggregate logic. I seen that Count() will only work with a foreign key relationship, so how can I add an 'additional field' with the .count() results to the aggregate with only writing it in one block. This is my custom action (Does not work): from django.db.models.functions import Coalesce from django.db.models import Min, Avg, Max, Value as Val, IntegerField @action(detail=False, methods=['get']) def get_stats(self, request, pk=None): total_ads = Ad.objects.all().count() stats = Ad.objects.aggregate( price_min = Coalesce(Min('price'), Val(0)), price_avg = Coalesce(Avg('price'), Val(0.0)), price_max = Coalesce(Max('price'), Val(0)), ads_total = Val(total_ads, output_field=IntegerField()), ) return Response(stats) Error: TypeError: ads_total is not an aggregate expression -
Refer to child class foreign key in base abstract model
I am trying to access the child model foreign key in base abstract model so I don't have to repeat the foreign key in each of the child model. Here is my code: class BaseModel(models.Model): child_field = models.ForeignKey(to='child_class_either_ModelA_OR_ModelB') class Meta: abstract = True class ModelA(BaseModel): .... class ModelB(BaseModel): .... I want to refer the child model in base abstract model. Is there a way to use an child model in base model?