Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django make pizza [closed]
Manage Toppings As a pizza store owner I should be able to manage toppings available for my pizza chefs. It should allow me to see a list of available toppings It should allow me to add a new topping It should allow me to delete an existing topping It should allow me to update an existing topping It should not allow me to enter duplicate toppings Manage Pizzas As a pizza chef I should be able to create new pizza master pieces It should allow me to see a list of existing pizzas and their toppings It should allow me to create a new pizza and add toppings to it It should allow me to delete an existing pizza It should allow me to update an existing pizza It should allow me to update toppings on an existing pizza It should not allow me to enter duplicate pizzas Can you guys help on how do I do this in Django project. -
How to fix {detail: Authentication credentials were not provided.} in Django Rest Framework
I have struggling with getting information from Django rest framework as a backend and from the frontend using flutter. The sequence of the project of the project is that I login and receive a {"key":"XXXXXXXXXXXXX"} Just for testing purposes I am trying to manully add the key to get access. I keep getting {detail: Authentication credentials were not provided.} I am not sure whether the error is because of Django Rest Framework setting or Flutter front end Here is the Fetch user() in the homescreen: Future<User> fetchUser() async { var url = Uri.parse(Config.apiURL + Config.userProfileAPI); print(url); final response = await http.post( url, // headers: { // HttpHeaders.authorizationHeader: // 'Bearer XXXXXXXXXXXXX', headers: { "Authorization": 'JWT XXXXXXXXXXXXX' // 'Authorization: ', },); final responseJson = jsonDecode(response.body); print(responseJson); if (response.statusCode == 200) { return User.fromJson(jsonDecode(response.body)); } else { throw Exception('Failed to load User'); }} class User { int? pk; String? username; User({this.pk, this.username}); User.fromJson(Map<String, dynamic> json) { pk = json['pk']; username = json['username'];} Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['pk'] = this.pk; data['username'] = this.username; return data;}} class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState();} class _HomeScreenState extends State<HomeScreen> { late Future<User> futureUser; @override … -
How do I change the verbose name of django table header
Since I can't use the verbose name of the model (Using jsonfields), I need a function which redefines the header's verbose name. As the docs say (Link to docs): In order of preference, this will return: The column’s explicitly defined verbose_name The model’s verbose_name with the first letter capitalized (if applicable) Fall back to the column name, with first letter capitalized. But how can I change this behaviour? I want to set the name of the columns header to something different. Currently I use def get_top_pinned_data(self): So I can show the verbose names on the top, but I want to sort it too. -
Django request.POST loop
How can I loop through the request data and post it as one line in to the database, user can submit multiple descriptions, lengths and so on, problem I have is in the DB its creating massive amounts of rows to get to the correct format of the last one A1 but the user could submit A1,1,1,1,1; A2,2,2,8,100 and so on as its a dynamic add form) descriptions = request.POST.getlist('description') lengths = request.POST.getlist('lengthx') widths = request.POST.getlist('widthx') depths = request.POST.getlist('depthx') quantitys = request.POST.getlist('qtyx') for description in descriptions: for lengt in lengths: for width in widths: for depth in depths: for quantity in quantitys: newquoteitem = QuoteItem.objects.create( qdescription=description, qlength=lengt, qwidth=width, qdepth=depth, qquantity=quantity, quote_number=quotenumber, ) bottom entry is correct post system -
Django celery task unable to use cairo svg2pdf
I have a small task that reads a svg file from a path and uses cairo svg2pdf to convert the svg to pdf. If I run the function without using celery delay then the function runs fine and converts the file to pdf. If I run the function as a celery task then I get some errors: Traceback (most recent call last): File "/..../tasks.py", line 24, in create_download_pdf svg2pdf(bytestring=bytestring, write_to=completeName) File "/.../lib/python3.10/site-packages/cairosvg/__init__.py", line 67, in svg2pdf return surface.PDFSurface.convert( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 131, in convert instance = cls( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 202, in __init__ self.cairo, self.width, self.height = self._create_surface( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 242, in _create_surface cairo_surface = self.surface_class(self.output, width, height) File "/.../lib/python3.10/site-packages/cairocffi/surfaces.py", line 876, in __init__ Surface.__init__(self, pointer, target_keep_alive=write_func) File "/.../lib/python3.10/site-packages/cairocffi/surfaces.py", line 158, in __init__ self._check_status() File "/../lib/python3.10/site-packages/cairocffi/surfaces.py", line 170, in _check_status _check_status(cairo.cairo_surface_status(self._pointer)) File "/../lib/python3.10/site-packages/cairocffi/__init__.py", line 88, in _check_status raise exception(message, status) OSError: [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: b'error while writing to output stream'] 11 Here is the function: @app.task(name="create_download_pdf") def create_download_pdf(folder_path: str, svg_data=None, filename=None, file_path=None) -> None: try: completeName = os.path.join(folder_path, f"{filename}.pdf") if svg_data: svg2pdf(bytestring=svg_data, write_to=completeName) elif file_path: with open(file_path, 'r') as f: bytestring=f.read() print(bytestring) svg2pdf(bytestring=bytestring, write_to=completeName) except (OSError, ValueError): logger.exception( f"PDF creation and download exception: Unable to download | create … -
Logic on serializer fields
I am trying to work out how to run some logic to get certain objects from within my serializer (or elsewhere). I have the following: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( Parent, related_name='children', on_delete=models.CASCADE) class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ( 'id', 'name', ) class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer() class Meta: model = Parent fields = ( 'id', 'name', 'children', ) class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer queryset = Parent.objects.all() class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer queryset = Child.objects.all() I would like to add a field to the parent response: first_child which is the first child alphabetically by name (this logic would be slightly more complex in reality, the largest value of the sum of multiple fields for example). I will also remove the children field in favor of this first_child field as the number of those will be too high to display in-line like this. -
Django doesn't return data from database on same HTML page as form
This is my final project for my college class and they required us to take many unnecessary steps in development I think may have overcomplicated my code but I am not sure what the best way to fix it is. I can get the data from the form into the database and then pass that data to the appropriate view where it queries yelp and puts it into a JSON file and then particular fields from the JSON file are saved to the database. My problem is that I can't seem to display the database data. After reviewing my code I think there may be too many steps along the way. I am thinking there is a simpler way to go about this but I don't want to destroy what I have trying to figure out and make it worse I am also concerned that I have made such a mess of things it needs an overhaul but I may be panicking lol. I am ok with the mess if I can get the information to display on the HTML page but I would like to know what the best way to write this would be if someone would like … -
Django admin foreignkey field in form
I have a model like class Info(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Detail(models.Model): info = models.ForeignKey(Info) ... In admin when I add Detail I want all the fields of Info model as a form field without + sign just as normal fields. How is this possible ? -
Trying to edit a profile using Django but keep running into bugs
I am really struggling to allow users to update the Profile model in my app. I'm working on building a web application that helps people set up a diet. The general structure is a website visitor shows up and immediately gets directed to a Sign In and either Registers or Signs In. When they register, a Profile is automatically created. The thought process was I would add the user data (height, weight, etc.) gets added to the Profile model. Right now a new user goes Sign in -> Register -> Sign In -> Profile (which is filled with blank data) -> and Edit Profile. The edit profile is where I'm stuck. No matter what I try, I keep running into errors and have been spinning my wheels too much. I would really appreciate some help. Models from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver #add this from django.db.models.signals import post_save #add this SEX = [('Male', 'Male'), ('Female', 'Female')] ActivityLevels = [('Sedentary', 'Sedentary'), ('Lightly active', 'Lightly active'), ('Moderately active', 'Moderately active'),('Active', 'Active'), ('Very active', 'Very active')] # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) massLbs = models.IntegerField("Weight in Lbs", null=True, blank=True) heightFeet … -
Automaticaly downloadable invoice pdf
I want to create an option to download a pdf file having an invoice with the following properties in the django database admin: models.py: from django.db import models from appsystem.models import Outlet from core.models import Item, Supplier from location.models import Warehouse, Zone, Section, Level class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) I need this to be a printable invoice slip with the specified values but I just can't get anywhere. -
ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' django
My site was working well in cpanel. when i add google search console for seo, after one day I am seeing such error. Passenger.log file My os is Windows. Please help guys. I would be very grateful. I installed psycopg2-binary as psycopg2 didnt work. -
Django template comparing strings returning false?
I have in my template a button that should only be visible if 1 The user is signed in and; 2 The user is the one who posted the listing but doesnt show up even if all the above conditions have been met, so i have this in my template: {% if user.username == "{{ users }}" %} <form action="listing" method="GET"> <input class="btn btn-primary" type="submit" value="Close Listing" name="close"> </form> {% endif %} where "{{users}}" is the username of whoever posted the listing, and thus if its a match, this user gets the button views.py listing = Listing.objects.all().filter(title=title).first() user = listing.user passing it to the template: return render(request, "auctions/listing.html", { "users": user }) Cant find what i am doing wrong -
Django count using in object list
I have two models - Book and Tags connected by ManyToMany. After filtering the list of books, I want to get the list of tags used in these books and the count for each tag. class Tag(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) type = models.CharField(max_length=255, default='tag') is_showing = models.BooleanField() using_count = models.IntegerField(default=0) def __str__(self): return self.name class Meta: constraints = [ models.UniqueConstraint( fields=['name', 'type'], name='unique_migration_host_combination' ) ] @property @lru_cache def count(self): cnt = self.book_set.count() return cnt class Book(models.Model): name = models.CharField(max_length=255) tag = models.ManyToManyField(Tag) def __str__(self): return self.name @property def tags_count(self): return self.tag.filter(type='tag').count() @property def genres_count(self): return self.tag.filter(type='genre').count() @property def fandoms_count(self): return self.tag.filter(type='fandom').count() The last time I manually took out a list of tags from each book and put them in a dictionary, after which I got a dictionary of the number of tags used, which was not very convenient to use in the django template engine -
how to render data from list in python over a html page?
lists = ['data1','data2','data3'] for in i lists time.sleep(5) //I would like to write a function that will take i as an //argument renders that in an html page something like this hello data1 after 5 seconds if we refresh the page hello data2 I am new to web development and I dont know how to implement it if some one could guide me it would be helpful -
in django how can i reverse to that page when info submitted
class ModelCreateView(CreateView): model = Message fields=['message'] template_name = "page.html" succes_url = reverse='page' No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. this is error but if i put get absolute url reverse going detail page -
How can i create a Array Custom Model Field
class PermsField(models.Field): def db_type(self, connection): return 'CharField' def __init__(self, *args, **kwargs): kwargs['max_length'] = 64 kwargs['verbose_name'] =_('permission') super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] del kwargs["verbose_name"] return name, path, args, kwargs I want to create a custom model Field who behaves like an array but i can't use an array. I don't understand because my code doesn't work, the permsField work like an str. But i want it work like an array (or list) of str -
Javascript Fetch Function returns [object Promise]
I'm currently working on a project, which includes a website, built and run by Django. On this website, I'm trying to load data through fast API and try to load this data through JavaScript and the Fetch API. But I always get instead of the Data provided through the API, an [object Promise]. I've tried many different methods but none seem to work. Any help will be greatly appreciated! I've tried for example: document.getElementById("1.1").innerHTML = fetch('the URL') .then(response => response.text()) or document.getElementById("1.1").innerHTML = fetch('the URL') .then(response => response.text()) .then((response) => { console.log(response) }) and many other methods. I've also checked and the API request works perfectly, returning a string. -
django modified_at field with database level auto update
I need to have modifed_at fields in my Django project. A field that updates every time a row updates in the database, despite where the update comes from: through calling .save() or through queryset.update() or even when updates happen in the database directly and not from the Django app. there is an auto_now property that does not solve my problem according to this SO question(based on Django document). other SO questions(like this and this) ask the same thing, update instance at every change not only .save() This problem can be solved using triggers as said here but this way we need to write the same trigger for every modifed_at field in models. as discussed in this Django ticket this probelem will not be addressed and solved in Django. even the suggested patch only updates the instance if it changes via Django. the only way that comes to my mind is to do something like this in a mixin. a mixin that when inherited creates a trigger for fields with auto_now=True. maybe change SQL when Django creates the model creation SQL. but I don't know how to implement this. so I have two questions: what is the best way to achieve … -
Corrent Way to Structure Models, Views and Serializers
I have the following structure of Parent and Child models, where the child references the parent. class ParentModel(models.Model): name = models.CharField(max_length=255) class ChildModel(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( ParentModel, related_name='children', on_delete=models.CASCADE ) created_by = models.ForeignKey(User, on_delete=models.CASCADE) class ParentSerializer(serializers.ModelSerializer): class Meta: model = ParentModel fields = ( 'name', 'children', ) class ChildSerializer(serializers.ModelSerializer): class Meta: models = ChildModel fields = ( 'name' ) class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer queryset = ParentModel.objects.all() class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer def get_queryset(self): user = self.request.user return ChildModel.objects.filter(created_by=user) I would like for ParentSerializer.children to only include the ChildModel objects with created_by as self.request.user. What is the correct way to filter ParentSerializer.children to the current user? I am open to changing the models as well. -
Create button to update in django posts with javascript fetch
I have an html that displays user's posts. At the same time, the post model is accessible via fetch (javascript). I want to create a button to update the content of the posts that django shows but with the fetch. The problem is that when the button is created in my code, instead of creating a button for each post, it creates 5 update buttons in the first post and it is logical because that is the id that I give it. How can I add a button to each of the posts that django shows with javascript? Note: the project its a test for the real project. I want to add a update button with javascritp in a django posts for update a field My html: <div id="formulario" class="form-style" style="border: 5px solid rgb(255, 170, 0);"> <h1>User's Posts</h1> {% for post in object_list %} <div id="posts-div" style="border: 5px solid red;"> <h3 id="user">{{post.usuario}} - User with id: {{post.id}}</h3> <h3>{{post.contenido}} - {{post.id}}</h3> </div> {% endfor %} <h1>Agregar</h1> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> </div> My views.py class PostsViewSet (viewsets.ModelViewSet): queryset = Posts.objects.all() serializer_class = PostsSerializer class PostView(CreateView, ListView): model = Posts fields = ['contenido','edad','usuario'] template_name = 'api_app/posts.html' … -
How to use ColorThief with Django Rest Api?
I'm very beginner with coding. I want to get a dominant color from pictures. Color have to be saved and showed as a hex code. For now i have created simple code with picture name, width and height. I don't know how to implement ColorThief to this small project. In models file at the bottom i have created some code which i don't know how to run. Here are some of my files: Models: from django.db import models from colorthief import ColorThief class UploadImage(models.Model): name = models.CharField( 'Name', max_length=100, ) image = models.ImageField( 'Image', upload_to='uploaded_media/', width_field='width', height_field='height', ) height = models.PositiveIntegerField( 'Image Height', blank=True, null=True, ) width = models.PositiveIntegerField( 'Image Width', blank=True, null=True ) def __index__(self): color_thief = ColorThief(self.image) self.image = (color_thief.get_color(quality=1),) self.save() return f'#{self.image[0]:02x}{self.image[1]:02x}{self.image[2]:02x}' Viewsets: from rest_framework import viewsets from rest_imageupload.serializers import UploadImageSerializer from imageupload.models import UploadImage class UploadImageViewSet(viewsets.ModelViewSet): queryset = UploadImage.objects.all() serializer_class = UploadImageSerializer Serializers: from rest_framework import serializers from imageupload.models import UploadImage class UploadImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = ('name', 'image', 'width', 'height') -
django-allauth messages not being displayed correctly
I'm using django-allauth in a project but unfortunately the messages on login and logout are not being displayed correctly. For example when I logout this message appears: <django.contrib.messages.storage.fallback.FallbackStorage object at 0x7f5b3f2c5e48> I've tried to reinstall Django and django-allauth but it hasn't fixed the problem. Any help/pointers much appreciated. -
One Wagtail API endpoint with different ViewSets
I'm using Wagtail API to set up a site with a single endpoint, but different Page types under that endpoint. In short, I have two models class TeamPage(Page) and class BlogPage(Page): and I want the following url paths GET /teams - TeamsAPIViewSet.listing_view to return a list of all TeamPages GET /teams/<slug> - TeamsAPIViewSet.detail_view to return the detail for a single TeamPage GET /teams/<slug>/blogs - BlogsAPIViewSet.listing_view to return a list of all BlogPages for a specific team GET /teams/<slug>/blogs - BlogsAPIViewSet.detail_view to return a specific BlogPage Registering the "teams" endpoint in api.py only allows a single ViewSet for that endpoint api_router.register_endpoint('teams', TeamsAPIViewSet) so, /api/teams will always use the TeamsAPIViewSet. I tried setting up paths in urls.py as follows: path('api/teams/', TeamsAPIViewSet.as_view({"get": "listing_view"}), name="listing"), path('api/teams/<slug:slug>/', TeamsAPIViewSet.as_view({'get': 'detail_view'})), path('api/teams/<slug:team_slug>/<slug:slug>', ContentAPIViewSet.as_view({'get': 'detail_view'})), path('api/teams/<slug:team_slug>/blogs/', BlogsAPIViewSet.as_view({'get': 'listing_view'})), path('api/teams/<slug:team_slug>/blogs/<slug:slug>/', BlogsAPIViewSet.as_view({'get' : 'detail_view'})), but that throws an exception, 'Request' object has no attribute 'wagtailapi_router' Any suggestions are appreciated. -
process remind to user on exact date and time in django
So I have notification system in place.For example when sending a task to user, user get a notification within my system. Right now I have only "instant" notifications. so when I send a task to someone, a notification is created in the db, and via web-socket the user is notified with the data of the notification. With the Reminder I have the problem, that the notification I want to send here is not necessarily "instant". I want to set the date to next Monday on 9 am. so User should receive the notification on Monday 9 am. Question: Is there an extension in django (or onboard methods) where I can execute stuff delayed? For example, send notification with the following data on Monday 9 am. -
How do I send available_apps in context to a view that is outside the admin panel in Django?
How can I get an application list like in get_app_list method in classy AdminSite? I try to do it this way, but then I get an empty list. from django.contrib.admin.sites import AdminSite def change_view(self, request): ... context = { ... 'available_apps': AdminSite().get_app_list(request) } return render(request, 'parts/part_form.html', context=context) I need this to display the admin side menu outside the admin panel.