Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store important queries in Djando models itself?
there are couple of queries which are important and used several times in different part of application. I wounder it would be great to have a method in the Model itself to retrieve requested data as needed. tried Classmethod and instance method but as the Manager is called in the query I got below error: AttributeError: Manager isn't accessible via ... instances code is look like below: class XDL(models.Model): name = models.CharField(max_length = 20) Order_Code_Description = models.CharField(max_length = 355) Status = models.CharField(max_length = 20) Supplier = models.CharField(max_length = 100) @classmethod def get_count_xdls(cls): return cls.objects.all() #query example def get_all_supps(self): return self.objects.all() #query example explained in Django documentation below: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations Is there a best practice to store important queries in a method somewhere in Model (or other parts)? as these queries run several time and also writing it as a method help the documentation as well. -
Django: only CSS is not served by Nginx
I deployed my Django app on a VPS with Nginx and I want Nginx to handle the statics. The strange thing right now is that all the images are rendered properly, but the CSS is not working at all... Django setting: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') Nginx configure: location /static/{ alias /home/xxx/App/django_app/static_root/; } In html template: <link rel="stylesheet" href="{% static 'app1/css/style.css' %}" type="text/css" media="all"> <img src="{% static 'app1/images/page1_img1.jpg' %}" alt=""> I've run python manage.py collectstatic, set Debug = False (everything works fine when Debug is true). I can confirm that all images are located in /home/xxx/App/django_app/static_root/app1/images, while all css files are under /home/xxx/App/django_app/static_root/app1/css. I'm able to access the css file with the url https://myserver/static/app1/css/style.css, also there is no error message in Nginx log. I've tried different browsers, cleared cache, restarted the server and Nginx several times with no luck, really running out of idea... Any suggestion would be appreciated. -
Django - ForeignKey Add Users Value As Default
I'd like to implement a grading model into my Django WebApp. This Grade Model has 3 ForeignKeys being a student, a subject and the schoolclass of the student. Is there a way to default the value of that field to student.klasse (which is already a field in the student model). models.py class Person(AbstractUser): # called the model Person since they can be teacher or student klasse = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, blank=True, null=True) class Test(models.Model): student = models.ForeignKey(Person, on_delete=models.CASCADE, blank=True, null=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) It throws this Error when trying to make the migration: school_class = models.ForeignKey(SchoolClass, on_delete=models.CASCADE, default=student.klasse_id, blank=True, null=True) AttributeError: 'ForeignKey' object has no attribute 'klasse_id' -
TypeError: translation() got an unexpected keyword argument 'codeset'
I'm following a Python tutorial on youtube and need to create a django website, however I am unable to start, because when I enter "python manage.py runserver" I get the "TypeError: translation() got an unexpected keyword argument 'codeset'" message. I've run back the video like 20 times to see if I've missed anything, but no, because it's just the beginning of the django website tutorial. I've also tried typing python3 instead of python and some other options I saw on Stack Overflow, but none are really exactly relevant to the error message I'm getting. Perhaps someone knows how to fix this? I tried to start a development server by typing in "python manage.py runserver" which was supposed to start a django webserver at 127.0.0.1:8000 or something, but instead I got the error message specified in the title code: PS C:\Users\kaspa\PycharmProjects\PyShop> python manage.py runserver Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x00000145784C1F80> Traceback (most recent call last): File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\kaspa\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, … -
How to 'add' QuerySet in Django?
I have written the below code. for number in numbers: booking_list = Booking.objects.filter(rooms=number) Here, numbers is a list of numbers. The problem with this code is that booking_list will only contain the QuerySet of the last number as the previous QuerySets will be overwritten but I want booking_list to contain all the QuerySets. Moreover, I want the QuerySets to be unique. In other words I want a union of the QuerySets. The reason as to why the QuerySet may have repeated vaues is because rooms is a list of numbers. Edit: The actual problem is complex. models.py class Booking(models. Model): customer_name = models.CharField(max_length=30) check_in_date = models.DateField() check_in_time = models.TimeField() check_out_time = models.TimeField() room_numbers = models.CharField(validators=[validate_comma_separated_integer_list], max_length=4000) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ('King', 'King'), ('Queen', 'Queen'), ) category = models.CharField(max_length=9, choices=ROOM_CATEGORIES) PERSON = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) person = models.PositiveSmallIntegerField(choices=PERSON, default=1) no_of_rooms = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], default=1 ) room_numbers can have values like [4, 21, 62, 50, 2, 12]. views.py for room_number in room_numbers: regex = rf"\b{room_number}\b" keys = ['room_numbers__iregex', 'customer_name', 'check_in_date', 'check_in_time', 'check_out_time', 'category__in', 'person__in', 'no_of_rooms'] values = [regex, customer_name, check_in_date, check_in_time, check_out_time, category, person, no_of_rooms] parameters = {} for … -
How to create a user specific home page
I'm busy learning Django. My current home page displays the posts, or posted passwords, for all users that have an account. I want the login page to display data unique to the logged in user. I've looked all over for a solution to this ... It seems straightforward, but I can't figure it out. I already have a detailed view for all posts created by a single user, but I don't know how to adapt that to serve as the actual home page once a user has logged in. Here's some of the code I've experimented with so far. I guess I'm trying to merge the functionality of UserPasswordListView class with the index view ... but I'm just not sure how to do so. views.py def index(request): context = { 'sites': SitePassword.objects.all() } return render(request, 'core/index.html', context) class PasswordListView(ListView): model = SitePassword template_name = 'core/index.html' context_object_name = 'sites' class UserPasswordListView(ListView): model = SitePassword template_name = 'core/user_sitepassword.html' context_object_name = 'sites' def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return SitePassword.objects.filter(user=user) class PasswordDetailView(DetailView): model = SitePassword models.py class SitePassword(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) password = models.CharField(max_length=200) email = models.CharField(max_length=200) logo = models.CharField(max_length=300) def __str__(self): return self.name def get_absolute_url(self): return reverse('sitepassword-detail', kwargs={'pk': … -
How to join two tables in Flask using mysqldb
I have two tables: the client table and the task table. I have added clients like 1) id , name,emai, phone,project. now I have to use this client in my second table task when I add a task it shows the client name automatically in task table form. how to get this using Flask and mysqldb (not sqlalchemy) i will get empty value insted of it shwo client -
django test.py changes the autoincrement of table
In the test.py I make new entry id=10000 for testing purpose(id is auto increment, current auto increment number is 36) temp = sm.mytable(id=10000,created_by="test",created_at=datetime.datetime.now()) temp.save() After test, this row is removed() automatically. However autoincrement number start from 10000~ Why this happen? database control in test.py affect the real database? -
why my second app doesn't want import to first app Django
File "C:\python mini\PyCharm Community Edition 2021.1.1\MyBlog\mysite\mysite\urls.py", line 3, in <module> from mysite.register import views ModuleNotFoundError: No module named 'mysite.register' Why do you think this error might occur? Why doesn't django see the app being imported? maybe I should try setting up mysite/blog urls? project structure: settings.py ` from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_DIR = os.path.join(BASE_DIR, 'static') CRISPY_TEMPLATE_PACK = "bootstrap4" STATIC_URL = '/static/' SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'menu', 'register.apps.RegisterConfig', ] mysite/urls.py from django.contrib import admin from django.urls import path, include from mysite.register import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path("register/", views.register, name="register"), ] ` If i try write just from register import views import underlined in red -
What do I have to do to make a django project available to my company's internal network?
Recently I developed a simple django project to be used by my colleagues. The goal was to have the project only available within the network so no one outside the company could access it. The company has a server, with a certain IP that will host the project. What steps do I have to take, either in django or on the company server, to make the project available to everyone in the company? Do I have to install python in the server? I tried to put the servers IPs in allowed_hosts but it doesn't work. Thanks for helping, Edward -
Getting incorrect title in the URL path Django
I have an app with a bunch of POST request on a path that looks like this: path("auctions/<str:title>", views.listing, name="listing") It's a sort of auction app, where users can create listings, and others can place bids and purchase these items. When a user clicks on one of these items, ive got this function that takes them to a page where they can get all details about the listing that they have just clicked and they can do things like place a bid or place the item in their watchlist. views.py def listing(request, title): if request.method == "POST": if watchlist.is_valid(): if "watchlist" in request.POST: watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first() if watchlist_data: watchlist_data.delete() else: true_wtchlist = Watchlists.objects.create(title=title, user=username) ps: watchlist here is just an example of one of the conditions under my function, i just posted it as an example, even though i will appreciate any errors beign pointed out if any is noticed. I can usually get the title of the listing that was clicked from the title argument that gets passed here def listing(request, title): , and i use this title to query the database. Now I am trying to add a 'Close listing' button to the page so that the … -
Django admin inline: Clone entry
I`m using a GenericStackedInline in my django admin. I would like to have the option to duplicate the inline object when editing the parent object. I can think of two ways of doing this: Using django-inline-actions to add a "clone" button. This did not work, because it does not show when using a fieldset in the GenericStackedInline Adding another checkbox next to "delete" checkbox with label "clone". When activating the checkbox and saving parent object, it should clone the inline object with new id. Is there an easy way to add another checkbox and add a action to handle cloning? -
video steaming using django Rest Framework
RestAPI Streem Video How i can do for this based requeste input:Video,Timesteemp, output: Return Based on Timeframe or base64 data Next Video Chunks send back -
Django suddenly refuses to load statics [closed]
Sorted this problem out before with "python manage.py collectstatic", but Django started to refuse loading static files for no reason. The error message on the terminal is: Not Found: /img/undraw_profile.svg What should I do? I cleared cache, made command 'collectstatic' again, checked root directory in settings.py but still could not find why. -
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.