Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF serializer is taking nested JSON payload as single JSON object
Please go through the description, I tried to describe everything i've encountered while trying to solve this issue. I have two models, User and Profile. I'm trying to update them through one serializer. I've combined two models into one serilzer like below: class DoctorProfileFields(serializers.ModelSerializer): """this will be used as value of profile key in DoctorProfileSerializer""" class Meta: model = DoctorProfile fields = ('doctor_type', 'title', 'date_of_birth', 'registration_number', 'gender', 'city', 'country', ) class DoctorProfileSerializer(serializers.ModelSerializer): """retrieve, update and delete profile""" profile = DoctorProfileFields(source='*') class Meta: model = User fields = ('name', 'avatar', 'profile', ) @transaction.atomic def update(self, instance, validated_data): ModelClass = self.Meta.model profile = validated_data.pop('profile', {}) ModelClass.objects.filter(id=instance.id).update(**validated_data) if profile: DoctorProfile.objects.filter(owner=instance).update(**profile) new_instance = ModelClass.objects.get(id = instance.id) return new_instance When I send request with GET method, the DoctorProfileSerializer returns nested data(Combining two models User and DoctorProfile) in the desired fashion. But when I try to update both models through this serializer, it returns error saying User has no field named 'doctor_type'. Let's have a look at the JSON i'm trying to send: { "name": "Dr. Strange updated twice", "profile" : { "doctor_type": "PSYCHIATRIST" } } Let's have a look at how the serializer is receiving the JSON: { "name": "Maruf updated trice", "doctor_type": "PSYCHIATRIST" } … -
How to make pdf editor using python with django?
I am working on a project in which clients requirement is The user can edite the pdf while using browser and user can remove the text which they want. Reference: [Like This ][1] [1]: https://www.sejda.com/pdf-editor I used lots of python libraries but not all are good. -
Access dictionary property with dollar sign `$` in it's name using django template syntax
I'm ttrying to access a property with a $ in its name in a django template. Unfortunately I have neither control over additional filters nor over the variable name itself. The object is structured as follows: { "title": "Some title", "metadata": { "$price": 9.99, "$inventory_policy": 1 } } I am trying to access {{ item.metatadata.$price }}, but the template builder crashes with an unspecified error. I already tried the methods from python templates, but they crash as well: {{ item.metatadata.$$price }} {{ item.metatadata.${price} }} -
Django Query: How to filter record that have more than one foreign key
This is my models class WorkReport(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='work_reports') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='tasks') effort = models.DecimalField() class ProjectMember(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='projects') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='members') role = models.CharField() In my views.py, I use ProjectMember as queryset and I can filter out the project that doesn't have any report, but can't find a way to filter out record where some member who haven't submit yet. This is what I currently get. Is there any way I can get only the first three? Project, Member, Role, Effort prj01, mem01, dev, 2 prj01, mem02, dev, 1 prj02, mem01, tst, 3 prj02, mem02, dev, null -
Save values into another database table with one-to-one relationship in Django during form update
This is my models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model. from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model class CustomUser(AbstractUser): email = models.EmailField(unique=True) post_code = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.username class UserComputedInfo(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) copy_input = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.copy_input Here is the relevant section of my views.py. from django.shortcuts import redirect from django.contrib import messages def profile(request, username): if request.method == "POST": user = request.user form = UserUpdateForm(request.POST, request.FILES, instance=user) if form.is_valid(): user_form = form.save() # How to save post_code to copy_input in UserComputedInfo model messages.success(request, f'{user_form.username}, Your profile has been updated!') return redirect("profile", user_form.username) return redirect("homepage") After a user submits a form, profile function will be run and post_code in CustomUser model will be updated. What I want to do is copy the content of post_code to copy_input in UserComputedInfo model as well. How do I do that inside my views.py? I am running Django v4 and Windows 10. -
Delete element with ajax in django
I am currently having some issue in deleting element with ajax in a Django Application. I have some pictures, each of them displayed in a bootstrap card. Basically, my code is kind of working, but I couldn't figure out why, for example, when I display the pictures in the card, in the first one of the list the Delete button doesn't work and, when I have multiple pictures, the delete button works but delete the first picture on the list and not the right one. I may have some mistake in fetching the IDs, but so far I couldn't find where the issue is. I post some code views.py def delete_uploaded_picture(request, pk): picture = Picture.objects.get(id=pk) if request.headers.get('x-requested-with') == 'XMLHttpRequest': picture.delete() return JsonResponse({}) js const deleteForms = document.getElementsByClassName('delete_form') deleteForms.forEach(deleteForm => deleteForm.addEventListener('click', (e)=>{ e.preventDefault(); let pk = deleteForm.getAttribute('data-pk') const cardDiv = document.getElementById('card_div'+pk) const clickedBtn = document.getElementById('clicked_btn'+pk) $.ajax({ type: 'POST', url: $("#my-url-div").data('url'), data: { 'csrfmiddlewaretoken': csrftoken, 'pk': pk, }, success: function(response){ $('#card_div'+pk).hide(); handleAlerts('success', 'Immagine Rimossa') }, error: function(error){ handleAlerts('danger', 'Ops qualcosa è andato storto!') } }) })) html <div class="form-group mt-2"> <div class="row"> {% if question.picture_set.all %} {% for pic in question.picture_set.all %} <div class="col-lg-4 col-md-6" id="card_div{{pic.id}}"> <form action="" method="post" class="delete_form" data-pk="{{pic.id}}"> <div … -
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' in Django 4 + highcharts
I'm trying to configure the display of graphs in django using highcharts and I encounter this error: AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' code: views.py import random from django.shortcuts import render from highcharts.views import HighChartsBarView class BarView(HighChartsBarView): title = 'Example Bar Chart' subtitle = 'my subtitle' categories = ['Orange', 'Bananas', 'Apples'] chart_type = '' chart = {'zoomType': 'xy'} tooltip = {'shared': 'true'} legend = {'layout': 'horizontal', 'align': 'left', 'floating': 'true', 'verticalAlign': 'top', 'y': -10, 'borderColor': '#e3e3e3'} @property def series(self): result = [] for name in ('Joe', 'Jack', 'William', 'Averell'): data = [] for x in range(len(self.categories)): data.append(random.randint(0, 10)) result.append({'name': name, "data": data}) return result index.html {% % load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hello</title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/highcharts/highcharts.js' %}"></script> <script type="text/javascript"> $(function () { $.getJSON("{% url 'bar' %}", function(data) { $('#container').highcharts(data); }); }); </script> </head> <body> <div id="container" style="height: 300px"></div> </body> </html> I have no idea how to fix it enter image description here -
Can I take live data from an external gps and plot it in an offline map using Django?
I want to see the live location and the changes when i change my location in my django local server by ploting it into an offline map. Is it possible? Can someone please share the resources too. -
Django admin inline auto creates multiple fields on admin panel
I have a TicketMessage model that contains a foreign key to Ticket. I wanted to have my TicketMessage message field appear on my Ticket admin panel as an inline. I did succeeded in doing so however as shown in the image below for some reason by default it creates three message fields instead of one. Would like to know how to make it so it shows only one message by default and the reason why this happens in the first place. TicketMessage model from django.db import models from django.utils.translation import gettext as _ from painless.models import TimeStampMixin class TicketMessage(TimeStampMixin): class Meta: verbose_name = _("Ticket Message"), verbose_name_plural = ("Ticket Messages") ticket = models.ForeignKey( "Ticket", default=False, on_delete=models.PROTECT, related_name="ticket_message", help_text="Lorem ipsum" ) message = models.TextField( _("message"), max_length=500, help_text="Lorem ipsum", ) def __str__(self): return f"Ticket subject: {self.ticket}" def __repr__(self): return f"Ticket subject: {self.ticket}" Ticket admin from django.contrib import admin from django.utils.translation import gettext_lazy as _ from desk.models import ( Ticket, TicketMessage ) class TicketMessageInline(admin.TabularInline): model = TicketMessage @admin.register(Ticket) class TicketAdmin(admin.ModelAdmin): list_display = ( 'subject', 'status_choices', 'priority_choices', 'is_read', 'is_important', 'is_archive', ) list_filter = ( 'is_read', 'is_important', 'is_archive', 'status_choices', ) inlines = ( TicketMessageInline, ) filter_horizontal = ( "tags", ) fieldsets = ( (_("Primary Informations"), { … -
Django /static/ files not found, 404 error
I have a problem with loading static files. It wont load images on my page at all. When i look for the address it says /apps/assets/img..... But it should be /static/assets/img like on the home page and login page. (/apps/ is my view name but i don't get it why it loads it like that..( All apps are in my installed apps directory, DIRS in templates is configured, i have 'django.contrib.staticfiles', tried running collectstatic, rerunning the server, ALLOWED_HOSTS = ["*"] , STATIC_URL = '/static/' , STATIC_ROOT = os.path.join(VENV_PATH, 'static_root' -
Is there a method to save model based form for specific user , I tried this but the form did not save on my data base, If I avoid author it saves
here is my models.py file, I try to save task, completed, and completiondate from my front with the logged-in user as a default author. *> #My models.py from django.db import models from django.contrib.auth.models import User class Task(models.Model): task=models.CharField(max_length=50) completed=models.BooleanField (default=False) comletiondate=models.DateTimeField (auto_now_add=False) author = models.ForeignKey(User, on_delete=models.CASCADE,default=None) def __str__(self): return self.task in my views.py file I try to save the data which I get from the front end with specific author #my views.py @login_required(login_url='/') def index(request): form=TaskForm() if request.method == 'POST': form=TaskForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() else: form=TaskForm() return redirect('/') context={'form':form} return render(request, 'todo/index.html',context) #my forms.py from django import forms from.models import * from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class TaskForm(forms.ModelForm ): class Meta: model=Task fields='__all__' class CreateUser(UserCreationForm): class Meta: model=User fields=['username','email', 'password1','password2']* -
How would I integrate BIRT with Python Django Project by using Py4j
Hi is there anyone who is help me to Integrate BIRT report with Django Projects? or any suggestion for connect third party reporting tools with Django like Crystal or Crystal Clear Report. -
Django rest authentication with email verification redirect to flutter app
How can I redirect a user to the mobile app developed in flutter after he has confirmed the authentication link sent by email? I need the token included in the link (same for password reset). Right now it takes me back to the django rest page. I am using dj-rest-auth and allauth to handle authentication in django. -
ModuleNotFoundError: No module named 'musiclibrary.song'
There is an issue while importing model 'Artist' of my django app in views.py. from musiclibrary.song.models import Artist when I runserver it gives ModuleNotFoundError. from django.shortcuts import render from django.http import HttpResponse from musiclibrary.song.models import Artist def hello_world(request): return HttpResponse("Hello World!") def home(request): return render(request, "home.html") def artist(request): artist_list = Artist.objects.all(). //// I have to make this line of code work context = {'artist_list': artist_list} return render(request, 'artist.html', context) Models code: from django.db import models class Artist(models.Model): name = models.CharField(max_length=250) country = models.CharField(max_length=150) birth_year = models.IntegerField() genre = models.CharField(max_length=150) class Song(models.Model): Title = models.CharField(max_length=250) release_date = models.IntegerField() length = models.DateField() artist = models.ForeignKey('Artist', on_delete=models.CASCADE) Error log: File "/Users/m.zcomputer/PycharmProjects/myFirstApp/musiclibrary/musiclibrary/views.py", line 4, in <module> from musiclibrary.song.models import Artist ModuleNotFoundError: No module named 'musiclibrary.song' -
Unexpected back button behavior after encountering external 404 using react SPA
I'm making a SPA app with react 18 and Django. I'm having trouble understanding and fixing an issue where after I encounter a 404 and press back, the browser's title changes but doesn't reload the page, even though the URL changes to match the title. To make it happen, I navigate to the home page, "/". I press a react "Link" to go to "/e" within the SPA. If I press reload on "/e", it works, because I added a path in the django urls.py for "/e" and also a react SPA react router route in my App.js. I then click another link to navigate to "/b". Now that I'm at "/b", which is a a react router route but NOT a django path, and refresh, I get a standard django "natural", non SPA 404. Pressing browser Back, the title of the "/e" route is correct, and the URL itself of the browser is correct, but the page does not reload my SPA and it stays a 404 page. I do not understand this behavior or know how to fix it. If I press back one more time, it will THEN reload the spa, and show "/" correctly, then pressing … -
Why Am I getting an Integrity Error while uploading csv file to django app?
While uploading a csv file I'm getting an Integrity Error. I have a correctly working QuizApp which has models about Quiz, Questions and Answers. But I've created another app csvs to upload csv file with Questions and Answers. While I'm trying to upload a CSV file I'm getting that error. The file isn't uploaded to the website. IntegrityError at /something/admin/csvs/csv/add/ null value in column "quiz_id" of relation "csvs_csv" violates not-null constraint DETAIL: Failing row contains (11, csvs/example_KLOIQJK.csv, 2022-09-15 05:46:25.666689+00, f, null) csvs.models.py class Csv(models.Model): file_name = models.FileField(upload_to="csvs") uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) csvs.forms.py from django import forms from csvs.models import Csv class CsvModelForm(forms.ModelForm): class Meta: model = Csv fields = ("file_name",) csvs.views.py from django.shortcuts import render from django.http import HttpResponse from .forms import CsvModelForm # Create your views here. def upload_file_view(request): form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm() return render(request, "csvs/import.html", {"form": form}) quiz.models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse, reverse_lazy import uuid class Quiz(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) short_description = models.CharField(max_length=500) resolution_time = models.PositiveIntegerField( help_text="Quiz Duration in minutes", default=15 ) number_of_questions = models.PositiveIntegerField(default=1) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) is_public = … -
Could not find a version that satisfies the requirement Python
Could not find a version that satisfies the requirement librabbitmq==1.6.1 (from versions: 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.5.0, 1.5.1, 1.5.2, 1.6.0, 1.6.1, 2.0.0) I am getting similar error while install librarabbitmq,numpy,supervisor,xattr,MySQL-python there are specific versions i am trying to install and it pops out the same error while the version remain in the packages it can't find those. -
Django-filters , display min price and max price in the placeholder
I have a models price and using class base views, i have added 'django_filters' to settings as well,this is what i have in my project: model.py class Product(models.Model): price = models.IntegerField(default=0) setting.py 'django_filters', views.py class ProductListView(generic.ListView): template_name = "product/product_list.html" queryset = Product.objects.all() filter_set = ProductFilter filters.py class ProductFilter(django_filters.FilterSet): min_price = django_filters.NumberFilter(field_name="price", lookup_expr='gt',widget=RangeWidget(attrs={'placeholder': 'min_price'})) max_price = django_filters.NumberFilter(field_name="price", lookup_expr='lt',widget=RangeWidget(attrs={'placeholder': 'max_price'})) class Meta: model = Product fields = { 'min_price', 'max_price' } everything is working perfectly when using price only in fields without 'min_price', 'max_price', but what i want is to have min_price and max_price show in my placeholder. When i run the code above, i get this error: "TypeError: 'Meta.fields' must not contain non-model field names: min_price, max_price" -
Restarted Apache2 with Ubuntu for a Django Website, and CSS format no longer recognized. The site only shows basic HTML format. Any ideas to fix this?
I had a functional Django Website that uses Materialize CSS apache2 and ubuntu. I made some small changes to the site (like changed text), then restarted the apache2 server sudo service apache2 restart After the restart, the website no longer showed the CSS format. The website is a basic html website now. I'm a quite new to building websites, so hoping there could be some ideas for what changed after the apache restart. -
Can I create Django widgets at an own discretion?
There is a widget in Django, called NumberInput, the type of which can be defined as range. It is an usual range. There is a graphical element – a slider (a range as well) in a website. That's convenient that it has an animated label with number value. A code and an image of the slider will be on the website. I found a supposed code realizing a similar thing, here is the code from that website: import floppyforms as forms class Slider(forms.RangeInput): min = 5 max = 20 step = 5 template_name = 'slider.html' class Media: js = ( 'js/jquery.min.js', 'js/jquery-ui.min.js', ) css = { 'all': ( 'css/jquery-ui.css', ) } I tried to redefine template_name variable with an html-file containing the code and also to point paths to css and js files but an error appears at testing in Django shell (run as python manage.py shell). If to apply a widget in Django form, to take an instance of the form, and to print the instance, then html code must be returned, but an error did. The error is about not existing a template (TemplateDoesNotExist). I think what to do. Can I create Django widgets at an own discretion? … -
Could not resolve URL for hyperlinked relationship django
Tried the solutions provided in question asked by Daniel Costa. Here is my models.py file class Integrations(models.Model): integration_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) integration_type = models.CharField(primary_key=True, max_length=256) def __str__(self): return self.integration_type class Meta: ordering = ["integration_type"] verbose_name = "Integration" verbose_name_plural = "Integrations" def get_default_mqtt(): return Integrations.objects.get(integration_type="MQTT") class MQTTSubscription(models.Model): mqtt_subscription_name = models.CharField( max_length=256, verbose_name="Subscription Name" ) mqtt_url = models.CharField(max_length=256, verbose_name="Mqtt Host") integration_type = models.ForeignKey( Integrations, default=get_default_mqtt, on_delete=models.PROTECT ) def __str__(self): return self.mqtt_subscription_name class Meta: ordering = ["mqtt_subscription_name"] verbose_name = "MQTT Subscription" The urls.py integrations_list = IntegrationsViewSet.as_view({"get": "list", "post": "create"}) integrations_detail = IntegrationsViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) mqtt_list = MQTTSubscriptionViewSet.as_view({"get": "list", "post": "create"}) mqtt_detail = MQTTSubscriptionViewSet.as_view( {"get": "retrieve", "put": "update", "delete": "destroy"} ) urlpatterns = [ path("integrations/", integrations_list, name="integrations_list"), path("integrations/<str:integration_type>/", integrations_detail, name="integrations_detaial"), path("mqttsubscription/", mqtt_list, name="mqtt_list"), path("mqttsubscription/<str:mqtt_subscription_name>/", mqtt_detail, name="mqtt_detail"), ] Views.py class IntegrationsViewSet(viewsets.ModelViewSet): serializer_class = IntegrationsSerializer queryset = Integrations.objects.all() lookup_field = "integration_type" class MQTTSubscriptionViewSet(viewsets.ModelViewSet): serializer_class = MQTTSubscriptionSerializer queryset = MQTTSubscription.objects.all() lookup_field = "mqtt_subscription_name" serializers.py class IntegrationsSerializer(serializers.ModelSerializer): class Meta: model = Integrations fields = ["integration_type"] class MQTTSubscriptionSerializer(serializers.ModelSerializer): lookup_field = "integration_name" class Meta: model = MQTTSubscription fields = [ "mqtt_subscription_name", "mqtt_url", "integration_type", ] The issue here is if "integrations/" is removed from urls.py it does not interpret the mqttsubscription/. While I update the … -
django unit testing timezone
In my settings.py I have implemented timezone as TIME_ZONE = os.environ.get("TIMEZONE", "Europe/London") How would I test if this is working on my test_timezone.py file? -
Django URL in Templates with Apache ProxyPass
I have a Django project behind a ProxyPass server in Apache. The project has an app called 'home', with this url patterns: urls.py urlpatterns = [ path('', views.HomeView.as_view(), name='index'), path('projects', views.HomeView.as_view(), name='dashboard'), path('projects/<int:pid>/members', views.ProjectMembersView.as_view(), name='project.members'), There are two URL that have the same View class (the first used for the root). In the HomeView class uses a template called 'dashboard.html' and get a list of projects to send to the template view class HomeView(LoginRequiredMixin, ListView): template_name = 'home/dashboard.html' context_object_name = 'projects' login_url = 'accounts.login' def get_queryset(self): ... # returns a list of projects The template renders a tablet with some information of the project and an URL to see the employess working on the project template <td class="align-middle text-center text-sm"> <a href="{% url 'project.members' pid=project.id %}">See employees</a> </td> In the case, the project behind the Apache ProxyServer, the URL generated in the template is the form: "https://example.com/4554/members", here, Django doesn't recognizes the URL The other situation, without Apache Proxypass the URL generated is like this: "http://127.0.0.1:8000/projects/4554/members", Django can recognize the URL and return the template when click in the link. The ProxyPass configuration in Apache is in file: "/etc/apache2/sites-enabled/the-projects.conf" proxypass <VirtualHost *:80> ServerName example.com ErrorLog /var/log/apache2/projects_perror.log CustomLog /var/log/apache2/projects_access.log combined RequestHeader … -
sqlite3 table is not updating when trying to add pandas dataframe
I am trying to add a Pandas data frame to a sqlite3 table in my Django project. However, when I try to add it to the table, nothing updates and no errors are printed in the console. For reference, the beginning of my code is correctly formatting the date in the csv file and then I am attempting to add it to an empty but existing table named 'daos_transaction' with the same attributes 'from_address', 'to_address', 'date_time', and 'amount'. import pandas as pd import sqlite3 # Reads data from csv file df = pd.read_csv("correct/path/to/csv/file") # Formats the date for dt in range(len(df['date_time'])): no_t_string = df['date_time'][dt].replace('T', ' ') clean_string = no_t_string.split('+')[0] df['date_time'][dt] = clean_string # Converts the column to a date time field df['date_time'] = df['date_time'].astype('datetime64[ns]') cnx = sqlite3.connect('correct/path/to/db') df.to_sql('daos_transaction', cnx, if_exists='append') -
Django Rest Framework With Djoser Jwt
I was looking into have more secure login and logout using JWT authentication and authorization .But in Djoser ,it has 3 endpoints /jwt/create/,/jwt/refresh/,/jwt/verify/. Here I want user login with jwt token and get verified token simultaneously and when logout refresh comes in to get access token.How could I do this?