Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Any" path in Django?
Is it possible to define a route that will be redirected to if Django could not find a match in the defined URLs? For example, let's say I have: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), ] Can I define a "dynamic" URL of a specific view that will be redirected to if the path doesn't exist? Suppose I enter the URLs /ajaxsignup and /ajaxdelete, which are not defined, but have them redirected to a URL of a certain view? In other words: urlpatterns = [ path('ajaxlogin', views.ajax_login, name='ajaxlogin'), path('ajaxprofile', views.ajax_profile, name='ajaxprofile'), path('every-other-url', views.another_view, name='path-everything-else'), ] I know there's Django's error handlers, but are there any other ways to achieve this? I have my frontend based separately on a React application, so I'd very much appreciate a "dynamic" URL rather than using Django's default 404 responses. I suspect that if path couldn't do it, I could use the old url with regex -- but I still have no clue. Thanks in advance. -
django rest framework set image field to null when updating the field
Here is my code; models.py class Book(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=255, blank=True, null=True) cover_image = models.ImageField(blank=True, null=True) def __str__(self): return f"{ self.title } - { self.author }" serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' views.py class BookListViews(generics.ListAPIView, generics.CreateAPIView, generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer The object is created alright, but when I try to update the title or author field, without updating the image, once I post it, the image value is set to null. This is problem because, I don't want to keep changing the image or update the image anytime I want to change the title or author field. -
Delete user create from allauth social login
In the process of learning allauth social login, I am able to successfully register & log in a user using google provider. For trial and testing purposes I need to delete the logged-in user and re-register with the same google email. I deleted the social account, social account token, email for that user from the admin console, but when I try to login again for the same user with the same email it gives an error - An account already exists with this e-mail address I have also checked rest-auth/user but found nothing. How can I completely delete a social account and log in again with the same Email? Any helpful tips? -
How to call a Class´s method with a button on a web page - Django -python
im starting with django and iot and i've decided to start (for learning purposes) an app that connects to my sensors attached to my raspberry pi. The thing that im struggling is the next one: I've done a class for my DHT11 sensor (temperature and humidity), and i've declared all values and wrote a method, which gets and prints the values of the sensor, and made a page where i show all the properties of the object, like "asigned pin" or the "name" of it; all fine until here. this is the class: class DHT11(models.Model): dht_sensor = Adafruit_DHT.DHT11 pin = IntegerField() status = BooleanField(default=False) name = CharField(max_length=15) humidity = IntegerField(default=0) temperature = IntegerField(default=0) def read_values(self): self.humidity, self.temperature = Adafruit_DHT.read(self.dht_sensor, self.pin) if self.humidity is not 0 and self.temperature is not 0: self.status = True else: self.status = False time.sleep(delay) print(self.temperature) print(self.humidity) The issue is that, in the same page where i show the properties of the object, id like to create a button, and with it call the "read_values" method of the object, and then show the values of temperature and humidity in the webpage that the method returns. ¿how do i do this?, do i need websockets? Here is an … -
How to Connect a Django Model with ManyToMany Relationship?
I am making an app that is pretty much similar to google classroom in django. I have a Course model and an assignment model, and I want to connect an assignment to the specified course. These are my models class Assignment(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=100) date_created = models.DateTimeField(default=timezone.now) class Course(models.Model): title = models.CharField(max_length=100) subject = models.CharField(max_length=100) image = models.ImageField(default='no_course_image.jpg', upload_to='course_images') owner = models.ForeignKey(User, on_delete=models.CASCADE) students_invited = models.ManyToManyField(User, null=True, blank=True) assignments = models.ManyToManyField(Assignment, null=True, blank=True) date_published = models.DateTimeField(default=timezone.now) class Meta: verbose_name_plural = 'Course' ordering = ['-date_published'] def __str__(self): return '{} - {}'.format(self.title, self.owner) But i am getting an error when I specify the course field in the assignment model with the ForeignKey! Could you please help me with how to connect the assignment to the Course model? Thank you -
How to create a nested DRF serializer with a UUID PrimaryKeyRelatedField?
I've simplified/minimised the example here (removed class meta which specifies model and all fields, removed some other explicitfields) but it matches the use case and replicates the behaviour being observed. class MainSerializer(ModelSerializer): a = ASerializer(required=False, many=True) def create(self, validated_data): a_data = validated_data.pop("a", None) main_instance = super().create(validated_data) if a_data is None: return main_instance for a in a_data: a["main_relation"] = main_instance a_serializer = ASerializer(data=a, many=True) a_saved = None if a_serializer.is_valid(): a_serializer.save() a_saved = a_serializer.data else: a_saved = a_serializer.errors return { **self.data, "a": a_saved.data() } class ASerializer(ModelSerializer): main_relation = PrimaryKeyRelatedField(queryset=ModelB.objects.all(), required=False, allow_null=True, default=None) The MainSerializer#create ends up throwing an error in the PrimaryKeyRelatedField#to_representation where it says the string representation of main_instance has no attribute pk, but when running through the debugger, the instance definitely has both the pk and uid attribute, and both are the same value as expected. So what's going wrong? Side question: if instead of returning the dictionary, and returning main_instance in both cases, will the viewset return the full MainSerializer#data representation of the instance (the nested a relationship included as per it's serializer)? And if the nested serializers have errors, will they come through in that data? Or would something like this require an extension of the drf functionality? -
How to make this very complicated query from three connected models with Django ORM?
Good day, everyone. Hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development while helping in a small app project. We currently want some of our models to update accordingly based on the data we submit to them, by using the Django ORM and the fields that some of them share wih OneToMany relationsips. Currently, there's a really difficult query that I must do for one of my fields to update automatically given that filter. First, let me explain the models. This are not real, but a doppleganger that should work the same: First we have a Report model that is a teacher's report of a student: class Report(models.Model): status = models.CharField( max_length=32, choices=Statuses.choices, default=Statuses.created,) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name='reports', ) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various dates results_date = models.DateTimeField(null=True, blank=True) report_created = models.DateTimeField(null=True, blank=True) . #Other fields that don't matter Here we have two related models, which are student and headroom_teacher. It's not necessary to show their models, but their relationship with the next two models is really important. We also have an Exams model: class Exams(models.Model): student = models.ForeignKey( student, on_delete=models.CASCADE, related_name='appointments',) headroom_teacher = models.ForeignKey( TeacherStaff, on_delete=models.CASCADE,) # Various … -
How I get obj from parent model in Django Admin to put in html template
Here is my code where I generate a PDF file, (like an invoice), but I can't retrieve the fields from the admin.TabularInline. In my model.py I have to class: Sale and SaleItems,and in admin.py I have : class SaleItemsInLine(admin.TabularInline): model = SaleItems extra = 1 readonly_fields = ('total', ) formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'100%'})}, } @admin.register(Sale) class SaleAdmin(DjangoObjectActions, admin.ModelAdmin): fields = ( ('order', 'created', 'due_date'), ('profile'), ('pay_method', 'tax_card'), ('therapist' ,'activity',), ('notes'), ('totals'), ('pay', 'payOne','payTwo'), ('subtotal', 'status'), ) readonly_fields = ('created', 'totals', 'order','subtotal', 'status', 'tax_card') search_fields = ['profile__name', 'profile__cpf', 'profile__phone', 'activity', ] autocomplete_fields = ('profile',) list_display = ('profile', 'order', 'created', 'due_date', 'totals', 'status') inlines = [SaleItemsInLine] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'30'})}, models.TextField: {'widget': Textarea(attrs={'rows':4, 'cols':100})}, } def generate_pdf(self, request, obj): html_string = render_to_string('sales/invoice.html', {'obj': obj}) html = HTML(string=html_string, base_url=request.build_absolute_uri()) html.write_pdf(target='/tmp/{}.pdf'.format(obj), presentational_hints=True); fs = FileSystemStorage('/tmp') with fs.open('{}.pdf'.format(obj)) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'filename="{}.pdf"'.format(obj) return response return response I get fields from Sale with {{ obj.name }}, {{ obj.created}}, etc... How I get the fields from SaleItems(TabulaInline) ??? -
How to search any of a set of fields spanning multiple tables and show a join of those fields on the results page in Django
I have a set of fields spanning 7 tables that I want to display as a consolidated search results table. (Not sure if it matters, but the relationships between the tables are mostly reverse relationships (except 1)). For illustrative purposes, here is the table hierarchy (where each subtable record has a link to the parent table): Study (1 field) Animal (4 fields) Sample (1 field) -> Tissue (one field - the only forward relationship) MSRun (0 fields) PeakGroup (3 fields) PeakData (3 fields) Each table (Except MSRun) has at least 1 field displayed (and searchable) in the results output (presented in table format). I want the user to be able to search any of those fields and I want only one view function and one results template (in order to reduce the overhead of maintaining multiple identically-appearing result pages when the format is changed (which I expect to happen)). The joined results should only contain values matching whatever the search field was. E.g. If they search for Animal 1, that column would have only '1' in it, along with all other related fields. Worst case, the results table would have roughly 2.2k rows from the largest Study. (Note, 4 of … -
Django not getting path not matching
I am trying to make a certain url on my localhost show "Alex!" when it is entered in. For some reason I am getting this error: "Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, sauce, didn’t match any of these." The app name is "main" Here is my code: main.urls from django.urls import path from . import views urlpatterns = [ path('sauce/', views.index, name='index'), ] main.views from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Alex!") mysite.urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('sauce/', include('main.urls')), path('admin/', admin.site.urls), ] I also tried doing this but with the homepage and not "sauce/" but that didn't work either. -
how I can use http post flutter with django
I want to make it without Django Reset Framework that is my code ''' from django.http import JsonResponse def index1(request): cursor.execute('select * from users where id = %s',[request.POST]) response = list(cursor.fetchall()) return JsonResponse(response, safe=False) ''' and when i use flutter http post put it gives me this Forbidden (CSRF cookie not set.): /index1 [04/Jun/2021 00:20:25] "POST /index1 HTTP/1.1" 403 2870 -
django ListView template post function using Q queries - too many values to unpack (expected 2)
I am using Django 3.2 I am creating a search form that will allow me to search for terms entered by user. I am using POST to post the search terms to the server. Here is my code: /path/to/views.py class FooSearchListView(ListView): model = Foo context_object_name = 'foos' template_name = 'path/to/foo_search_list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) return context def post(self, request, *args, **kwargs): query_original = request.POST.get('search_terms', None) lookups = Q() if query_original: search_query = [x.strip() for x in query_original.lower().split(',')] for word in search_query: lookups = (lookups | Q(title__icontains=word) | Q(tags__name__icontains=word) | Q(caption__icontains=word) ) return Foo.objects.filter(lookups, is_public=True).distinct() # <- Barfs on this line /path/to/page.html <form action="{% url 'foo-search' %}" class="form-inline input-group col-md-4" method="post"> {% csrf_token %} <input id="search-terms" name="search_terms" class="form-control py-2 border-right-0 border" type="search" value="search"> <span class="input-group-append"> <button class="btn btn-outline-secondary border-left-0 border" type="submit"> <i class="fa fa-search"></i> </button> </span> </form> /path/to/urls.py # ... path('foos/search/', FooSearchListView.as_view(), name='foo-search'), # ... What is causing this error - and how do I fix it? -
Call python function with Django
I've recently started learning how to use Django and I was wondering whether or not you could create a button in HTML that can directly call a python function without changing the URL. I was told this was possible with JS but I wanted to know if you could do that in Python. Thanks for your time reading this! -
Flash popup from within decorator function on Flask Route
I would like to create a flash popup from within a decorator function applied to a Flask view. When I generate a flash from within my view, everything works perfectly fine. I would like to be able to also generate flash messages from a wrapper function acting on the view; the form I have tried is: from flask import Flask, render_template from functools import wraps def my_wrapper_function(_f): @wraps(_f) def _decorated_function(*args, **kwargs): ... flash(removed_article.get('name', 'expansion')) ... return _f(*args, **kwargs) return _decorated_function @app.route('/my_view/<int:_id>', methods=['GET']) @my_wrapper_function def my_view(_id): ... return render_template('my_template.jinja2') This does not appear to work however, no flash message appears. N.B: As opposed to generating flash messages within my view, which does work. The following template is included below for completeness; I would imagine the solution lies in the python code. # my_template.jinja2 {% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category == 'message' %} <div class="alert alert-success text-center" role="alert"> {% else %} <div class="alert alert-{{ category }} text-center" role="alert"> {% endif %} {{ message }} </div> {% endfor %} {% endif %} {% endwith %} Since I'm fairly new at both decorators and Flask in general, I thought I'd … -
Django-Python: Grabbing Alias Outlook Email in the form of JSON
0 I am trying to grab the alias email addresses created within the main account. How am I able to grab the JSON for all of the alias email addresses and then grab all the calendar events contents? Here is the layout of my code: https://github.com/reportex-development/Lobby-Menu/tree/main/Lobby-menu-v3-here I see that in the tutorial > graph_helper.py there is something that's trying to get_calendar_events but it seems like it is only for that one main account but I want to see all the events in the alias accounts. I tried doing: print(events) print(get_user(token)) print(get_calendar(token)) print(get_calendar_group(token)) But none of those are showing me the alias email addresses it is only showing me the main account information. How do I see the alias account information? -
Getting TypeError: __init__() got an unexpected keyword argument 'upload_to' in Django Project?
I have just started learning Django frame work and got stuck after getting an unexpected error as below:-(I have tried to post all information, which i find necessary to be here) TypeError: __init__() got an unexpected keyword argument 'upload_to' I got this error while running command python manage.py makemigrations My project contains only one Model class Products My Model Class:- from django.db import models # Create your models here. class Products(models.Model): name = models.CharField(max_length=25) price = models.IntegerField() description = models.CharField(max_length=50) pic = models.DateTimeField(upload_to="myimages") I am added my app in INSTALLED_APPS fields in setting.py Thanks in advance. Hope to here from you soon. -
Django: Change default parameter appended in the URL in forms
I have a form like this: <form method="get"> <button name="load" type="submit" value="{{game.game_id}}|{{game.champion}}">Show user's stats</button> </form> When the user submits the form, the parameter will automatically be appended into the URL like this www.example.com/?load=5293733926|99 However, I want to add manually another parameter to the URL making the URL look like this: www.example.com/?load=5293733926|99&page=2 If I manually type this to the URL, it goes to where I want. How should I do this? I tried adding: action="./?load={{game.game_id}}|{{game.champion}}&page={{game.page}}" and multiple other variants. But it doesn't work, it redirects to www.example.com/?load=5293733926|99. Context: I have a huge list of dictionaries and if I show them all at the same time and process them, it takes a lot of time. I divided the list with Django's paginator. The forms act as a load more. By default, I show some data from the dictionary and when the user clicks the form button, some extra information is showed. However, if someone clicks the form button in page 2 www.example.com/?page=2, Django would redirect the user to the first page after processing the data. In order to redirect the user to the submitted button's page, I would need to redirect the user to www.example.com/?load=5293733926|99&page=2 It's my first time asking a question … -
How to use Login View in django?
I decided to customize the login form and make authentication with email. I can login with super user account but can't do it with the simple user. Here's the models.py file. I created custom user manager and redifened the creation logic def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Staff must be True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be True') if other_fields.get('is_active') is not True: raise ValueError('Is active must be True') return self.create_user(email, user_name, first_name, last_name, password, **other_fields) def create_user(self, email, user_name, first_name, last_name, password, **other_fields): if not email: raise ValueError('You must provide an email') email = self.normalize_email(email) user = self.model(email = email, user_name = user_name, first_name=first_name, last_name = last_name, **other_fields) user.set_password(password) user.save() return user class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) department = models.CharField(max_length=150) company = models.CharField(max_length=150) head = models.CharField(max_length=150, blank=True) is_staff = models.BooleanField(default=False, blank=True) is_active = models.BooleanField(default=False, blank=True) is_admin = models.BooleanField(default=False, blank=True) dashmodel = models.CharField(max_length=150, blank=True) role = models.CharField(max_length=150, blank=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name','first_name','last_name'] def __str__(self): return self.user_name ``` I change the logic of … -
Django Formset new entry fails validation
I am trying to create a formset where I can 1) show all entries +1 (for new entry) 2) update existing entries 3) add new entries. Currently I can successfully complete 1 & 2. When it comes to adding a new entry the formset fails .is_valid() check. This is because I have a hidden input for the entry_id. The id is necessary for bulk_update() to update existing entries, but causes the is_valid() function to fail on the new entry. If I use bulk_create(), I do not need the id but it will duplicate all existing entries. Is there a way to pass the .is_valid() check when attempting to add a new entry? views.py def CustomerView(request): template = "accounts/customers.html" # Create the formset, specifying the form and formset we want to use. CustomerFormSet = formset_factory(CustomerForm, formset=BaseFormSet) # Get our existing data for this user. customer_list = Customers.objects.all().order_by("cust_name") customers = [{'customer_id': c.id, 'customer_name': c.cust_name} for c in customer_list] if request.method == 'POST': customer_formset = CustomerFormSet(request.POST) # print(customer_formset.errors) if customer_formset.is_valid(): # Now save the data for each form in the formset customer = [] for customer_form in customer_formset: customer_id = customer_form.cleaned_data.get('customer_id') customer_name = customer_form.cleaned_data.get('customer_name') if customer_id and customer_name: customer.append(Customers(id=customer_id, cust_name=customer_name)) try: with transaction.atomic(): … -
Get Return from a dynamic form from javascript to view in django imagefileds
I want to get dynamic image upload data from a javascript to my view.py in django my dynamic scrpit <script> $(document).ready(function(){ var id = 1; $("#add_more").click(function(){ var showId = ++id; if(showId <=5) { $(".input-files").append('<input type="file" name="file_upload-'+showId+'">'); } }); }); </script> and my view and model img_dokans = ArrayField(models.URLField(max_length=200), blank=True, null=True) Suggest me my view from a html form how can i integrate script to django so i can get the files which later i ll upload to S3 -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte while calling the function
while calling the investors_data function ,getting the error "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte" views.py owners_with_pp=['Q5UrH4bPgggmroA8g8p5sJ', 'qpA8kptiYUGFCFYN2Tg4oR', 'e6dQwGi2ehgLaK6qYJr8KA', 'YZovJ23LamzMWpKaPsgrsk', 'YZovJ23LamzMWpKaPsgrsk'] owners_without_pp = ['9jeJ8YNJtF9N9tjibtpdZG'] if owners_with_pp: stock_data['investors_with_pp'] = utils.investors_data(owners_with_pp,friends,'with') if owners_without_pp: stock_data['investors_without_pp']= utils.investors_data(owners_without_pp,friends,'without') utils.py def investors_data(user_data,friends,flag): inv_data = User.objects.filter(id__in=user_data).order_by('-user_name') F = False profile_pic = None for investor in inv_data: if investor.id in friends: F = True if investor.profile_pic: profile_pic = investor.profile_pic investors_details = {'id': investor.id, "user_name": investor.user_name, "profile_pic": profile_pic, "is-friend": F} return investors_details but it works when i comment out # if owners_with_pp: # stock_data['investors_with_pp'] = utils.investors_data(owners_with_pp,friends,'with') -
Best practise Django-Rest-Framework external library testing
i'm developing an API that has both a lot of external libraries such as django-polymorphic and django-cors-headers. And I have lots of 3rd party integration such as AWS for deployement and i was wondering when i run python manage.py test does it run the tests in these external libraries ? Or do i have to include them? If i have to include them whats the best way to do it ? -
Image not saving to media or creating media folder (Python, Django)
I have been struggling with this for the past days i have done everything right and i dont know what am missing exactly. when i try to upload the image from the admin page it uploads succesfully creates the media folder if not exist already. but when i try to get the image from url the image is saved in the url field of my model but never get create to the image field of my model whis is image = image = models.ImageField below is my code models class Image(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="user_images", on_delete=models.CASCADE ) users_like = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="images_liked", blank=True ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to="images/%Y/%m/%d/") description = models.TextField(blank=True) created = models.DateField( auto_now_add=True, db_index=True ) forms save method def save(self, force_insert=False, force_update=False, commit=True): image = super().save(commit=False) image_url = self.cleaned_data["url"] name = slugify(image.title) extension = image_url.rsplit(".", 1)[1].lower() image_name = f"{name}.{extension}" # download image from the given URL response = request.urlopen(image_url) image.image.save(image_name, ContentFile(response.read()), save=False) if commit: image.save() return image -
How can I modify models.py in external app in Django CMS
I am trying to modify existing model(In Django CMS Blog application). There is a Post class, I can modify it in models.py that located inside the Django CMS Blog project, like so: media = PlaceholderField("media", related_name="media") post_title = PlaceholderField("post_title", related_name="post_title") # My code content = PlaceholderField("post_content", related_name="post_content") liveblog = PlaceholderField("live_blog", related_name="live_blog") And after the migration the DB looks like this. As you can see, the field is added. But how can I do that from my local project files? I don't want to add this code inside 3d party app models, because it will lead to problems with updating this 3d party app. -
Django: change column headers in Admin ListView without losing sortability
I just want to change the column header in Django' Admin ListView. There is already an answer: Django admin listview Customize Column Name, but this solution (define a function and set .short_description on it) comes at the cost of no longer being able to sort by the column in question. I cannot find any other solution. It seems to simple a wish that I cannot believe it cannot be done.