Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stuck on how to create an Invoice Form with Django
I'm trying to create an invoice that will generate data from related tables, but I'm not sure how to proceed. In essence, an Invoice instance should capture logged hours found in a Timesheet model and be multiplied by a rate found in another table (ProjectUser) I have attached what the database schema looks like: https://dbdiagram.io/d/5ef0e2bc9ea313663b3ae6e4 How can I populate the amount field on my Invoice ModelForm with data from ProjectUser (user_hour_cost) and Timesheet (day_1 through day_7). Say user_hour_cost is 500, and the sum of the values for day_1 through day_7 is 50. How can I display on the Invoice form the amount value 25000? (500 * 50). -
chown command does not work to give permissons for sqlite database
I have a django app deployed on digital ocean. When I try to use functions of it that write in the database I get a permission error. On the digitalocean website I found the following solution;chown django:django db.sqlite3 My username on my server isn't django, so i ran the command with my username. Nothing changed. What can I do? -
Error when trying to import django templates
i got this html template(sorry i dont' know how to separate 2 codes from each other so i'm adding django code on the same place) ,I get this error from the webpage: django.template.loaders.filesystem.Loader: D:\lirdi\python\django_blog_project\djangonautic\home\homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\lirdi\python\django_blog_project\interpreter\lib\site-packages\django\contrib\admin\templates\home\homepage.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\lirdi\python\django_blog_project\interpreter\lib\site-packages\django\contrib\auth\templates\home\homepage.html (Source does not exist) <html> <head> <title>Homepage</title> </head> <body> <h1>This is the homepage</h1> <p>Welcome to Djangonautic</p> </body> </html> //This is my code at views file def homepage(reqeust): return render(reqeust,'home/homepage.html') //this is my code at settings file 'DIRS': ['templates'], -
Django netbox Static Media Failure
Installing netbox using Django and nginx (https://netbox.readthedocs.io/en/stable/installation/4-http-daemon/) i have a problem as django gets (The following static media file failed to load: select2-bootstrap-0.1.0-beta.10/select2-bootstrap.min.css) and multiple files and only work when i use Python3 manage.py runserver --insecure -
Forloop.counter in Django
{% for each_item in item.artifacts %} {% if each_item.scanner_count > 0 and each_item.scanner_match > 0 %} {% if forloop.counter <= 5 %} <tr> <td>{{each_item.threat_name}}</td> </tr> {% else %} {% if forloop.last %} <p><b><i> {{ forloop.counter|add:"-5" }} rows were truncated. See full report for more details. </i></b></p> {% endif %} {% endif %} {% else forloop.counter -=1 %} {% endif %} {% endfor %} ERROR:Malformed template tag at line 171: "else forloop.counter -=1" I want to increment the counter only when if condition is successful. Dont know how to do it with forloop.counter. Goal is to print 5 rows of valid output(scanner count >0 and Scanner match >0) -
Page not found (404) Request Method: POST Request URL:http://127.0.0.1:8000/reg_done Am new to this so please help me out
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.Index, name='Index'), path('register/', views.register, name='register'), path('login/', views.login, name='login'), path('register/reg_done/', views.reg_done,), ] Above is my urls.py. What i am trying is to get my reg_done page come up as after a user click on the submit button to save the regestration info. But its showing that this page not found. I tried to change the path in form action as register/reg_done/. But then it showed the same error with register/register/reg_done. Do help me out in this. IN HTML I am Giving Form Action the value"/reg_done" Thats it. Below is my views.py from django.shortcuts import render from django.http import HttpResponse import sqlite3 # Create your views here. def Index(request): return render(request, 'index.html') def register(request): return render(request, 'register.html') def login(request): return render(request, 'login.html') def reg_done(request): name = request.POST.get('name') mail = request.POST.get('mail') phone = request.POST.get('phone') psw = request.POST.get('psw') pswr = request.POST.get('pswr') all = [name, mail, phone, psw, pswr] return render(request, 'reg_done.html', {'all':all}) -
Subdirectories inside Django app not considered by migrations
I want to create subdirectories inside a Django app, containing a models, but I can't find a way to make migrations to include such models. This is how my project is structured: As you can see, app Attractora includes a directory calles auth, which includes a file models.py. The problem is that python manage.py makemigrations don't consider models in that file. Is there a way to instruct Django to include them? -
how can you calculate execution time of a view in Django?
this is my view: def post_detail(request, year, month, day, slug): post = get_object_or_404(models.Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) comment_form = forms.CommentForm() comments = post.comments.filter(active=True) context = { 'comments': comments, 'post': post, 'comment_form': comment_form, } return render(request, 'blog/post_detail.html', context) is there any way to calculate time of execution in Django ? -
Test timezone in Django model
I am trying to test a model in django but I faced a issue with the DateTimeField(auto_now_add=True) method. I see that since I am asserting equal to the model creation, the message error is telling me that there is a difference of almost one millisecond. I've tried to find the solution but I don't know how to fix this issue. Here is the code: class Contact(models.Model): name = models.CharField(max_length=80, blank=False) email = models.EmailField(blank=False) subject = models.CharField(max_length=40, blank=False) message = models.TextField(blank=False) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return 'Contact {} by {}'.format(self.contact, self.name) # test_cotact_model def test_cotact_model(self): contact = Contact.objects.create( name = 'neil', email='neil@email.com', subject= 'this is a test.', message = 'test', created_on = timezone.now(), active = False, ) contact.save() self.assertEquals(contact.name, 'neil') self.assertEquals(contact.email, 'neil@email.com') self.assertEquals(contact.subject, 'this is a test.') self.assertEquals(contact.message, 'test') self.assertEquals(contact.created_on, timezone.now()) self.assertEquals(contact.active, False) # Error self.assertEquals(contact.created_on, timezone.now()) AssertionError: datetime.datetime(2020, 6, 22, 19, 0, 54, 413700, tzinfo=<UTC>) != datetime.datetime(2020, 6, 22, 19, 0, 54, 414675, tzinfo=<UTC>) I have even saved the timezone.now() in a variable also changed the assertEquals() method for the timezone after the contact.save() command to see whether I could match the time but with no success. -
Form dropdown from different models
I have models as CustomPermission and DelegatedPermission. User gets CustomPermission when it is created. Later on, these permissions can be delegated to another user, then appears in DelegatedPermission table. I need DelegatedPermission table to track which permission is delegated by whom to whom. Problem: User A delegates can_view permission to user B. Then User B should be able to see this permission among his other permissions and delegate to another user. user B delegates permission In permission dropdown I need to see user B's CustomPermissions and its DelegatedPermissions together (which are delegated from other users). When I add user B's delegated permissions from DelegatedPermission table to permission dropdown, I cannot use them. Because they are from different models. I can only use permissions from CustomPermission model to create a new delegation. class CustomPermission(models.Model): codename = models.CharField(_('codename'), max_length=100)... class DelegatedPermission(models.Model): delegator = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='delegator') receiver = models.ForeignKey(User, null=True, on_delete=models.CASCADE,related_name='receiver') permission = models.ForeignKey(CustomPermission, null=True, on_delete=models.CASCADE,related_name='delegatedpermissions')... -
Django Rest Framework I have multiple tables that have foreign key of User, how I do create update and delete?
Django rest framework I have four table that have user as foreign key and I want to create update and delete tables with foreign key. Models.py from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.db import models from .managers import UserManager from django.conf import settings # Cutom User model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_lenght=50, unique=True) name = models.CharField(max_length=30, null=False, blank=False) first_name = models.CharField(max_length=30, null=False, blank=False) last_name = models.CharField(max_length=30, null=False, blank=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) date_updated = models.DateTimeField(_('date updated'), auto_now=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'first_name', 'last_name'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') # to set table name in database db_table = "users" # Address model class UserAddress(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='address', on_delete=models.CASCADE) address_office = models.CharField(max_length=30, null=False, blank=False) addres_phone_number = models.CharField( max_length=30, null=True, blank=True) address_website = models.CharField(max_length=30, null=True, blank=True) address_pobox = models.CharField(max_length=30, null=True, blank=True) address_district = models.CharField(max_length=30, null=False, blank=False) address_region = models.CharField(max_length=30, null=False, blank=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) date_updated = models.DateTimeField(_('date updated'), auto_now=True) class Meta: verbose_name = _('address') verbose_name_plural = _('address') # to set table name in database db_table = "address" # Report model class UserReport(models.Model): user = … -
Django - Save only time and validate start time is earlier than end time
I have a Django Model - class Store(models.Model): store_id = models.AutoField(primary_key=True) contactNumber = PhoneField(blank=True, help_text='Contact number') startTime = models.TimeField(auto_now = False, auto_now,add = False) endTime = models.TimeField(auto_now = False, auto_now,add = False) How do I ensure that startTime is always less than endTime ? -
Middleware in GraphQLView doesn't work in Django Ariadne Graphql
i am new to ariadne, i defined my typedef and resolvers and every thing is up and runing, but i want to use django-ariadne-jwt for JWT things in my project, in django-ariadne-jwt documnets there is a line of code which doesn't work, the line is : urlpatterns = [ path( "graphql/", csrf_exempt( GraphQLView.as_view( schema=schema, middleware=[JSONWebTokenMiddleware()] ) ), name="graphql" ) ] in GraphQLView.as_view function i pass middleware=[JSONWebTokenMiddleware()],it is necessary for authorization and token verification, but this middleware doesn't work anyway, can any one give me a solution? django-ariadne-jwt doc: https://pypi.org/project/django-ariadne-jwt/ -
Django fails to loaddata with deserialization error
I am running Wagtail which runs on django and when running dumpdata > dump1.json it seems to work fine. After that I delete the sqlite database and remove the migrations from the apps migrations directory so I can have an empty database and test the dumped data. After running migrate I execute loaddata dump1.json and the following error comes up Tracking file by folder pattern: migrations Traceback (most recent call last): File "/home/user/Desktop/projects/mytestwebapp/venv/lib/python3.8/site-packages/django/core/serializers/json.py", line 68, in Deserializer objects = json.loads(stream_or_string) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/pycharm-professional/plugins/python/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/opt/pycharm-professional/plugins/python/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/usr/lib/python3.8/runpy.py", line 207, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/usr/lib/python3.8/runpy.py", line 97, in _run_module_code _run_code(code, mod_globals, init_globals, File "/usr/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/user/Desktop/projects/mytestwebapp/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/user/Desktop/projects/mytestwebapp/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/user/Desktop/projects/mytestwebapp/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line … -
Django polymorphic admin list views
I have a list of global configuration variables in my Django code, where some are integers, and some are strings. I am currently using django-polymorphic, such that the base model has the name, and the child models have the values. For example: class Configuration(PolymorphicModel): name = models.CharField(max_length=128, unique=True) def __str__(self): return self.name class ConfigurationInt(Configuration): value = models.IntegerField(default=0) def __str__(self): return f'{self.name} = {self.value}' class ConfigurationStr(Configuration): value = models.CharField(max_length=256,default='') def __str__(self): return f'{self.name} = {self.value}' The models are then registered to the admin part like so: @admin.register(Configuration) class ConfigurationAdmin(PolymorphicParentModelAdmin): list_display = ('__str__',) child_models = (ConfigurationInt, ConfigurationStr) @admin.register(ConfigurationInt) class ConfigurationIntAdmin(PolymorphicChildModelAdmin): base_model = ConfigurationInt @admin.register(ConfigurationStr) class ConfigurationStrAdmin(PolymorphicChildModelAdmin): base_model = ConfigurationStr Unfortunately the __str__ part only shows the base class one in the shared list view of "Configuration". The value can't be accessible in any way that I can see, other than looking in the specific lists of "ConfigurationInt" and "ConfigurationStr". Is there any kind of way to actually list them in one nice list? Let's suppose I forget django-polymorphic and go with sparse data, such that each configuration has both an integer and a string, and some mechanism to state what it should be, like a type integer. I could then show the … -
Update an instance of a model in django such that the older instance and its relationship with other instances remain unaffected
I have been working on a e-commerce project. I have three models Item, OrderItem, Order. They are linked with Foreignkey(s) (Item -> OrderItem -> Order). Item is the actual product and an Order contain(s) Item(s). Item basically represents a product. In Item there is an attribute 'price' which needs to updated as need suggest. Like during a sale or something else. What happens is when I update the price of an Item, the price of that item also gets updated in the instances of the Order(s) that are already completed. Basically I would want to separate these models in a way such that any changes in the Item model doesn't effect the Orders that are completed. class Item(models.Model): title = models.CharField(max_length=100) sku = models.CharField(max_length=8, validators=[ MinLengthValidator(8)], unique=True) upc = models.CharField(max_length=12, validators=[ MinLengthValidator(12)], unique=True, blank=True, null=True) date_updated = models.DateTimeField( auto_now=True, blank=True, null=True) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField(upload_to=upload_location, blank=True, null=True) stock_quantity = models.IntegerField(default=0) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) item_variations = models.ManyToManyField(ItemVariation) quantity = models.IntegerField(default=1) purchase = models.FloatField(blank=True, null=True) def get_total_item_price(self): return self.quantity * self.item.price class … -
How to call model method in django view?
I'm trying to call a method in my Conversation model to get the latest message in my template. Here's my model.py: from django.db import models from django.contrib.auth.models import User class Conversation(models.Model): participants = models.ManyToManyField(User) def get_last_message(self): lastmessage = Message.objects.filter(conversation=self).order_by('id')[0] return lastmessage class Message(models.Model): sender = models.ForeignKey(User, on_delete= models.CASCADE, related_name="sender") recipient = models.ForeignKey(User, on_delete= models.CASCADE, related_name="recipient") text = models.TextField(null=False, blank=False) timestamp = models.DateTimeField(auto_now_add=True) conversation = models.ForeignKey(Conversation, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return self.text And here is my template: {% for conversation in conversations %} <p>{{ conversation.get_latest_message.text }}</p> I don't see any errors but there isn't any output. I can display the conversation.participants fine, but the call to the get_latest_message method doesn't do anything. What am I missing? Thanks! -
Can we make either of the serializer fields compulsory in the serializer class itself?
I have a serializer class, which I want to primarily use to fetch request data and use it to save details in different models. I want to have in request body either one or both the parameters. I can handle it in my views.py, though I want to know is there a way we can have that either or both check inside the serializer class itself? Thanks in advance :) #serializers.py class ScanUpdateSerializer(serializers.Serializer): assets = serializers.ListField(child=serializers.DictField()) issues = serializers.ListField(child=serializers.DictField()) -
Django python how do i get multiple images in a model
class Product(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) price = models.DecimalField(max_digits=9, decimal_places=2) quantity = models.IntegerField() categories = models.ManyToManyField(Category, related_name='categories') image = models.ImageField(default='default.jpg', upload_to='product_images') image2 = models.ImageField(default='default.jpg', upload_to='product_images') image2 = models.ImageField(default='default.jpg', upload_to='product_images') active = models.BooleanField(default=True) created_at = models.TimeField(auto_now_add=True) updated_at = models.TimeField(auto_now=True) this the code I have now but now I can't choose wether to upload just 1 image or 3. is there a way to have sometimes only one imagefield and sometimes multiple? -
How to hide/show certain values inside Drop-down for Superuser in Django admin
I have a model with the the below field: Choice_options=( ('Open',Open'), ('Pending','Pending'), ('Re-verify','Re-verify'), ('Approved',Approved'), ('Cancelled',Cancelled'), ) class Sample(models,model): Choice=models.Charfield(Max_length=50,default='Open',choices=Choice_options) When the superuser log in to this admin page, he should see only the following options in the choice field: ("Approved","Cancelled", Re-verify") Thanks in advance, -
.getlist() is not returning anything in django / html form checkbox input
I have a 2 forms within my list view for a model. The first one is a search bar which works fine with GET and the next is to select items displayed and collect them to edit. I haven't gotten to the editing because I cannot get a list of the selected objects. View.py @login_required def ex_list(request): context = {} if request.GET: #code for search bar if request.POST: selected_values = request.POST.getlist('exlist') print(selected_values) return render( request, 'ex/list.html', context ) List.html <form method="POST" action=""> {% csrf_token %} <table id="exs" class="table table-hover table-striped"> <tbody> {% for ex in exs %} <tr> <td> <center><input type="checkbox" name="exlist" value="{{ex.esid}}"/></center> </td> {% endfor %} <input type="submit" class="btn btn-primary" value="Edit Selected Items" name="edit"> </form> Although I have print(selected_values), all that is being returned is empty brackets {}. I at least know that we are getting inside of the if statement. -
Delete or modify an item in database
#this_examples_are_from_laravel but it can be helpful in other frameworks I noticed that a lot of codes contains something like this : Res=Post::where('id', $request->id)->delete(); Which I don't think it's a good practice with a simple reason is that the user can inject any "id" into your request and delete maybe someone else's post . -
Django concurrency issues/race condition when multiple requests require access to the same object?
My application sends out review requests to multiple users and should cancel (obsolete) all other related requests when one user accepts one of the related requests. Here is what the model looks like: class ReviewRequest(models.Model): class Status(models.IntegerChoices): DISPATCHED = 0 ACCEPTED = 1 REJECTED = 2 CANCELLED = 3 COMPLETED = 4 OBSOLETED = 5 #TODO: expired? version = models.ForeignKey(Version, models.SET_NULL, null=True) reader = models.ForeignKey(Reader, models.SET_NULL, null=True) status = models.IntegerField(choices=Status.choices, default=Status.DISPATCHED) rating = models.FloatField(null=True, blank=True) reqs_to_obsolete = models.ManyToManyField('self') #TODO: look into race condition here Suppose two readers accept review requests req1 and req2 at the same time in two different threads A and B. This is something I anticipated can happen: A: sees req1.status is DISPATCHED A: sees all req1.reqs_to_obsolete have status DISPATCHED B: sees req2.status is DISPATCHED B: sees all req2.reqs_to_obsolete have status DISPATCHED A: req1.status set to ACCEPTED B: req2.status set to ACCEPTED At this point both threads would end up marking the other review request as OBSOLETE, meaning neither party would be able to complete the request. Is this actually possible as I've identified? From what I understand, Django handles request in multiple threads, so I can imagine I might need to get a lock on all … -
How to perform Search functionality in flutter with rest api and Search Delegate?
I am trying to achieve a search view like what we have on youtube. With search delegate in flutter, I could only achieve a search with hardcoded data. But I could not do the same with the Rest API. I have created a Rest API with Django rest framework. Django rest Framework Search API: class SearchApi(generics.ListAPIView): queryset = Youtube.objects.all() serializer_class = YoutubeSerializer filter_backends = [filters.SearchFilter] search_fields = ['title', 'description'] Search Delegate in Flutter class DataSearch extends SearchDelegate<String> { final cities = [ 'Chennai', 'Mumbai', 'Jaipur', 'Visa', 'America', 'Japan', 'North India', 'Tamil Nadu' ]; final recentCities = [ 'America', 'Japan', 'North India', 'Tamil Nadu' ]; @override List<Widget> buildActions(BuildContext context) { // TODO: implement buildActions return [IconButton(icon: Icon(Icons.clear),onPressed: (){ query = ''; },)]; throw UnimplementedError(); } @override Widget buildLeading(BuildContext context) { // TODO: implement buildLeading return IconButton( icon: AnimatedIcon( icon: AnimatedIcons.menu_arrow, progress: transitionAnimation, ), onPressed: (){ close(context, null); }, ); throw UnimplementedError(); } @override Widget buildResults(BuildContext context) { // TODO: implement buildResults print(query); List<Youtube> list = List(); List<dynamic> youtubeList = List(); var isLoading = false; return Column( children: [ Text('Hello') ], ); throw UnimplementedError(); } @override Widget buildSuggestions(BuildContext context) { // TODO: implement buildSuggestions return Column( children: [ Text('Hello') ], ); throw … -
object is not iterable error on Django error on view
I'm new on Django and its a test project this isthe content on views.py def empleado(request, empleado_id): empleados = Empleado.objects.get(pk=empleado_id) context = { 'titulo':'Detalle de empleados', 'lista_empleados': empleados } return render(request, 'empleados.html', context) the model class Empleado(models.Model): departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE) habilidades = models.ManyToManyField(Habilidad) nombre = models.CharField(max_length=40) fecha_nacimiento = models.DateField() antiguedad = models.IntegerField(default=0) the template {% extends 'base.html' %} {% block contenido %} <table> <tr> {% for empleado in lista_empleados %} <td>ID</td> <td>empleado.id</td> <td>Nombre</td> <td>empleado.nombre</td> <td>Antiguedad</td> <td>empleado.antiguedad</td> {% endfor %} </tr> </table> {% endblock contenido %} the table content I don't know why this is the empleados variable content,there is only one element <Empleado: nombre = Uno_de_prueba, fecha de nacimiento = 2020-06-01, antiguedad = 1> An when I call the url I get this error: Exception Type: TypeError Exception Value: 'Empleado' object is not iterable I'm not getting the table content in the correct way?First time I use django I don't know what its the problem