Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Pulp Optimisation AttributeError: 'str' object has no attribute 'hash'
I am writing a script for pulp Optimisation to engage with my Django database. The problem contains a few thousand variables to be optimised and several hundred constraints which vary depending upon the values of a,b,c. var_names[] var_values{} for _foo_ in list_1: for _bar_ in list_2: for _var_ in list_3: for _eet_ list_4: var_name = str(_foo_)+str(_bar_)+str(_var_)+str(_eet_) var_names.append(var_name) exec(str(_foo_)+str(_bar_)+str(_var_)+str(_eet_) + "= LpVariable("str(_foo_)+str(_bar_)+str(_var_)+str(_eet_)+", lowBound=0, cat='Integer')") var_value = DataBase.objects.get(column_A = str(_foo_)+str(_var_)).value var_values.append(var_value) obj_func = LpAffineExpression([var_names[i],var_values[i] for in in range(len(var_names))]) problem = LpProblem(name="name", sense=LpMinimise) #Example of constraints exec("problem += (" + str(function(a1,b1,c1)_) +str(function(a1,b1,c2)) +" >= Database_2.objects.get(column_A = z1).value") problem += obj_func problem.sovle() The code works in jupyter notebook when I load the database info as a dataframe. However, I keep receiving this following error code when using in Djagno: File "/path/to/files/prob.py", line 1610, in <module> problem.solve() File "/path/to/files/lib/python3.9/site-packages/pulp/pulp.py", line 1913, in solve status = solver.actualSolve(self, **kwargs) File "/path/to/files/lib/python3.9/site-packages/pulp/apis/coin_api.py", line 137, in actualSolve return self.solve_CBC(lp, **kwargs) File "/path/to/files/lib/python3.9/site-packages/pulp/apis/coin_api.py", line 153, in solve_CBC vs, variablesNames, constraintsNames, objectiveName = lp.writeMPS( File "/path/to/files/lib/python3.9/site-packages/pulp/pulp.py", line 1782, in writeMPS return mpslp.writeMPS(self, filename, mpsSense=mpsSense, rename=rename, mip=mip) File "/path/to/files/lib/python3.9/site-packages/pulp/mps_lp.py", line 204, in writeMPS constrNames, varNames, cobj.name = LpProblem.normalisedNames() File "/path/to/files/lib/python3.9/site-packages/pulp/pulp.py", line 1546, in normalisedNames _variables = self.variables() File "/path/to/files/lib/python3.9/site-packages/pulp/pulp.py", line 1624, in … -
Can I host my Django website to Godaddy domain?
I have Standard Plan in GoDaddy and want to host my Django website, can I do that without an up plan? -
How to customize the superuser creation in Django when using a proper User model?
I have the following models defined on my user's app: class Address(models.Model): tower = models.SmallIntegerField() floor = models.SmallIntegerField() door = models.CharField(max_length=5) class User(AbstractUser): address = models.OneToOneField(Address, on_delete=models.CASCADE) REQUIRED_FIELDS = ["email", "address"] That is, I'm extending the Django's base User object, by adding a one to one field to a table which handles the address for each user. But taking this approach, then when I try to create a superuser account from CLI, with python manage.py createsuperuser, the following happens: Username: admin Email address: admin@admin.com Address (Address.id): 1 Error: address instance with id 1 does not exist. So Django is requesting me to enter an address id but as no address is yet stored in the database, that error is raised. Is there any way to create a superuser by entering both fields from User model and from Address model, and creating a record in both tables? That is, something like: Username: admin Email address: admin@admin.com Tower: 1 Floor: 12 Door: A -
Can't access app running in docker container exposed on port 1337 because of firewall
I have my app running on port 1337 on a cloud VPS server. This app is accessible when I disable firewall by running the command ufw disable. But once I enable it, any attempt to connecting results in timeout. The same goes for port 5050. I have not seen anything weird with my setup. It seems to be the same as every other django deployment docker flow. I'm hosting the apps on a rather unpopular VPS provider mvps. I have allowed the ports 1337/tcp and 5050/tcp also on their page. These are my firewall rules by running ufw status verbose: Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), deny (routed) New profiles: skip To Action From -- ------ ---- 22/tcp ALLOW IN Anywhere 5050/tcp ALLOW IN Anywhere 1337/tcp ALLOW IN Anywhere 80/tcp ALLOW IN Anywhere 443/tcp ALLOW IN Anywhere 22/tcp (v6) ALLOW IN Anywhere (v6) 1337/tcp (v6) ALLOW IN Anywhere (v6) 5050/tcp (v6) ALLOW IN Anywhere (v6) 80/tcp (v6) ALLOW IN Anywhere (v6) 443/tcp (v6) ALLOW IN Anywhere (v6) This docker-compose file: version: '3.9' services: app: image: someimage:prod.1.1 expose: - 8000 env_file: - ./.env.prod restart: always links: - db depends_on: - db volumes: - media:/media - static:/static nginx: … -
How to combine forms for models with related objects?
I'm writing a program to store analyses for patient and I need to make a form with nested forests with next scheme Each patient has an analyses results sheet Each result sheet has date, patient (foreign key) and set of analyses values Each set of analyses values has strict number and strict types of analyses Each type of analyse has it's value, name and units For example I want to create John's analyse result sheet for blood Patient: John Date: 10.02.23 Set of values: 'Blood analysis' Red blood cells: 3,23 10^9 Haemoglobin: 124 g/l I've made models: analysis/models.py class AnalysisGroup(models.Model): name = models.CharField(max_length=64) class AnalysisType(models.Model): name = models.CharField(max_length=256) measurement = models.CharField(max_length=10) analysis_group = models.ForeignKey(AnalysisGroup, on_delete=models.CASCADE) class PatientAnalysisResultSheet(models.Model): an_number = models.PositiveBigIntegerField() date = models.DateField() time = models.TimeField() patient = models.ForeignKey('patient.Patient', on_delete=models.CASCADE) analyzes_group = models.ForeignKey(AnalysisGroup, on_delete=models.CASCADE) class PatientAnalysis(models.Model): analysis = models.ForeignKey(AnalysisType, on_delete=models.CASCADE) value = models.FloatField() patient/models.py: class Patient(models.Model): hist_number = models.IntegerField(unique=True) last_name = models.CharField(max_length=32) first_name = models.CharField(max_length=32) def get_absolute_url(self): return reverse('patient:patient-detail', kwargs={'pk': self.pk}) Now how can I make a form to have an opportunity go on patients page and then add an group of analyses (blood analysis) at once? -
Not showing bio tag in Django?
I'm working on a blog page, and I'm creating page about authors but it doesn't work to load bio (short description). I don't know why it wasn't working, please see code below: this is author_detail.html <p>Bio: {{ author.bio }}</p> this is views.py def author_detail(request, slug): user = User.objects.get(username=slug) author = Author.objects.get(user=user) posts = Post.objects.filter(author=user) return render(request, 'author_detail.html', {'author': user, 'posts': posts}) this is models.py class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, default='', help_text='Enter a short description about yourself.') slug = models.SlugField(unique=True) def save(self, *args, **kwargs): if not self.slug: self.slug = self.user.username.lower().replace(' ', '-') super().save(*args, **kwargs) if not self.bio: self.bio = "This author hasn't added a bio yet." def __str__(self): return self.user.username if I add print('author.bio') it gives me in the terminal the bio, but I don't know why it doesn't show up in (html) page... Any idea? Thanks in advance! -
Filter in Django doesn't show results despite the right link
My program correctly shows the list of meanings in checkbox from all items. And when I choose option in checkbox and press a button, I have, for instance, the result: http://127.0.0.1:8000/measure_list/?measure=thing1 But my page continues to show the whole list of objects. How to fix it? Urls.py path('measure_list/', MeasureView.as_view(), name='measure_list'), path('measure_list/filter/', MeasureView.as_view(), name='filter'), Measure_list.html <form> <div> <h3>Choose:</h3> <ul> {% for measure in view.get_measure %} <li> <input type="checkbox" class="checked" name="measure" value="{{ measure.income }}"> <span class="span editContent">{{ measure.income }}</span> </li> {% endfor %} </ul> </div> <button type="submit">Find</button> </form> <div> <h3>List:</h3> {% for measure in object_list %} <div> <p>Name: {{ measure.name }}, income: {{ measure.income }}</p> </div> {% endfor %} </div> Views.py class FilterList: def get_measure(self): return Measure.objects.values("income").distinct() class MeasureView(FilterList, ListView): model = Measure template_name = 'measure_list.html' Not all questions benefit from including code, but if your problem is better understood with code you’ve written, you should include a minimal, reproducible example. -
how can i get date of each weekdays for this week on python?
Lets explain it by giving a example: Lets say im going to create a shopping website, and i want to show statics of the items sold for this week. like: Sunday - 10 products sold Saturday - 14 products sold Monday - 2 products sold .... total: 100 products sold. and the framework i am using (Django) requires datetime.date format for getting an item in specified date. I researched alot about it, but i just found codes that find which day of week is a date, that doesnt help me or i dont know how to fix it. -
How to make this code working django url path
My code is not working, and I am not sure why. I have the problem with hours_ahead function. -
Django compressor throws "isn't accessible via COMPRESS_URL" when scss used in <link...>
I'm using "Django Compressor" to convert my SCSS files to css files and load them in my project. Everything works fine until I try to use "variables" passed to the template from "views.py" in <link...> elements: {% compress css %} <link type="text/x-scss" href="static/myApp/{{variable}}.scss" rel="stylesheet" media="screen"> {% endcompress %} Django throws the error: static/myApp/[variable value].scss' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed I tried to read through solutions for similar problems here: Django-Compressor won't work in offline mode with custom S3 domain and here: UncompressableFileError: 'scripts/app.js' isn't accessible via COMPRESS_URL ('http://my-bucket.s3-us-west-2.amazonaws.com/') and can't be compressed What is the solution to this? -
How do I fix this issue while trying to deploy a heroku django app?
I am following a book called Django for beginners, and in their section for deploying to heroku, i am getting an error while trying to deploy. The project is working fine, and the website can be viewed. I have followed everything that was said and all the commands were working. I installed gunicorn, added a procfile, updated allowed_hosts, and then for deploying to heroku, i used git init and committed my changes. I logged into heroku, used the create command, then disabled collection of static pages. Everything was working fine, however when I ran git push heroku main There is also only one branch, which is main instead of master on github. Then, when I run the code, I get this error Enumerating objects: 1095, done. Counting objects: 100% (1095/1095), done. Delta compression using up to 4 threads Compressing objects: 100% (1082/1082), done. Writing objects: 100% (1095/1095), 3.18 MiB | 1.92 MiB/s, done. Total 1095 (delta 103), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. … -
How to design Multi-step Multiform for models with few join models in Django
I am trying to design inlinemodelform for multi-child models. However I can't get hold off on what's the best way to design this form. I am designing sample store where a Person/User will purchase cloth where he will go through multi-step form to purchase the cloth. Cloth Type which are offer to Person are Business Wear, Casual Wear,Formal Wear or Sportswear. So when Person will purchase cloth for him/her then he will be asked to go through following steps: Step 1: Select Size or Colour (each of them will be multi select i.e. Size: XS, S, M, L, XL and user can select multipe size) Step 2: Based on Step 1 Selection: Step 2 will display all available choice for Cloths for user to select. Step 3: Person confirm and purhcase the cloth. My Model.py: class Size(models.Model): SIZE = (('xs','Extra Small'), ('s','Small'), ('m','Medium'), ('l', 'Large'), ('xl', 'Extra Large')) size_id = models.AutoField(primary_key=True) size = models.CharField(max_length=10, null=True, choices=SIZE) class Colour(models.Model): COLOUR = (('R','RED'), ('B','BLUE'), ('P','PINK'), ('Y', 'YELLOW')) colour_id = models.AutoField(primary_key=True) colour = models.CharField(max_length=10, null=True, choices=COLOUR) class ClothType(models.Model): type_id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) class Cloth(models.Model): cloth_id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) cloth_type_id = models.ForeignKey(ClothType, on_delete=models.CASCADE) description = models.TextField() class ClothAssignment(models.Model): cloth_assignment_id = … -
Django-allauth redirect straight to google social log in for @login_required decorator
I've set up a django app with allauth and have some views with the @login_required decorator How can I make it so it redirects them straight-away to the google oauth page from this decorator if they are not logged in? Right now it takes user to a sign up page on my domain, then the sign in via google page on my domain, and finally to the google oauth page -
how to use multiple images in django ecommerce
so basically i can explain my query this way that for example when we open amazon.com we open a product we see a primary image (which is the image of the Product) but sidewise we also see seperate images which are of same product but defines different aspects again clearer example : i open a bag in amazon.com it initially shows black color of back but i am a psycho and want a different color and so there are photos of that same product but in different color in same page thats what i am talking about... i need those pics in my project how do i do btw in django only i tried creating a different model but couldnt figure out -
API not working after giving authentication permission
I created an API to list the employees and applied authentication permission. when I tried to load the page it shows a login page. After giving the login credentials it shows a page not found error. Before the authentication the url's was working perfectly. views.py from rest_framework.permissions import IsAdminUser class EmpListView(ListAPIView): queryset = Employee.objects.all() serializer_class = EmpModelSerializer filter_backends = [filters.SearchFilter] search_fields = ['Ename', 'Position'] permission_classes = [IsAdminUser] urls.py urlpatterns = [ path('admin/employee/', EmpListView.as_view(), name='emp-list'),] -
Custom serializer.py failed django.db.utils.IntegrityError: null value in column violates not-null constraint
What i am trying to do - is to save post to the model with custom conditions. But each time im trying to save - i receive this error django.db.utils.IntegrityError: null value in column violates not-null constraint So far, i have tried editting my models, and adding null=True in parameters, but it doesn't see to help. So what is the best way to solve the problem here? serialier.py: class EventSerializers(serializers.ModelSerializer): class Meta: model = Events fields = ["cam_id", "vehicle_plate", "is_recognition", "is_confirmation", "vehicle_plate", "transit_block_time_min"] def save(self, **kwargs): instance = super().save(**kwargs) is_recognition = instance.is_recognition is_confirmation = instance.is_confirmation vehicle_plate = instance.vehicle_plate if CarParkItem.objects.filter(vehicle_plate=vehicle_plate).exists(): instance.event_code = 1008 elif BlackListItem.objects.filter(vehicle_plate=vehicle_plate).exists(): instance.event_code = 1004 elif is_recognition == False: instance.event_code = 1003 elif is_recognition == True and is_confirmation == False: instance.event_code = 1006 elif is_recognition == True and is_confirmation == True: instance.event_code = 1007 instance.save() return instance I have read about different approaches, but editing serializer - looks like standard thing here models that are used for it: class BlackListItem(models.Model): vehicle_plate = models.CharField(max_length=999, db_index=True) valid_until = models.DateTimeField(db_index=True) description = models.CharField(max_length=999) def __str__(self): return self.vehicle_plate class CarParkItem(models.Model): vehicle_plate = models.CharField(max_length=999, db_index=True) valid_until = models.DateTimeField(db_index=True) description = models.CharField(max_length=999) def __str__(self): return self.vehicle_plate class WorkingMode(models.Model): PASSMODE_CHOICES = [ ('pay_by_hour', 'pay_by_hour'), … -
How to add these constraints to Django models?
Help me please. How to make constraints in the database? I am using sqlite, django 3.2, python 3.7 I have three models: Refbook, Versions of refbooks, Elements of refbook from django.db import models class Refbook(models.Model): code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=300) description = models.TextField() class VersionRefbook(models.Model): refbook_id = models.ForeignKey('Refbook', on_delete=models.CASCADE, related_name='versions') version = models.CharField(max_length=50) date = models.DateField() class Meta: unique_together = ('refbook_id', 'version') class Element(models.Model): version_id = models.ManyToManyField('VersionRefbook') code = models.CharField(max_length=100) value = models.CharField(max_length=300) The following constraints must be added to these models: There cannot be more than one Refbook with the same value in the "code" field. There cannot be more than one Version with the same set of values "refbook id" and "version" One Refbook cannot have more than one Version with the same date In one Version of refbook, there cannot be more than one Element of refbook with the same value in the "code" field OK. I solved the first point by adding the «unique=true» parameter to the «code» field in the Refbook class. It seems that I solved the seconf point by adding the «unique_together = ('refbook_id', 'version')» parameter to the Meta class. Third point. I think need to override the save method. But … -
Django: how to access inline fields from parent model form
I am working on a simple quiz application. There will be questions which are either multiple choice or open. From the admin site, I want to be able to add questions along with their related answers, while having the following validation: If a question's type is multiple choice, then it must have 4 possible answers and only of them should be marked as correct. If a questions's type is open then it must have only 1 answer and it must be marked as correct. Here is the relevant part of the Question and Answer models that I have. class Question(models.Model): class QuestionType(models.TextChoices): MULTIPLE_CHOICE = "MC" OPEN = "OP" text = models.CharField(max_length=250) topic = models.ForeignKey(Topic, on_delete=models.PROTECT) class Answer(models.Model): text = models.CharField(max_length=150) is_correct = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE) And here is what I have in admin.py class AnswerInline(admin.TabularInline): model = Answer class QuestionAdmin(admin.ModelAdmin): fields = ["text", "topic", "type", "difficulty"] inlines = [AnswerInline] def clean(self): """ How do I access the is_correct values of the items which are in the AnswerInline instance? """ I dont'know how to access the contents of the inline instance in the parent form(QuestionAdmin). How can I do that? Or perhaps, is there another way to achieve the … -
Why am I getting "Volumes must be mapping" error
Trying to add Django app with a PostgreSQL db to a Docker container. When trying to run "docker-compose build", I am getting a "Volumes must be mapping" error. Not sure what I'm doing wrong as it looks like the : syntax signified a mapping. When I remove the volumes sections entirely the build continues (with or without a Dockerfile reference so I've omitted that part). See docker-compose.yml: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - dev-static-data:/backend/django_static command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme - DEBUG=1 depends_on: - db - redis db: image: postgres:15-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASS=changeme volumes: - dev-db-data: - dev-static-data: Any ideas? -
Celery in production raise ModuleNotFoundError: No module named 'celery'
In developement all is good, app starts without any problems. However, in production, Gunicorn can't start due ModuleNotFoundError: No module named 'celery' Celery is installed properly >>> from celery import Celery >>> print(Celery) <class 'celery.app.base.Celery'> already tried changing file name to anything other than celery.py - did not help Any thoughts? -
setting up database for @shared task using celery django
The application I am working on is a multitenant application. I am using celery to run background tasks. The background tasks that get pushed to Queue (rabbitmq) are getting executed properly when run on the default db setting configured in the settings. But when I submit the background jobs from other tenants, i.e. settings other than default they fail. This is because, in normal sync flow, I am using a custom router that sets the DB to be used based on the request URL( which contains the tenant details). but the same context is lost when the job is submitted as a background task. Any suggestions ? -
Test django template equality with pytest(HTML strings)
Let me know if there is any limitation to the test below? import pytest from html.parser import HTMLParser from django.template import Template, Context # ... def test_render(settings): context = Context() template = Template('{% include 'test.html' %}') assert HTMLParser().feed(template.render(context)) == HTMLParser().feed( '<html><head><title>Testing</title></head> ' '<body><h1>This is a test!</h1></body></html> ' ) I'm using pytest without pytest-django plugin. And I just wanted to check html template equality. -
django admin interface text box size customizing
I want the Charfield box in the admin interface to be larger so that you can see your text more clearly when you write it in. heres my code in models.py from django.db import models from datetime import date # Create your models here. class BlogPost(models.Model): `created_at = models.DateField(default = date.today)` `Title = models.CharField(max_length=100)` `Tag = models.CharField(max_length=100)` `Text = models.CharField(max_length = 1000)` and here is the code in admin.py from django.contrib import admin from .models import BlogPost # Register your models here. admin.site.register(BlogPost) i looked trought the stackoverflow questions and i didnt understand it -
Safari does Preflight Request for same origin
I am currently testing my Web Application with different devices and for most of them everything works as intended. Sadly with my IPhone and Safari i am experiencing a weird issue, that it does a Preflight Options Request, when its the same origin. To my Knowledge this is not required. Sadly the Options fails. When testing with Chrome on the same device everything worked. I also tested Safari on a different Iphone and it worked there. Now the really confusing part is, when clicking on a link to the website in Discord for example with safari it works aswell without doing a Options. I know that in a "perfekt" World the Options should not fail, but that is another struggle when i was deploying the app. Currently frontend runs under https://example.com and the API under https://example.com/api. I am a absolute beginner with CORS and i am quite confused why this error happens. Another problem is that i cant really use devtools on the iphone to have a exact error message. I can only see the Options in the nginx logs and then the missing follow up request. -
How to save subform in parent form django ModelForm?
I have these models, enter image description here enter image description here with the following forms.py enter image description here I am have subform which is Bill form inside Transaction form, upon submission of transaction form, I want my bill form to be saved as well, please advice here is the view im trying enter image description here