Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use checkboxes with custom Django form
I'm trying to get Checkboxes to work with my custom form but experiencing some issues. A similar approach using Select inputs works fine, thought it would be similar. By doing {{ form.answer }} I get it to render in my template, but nothing is being saved once I press submit. The column is an integer field since I want to store values between 1-5, and not just true or false answer = models.IntegerField(default=None, null=False) Worth mentioning is that this particular column will store only one value, so the MultipleChoiceField() might be misleading. Will need to change that to the correct one whichever that is later on. My form class EditProfile(UserChangeForm): USER_OPTIONS = ( ('1', 'apple'), ('2', 'banana'), ('3', 'orange'), ('4', 'pear'), ) answer = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=USER_OPTIONS) class Meta: model = Person fields = ( 'answer', ) exclude = ( 'password', ) Any clues or feedback would be appreciated! -
Creating drop down menu in html and css (strange error)
Before you read: please do not judge me on every little thing. I am a beginner to this sort of thing and I am just trying to get some practice. Only comment my mistakes if they are either relevant to the conversation or truly helpful. I've looked over and over at my code and stackoverflow answers but nothing has what I need. I want to create a dropdown menu (you hover on a button and multiple links appear in a vertical line below it). I have been having trouble because the links are horizontal instead of vertical when I hover. I have no idea why. I thought this may be because the display style on my nav bar is set to inline, but I used id's in my css, so that should override the navbar classes. I'm very confused. Someone please help. Here is the relevant code (yes, I am using django): <style> #dropdown {display: none;position: relative;background-color: #dde000; padding: 0px;z-index: 1; left: 970px; top:45px;} #drop:hover #dropdown {display:block;} div.navbar {border: 2px outset gray; position: relative; margin-left:-21px; height:45px; background: #dddddd; margin-top:-6px; left: 15px;} .navbar a {height: 23px; display:inline; text-decoration: none; color: black; padding: 10px; float: left; background: #dddddd; padding-top:12px;} .navbar a:hover {background: … -
Django Storages [file upload to was s3]
I am using django storages library for upload my files to s3. I want to understand how this file uploads works , does the file uploads to s3 folder directly or it uploads to my server and then goes to s3? How does the file upload works in django storages. If I upload multiple files , will they use bandwidth of my server of will they be directly uploaded to s3 and will not slow the speed of my server. Thank you -
Populating django model with objects from other model
I'm new to django, but working on an app for a volunteer sailing organization in my local area. Not sure how to ask this question since it's fairly general but I want the following to happen based on two models; Yacht class (boat name, skipper, color, etc.) Race_Event class (event date, time results for each boat) Step 1: The user will need to create a Race_Event each week. I want the boats from the Yacht model to be loaded into the Race_Event. Step 2: The user will enter race times for each boat. Is there a way to pre-load objects from one model into another? With a ForeignKey the user has to add the boats each time. Any direction for me to research would be helpful. Thanks -
how do I save properly manytomany field in django?
I am trying to save an m2m field where my JSON takes an array where of tactics where it should store n times tactics appear in the list, but how can I do this properly? in my following case, it should be stored two times since the technique is shared in two tactics, but how do I achieve the following? for technique in src_techniques: for data_technique in technique: techniques = { technique_id = data_technique['technique_id'] technique_name = data_technique['technique_name'] tactics = data_technique['tactics'] } Technique.objects.get_or_create(**techniques) src_techniques [{"id":1,"source_name":"mitre-attack","tactic_id":"TA0009","tactic_url":"https://attack.mitre.org/tactics/TA0009","tactic_name":"Collection"}] src_techniques [{'technique_id': 'T1548', 'technique': 'Abuse Elevation Control Mechanism', 'url': 'https://attack.mitre.org/techniques/T1548', 'tactic': ['Collection', 'Defense Evasion']}] models class Technique(models.Model): technique_id = models.CharField(max_length=10) technique_name = models.CharField(max_length=40) tactics = models.ManyToManyField(Tactic, blank=True, null=True) class Tactic(models.Model): tactic_name = models.CharField(max_length=100) -
Trying to load data into databse through web browser: save() prohibited to prevent data loss due to unsaved related object 'ship'
I'm at a total loss as to why I get this error. When I run similar code in the python shell I never get this error but when I try to do this through the web browser I get this error. Any idea why this happens? FYI, I'm a total beginner. Models: from django.contrib.auth.models import User class Hull (models.Model): hull = models.CharField(max_length = 33, ) def __str__(self): return self.hull class Hull_Spec(models.Model): ship = models.ForeignKey(Hull, on_delete=models.CASCADE) speed = models.FloatField() depth = models.FloatField() remarks = models.CharField(max_length =300) def __str__(self): return self.remarks views def new_ship (response): x = Hull x.objects.create(hull = response.POST.get('ship')) Z = Hull(hull = response.POST.get('ship')) Z.hull_spec_set.create(speed = response.POST.get('speed'), depth = response.POST.get('depth'), remarks = response.POST.get('remarks')).save() return HttpResponse('Success') html user interface <div> <form action = '/new_ship/' method = 'POST'> {% csrf_token %} <table> <col> <tr> <td><input type = 'text' name = 'ship'>Hull</input></td> <td><input type = 'text' name = 'speed'>Speed</input></td> </tr> <tr> <td><input type = 'text' name = 'depth'>Depth</input></td> <td><input type = 'text' name = 'remarks'>Remarks</input></td> </tr> <tr> <td><input type="submit" value="Submit Fields" id = 'button_1'></td> </tr> </col> </table> </form> </div> -
Django - User can upload an image, but the image does not display - HTML issue? (Beginner help)
I'm new to Django and creating a way for users to upload an image onto a post. Then the image should be visible on each individual post's page. So far in my 'create' function users can successfully create a post and upload a photo. The photo is uploaded into my project but it is still not displaying at all. Any help is greatly appreciated. I think the issue is how the class in views.py, and the html in index.html is written. Just not sure how to fix. views.py to create the post: def create(request): if request.method == 'GET': context = { 'form': CreateForm(), 'form1': CategoryForm(), 'img_form': ImgForm(), } return render(request, "auctions/create.html", context) else: form = CreateForm(request.POST, request.FILES) form1 = CategoryForm(request.POST, request.FILES) img_form = ImgForm(request.POST, request.FILES) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] starting_bid = form.cleaned_data['starting_bid'] if form1.is_valid(): category = form1.cleaned_data['category'] if img_form.is_valid(): image = img_form.cleaned_data['image'] auctionCreated = Listings.objects.create( title=title, description=description, starting_bid=starting_bid, ) categoryCreated = Categories.objects.create( category=category, ) ImageCreated = Img.objects.create( image=image, ) return redirect('index') views.py - this should show a list of each post (on the homepage) and each image should be visible but the image is not appearing: def index(request): items = Listings.objects.all() images = Img.objects.all() return render(request, … -
How to improve the structure of my django project?
Oops good night, recently I started studying django and I came across the problem of structuring the project. Using the codes as an example (suppose you have 1 billion business rules there), I rewrote the user model (user, works perfectly), created a custom manager custom queryset, views (which already comes in startapp) and created a service (another name for "put the business rule"). And my doubts are: 1 ° - Is this basic structure correct? 2 ° - What could I change to further improve the structure of the project? 3 - What is the best way to call my services? static method, instance or class method? 4 - Is it better to put the services of each application in class or to separate everything into functions? 5 ° - If I have a function call from a service view and this function calls another internal function, is it better to instantiate a class to be able to call the functions with the self or to position the function above the other to be able to call? models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db.models import Q from .manager import UserManager class User(AbstractBaseUser): REQUIRED_FIELDS = ['name', … -
Can I use a custom Django manager on a given set of objects?
I have some queryset logic that I would be happy to have in a Manager. I already have the objects in an existing queryset, and I would just like to reorder them. I am thinking of doing something like this: class WorkdayManager(Manager): def ordered_by_time_available(self, object_set): results = object_set.annotate( remaining=F('duration') - F(Coalesce((Sum('record__minutes_planned'), 0)))) return results.order_by(['-remaining']) And I would like to use it like this: object_set.ordered_by_time_available() Would this work? Or should I be using something different? -
django JSONField doesn't accept value
I add a JSONField for one of my models. I want to create an instance of that model in admin panel but that JSONField returns a validation error (Enter a valid JSON.) how I can fix this?? model: class Product(models.Model): category = models.ManyToManyField(Category, related_name='products') name = models.CharField(max_length=500) slug = models.SlugField(max_length=500, allow_unicode=True, unique=True) image_1 = models.ImageField(upload_to='products_pic/%Y/%m/%d/', null=True, blank=True) description = models.TextField(null=True, blank=True) attribute = models.JSONField(default={}) price = models.PositiveIntegerField() discount = models.PositiveIntegerField(null=True, blank=True) available = models.BooleanField(default=True) popular = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) class Meta: ordering = ('-created',) def __str__(self): return self.name I add products in admin panel this is the error: -
Django annotate field in different model for union
I'm trying to do a union for two tables: from django.db import models class Base(models.Model): id = models.BigAutoField() created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class A(Base): ... class B(models.Model): id = models.BigAutoField() title = models.CharField(max_length=255) class C(Base): parent = models.ForeignKey(B, on_delete=CASCADE) And I want to do a union on models A and C while grabbing the attributes of model B: _values = ["id", "parent_id", "parent__title"] A.objects.annotate(parent_id=models.Value(-1, output_field=models.BigIntegerField()), models.Value("", output_field=models.CharField()) ).values(*_values).union(B.objects.values(*_values)).order_by("-created")[:5] But in Postgres 12, Python 3.8, Django 3.1.3, I'm getting this error: django.db.utils.ProgrammingError: UNION types character varying and bigint cannot be matched If you'd like me to get the SQL statement for this, I'd be happy to use Django's SQL compiler to do so. The above was just a demonstration. -
How to create a rating user django
this is the question. I have a mini blog and user profiles. On the user profiles page, I display information: Comments count of this user; Posts count of this user; I display the number of comments in the template userprofile like this: {{comments.count}} I would like to make a small rating system, for example: If a user has left 10 comments and 10 posts - he is a cat. If 20 is a dog. 30 - elephant, etc. For this I would like to have a separate table in the database, so that I can then make a selection by users rating. How can I implement this? Help me pls -
Cannot connect to local database in SQL Server with django 3.1.4
I'm trying to connect to local database with django and I've got this error: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') My connection string is: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '127.0.0.1\MSSQLSERVER', 'NAME': 'RTLLTR', 'USER': '', 'PASSWORD': '', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, -
Django ORM Select Column From Two Model or More
I want select column with django orm from two model or more. SELECT nim, k.kode, s.nama, sks, nilai, th_ajaran FROM mahasiswa_khs k, mata_kuliah_si s WHERE k.kode = s.kode AND nim = %s This is my code khs = Khs.objects.filter(nim=nim).values_list('kode').union(SI.objects.all().values_list('kode')) But, went I call in template it's didn't show -
HOST_NAME is 127.0.0.1 (gunicorn via Apache)
I managed to get gunicorn running behind Apache: <Location /foo/> ProxyPass unix:/run/gunicorn-foo.sock|http://127.0.0.1/ ProxyPassReverse unix:/run/gunicorn-foo.sock|http://127.0.0.1/ </Location> Everything works, except ALLOWED_HOSTS checking. The HTTP_HOST is always 127.0.0.1 How to pass the HTTP_HOST to gunicorn? Apache/2.4.46 (Debian) BTW: I would prefer Nginx, but that's not possible in this case. -
Django qyery to join data from two models without primary or forign key
I'm lerning Django, so farso good, however i stuck with get_query(self) function. I have two models in django no forign in tables: class Airport(models.Model): ID = models.AutoField() Name = models.CharField() City = models.CharField() ICAO = models.CharField() class Airport_Frequency(models.Model): ICAO = models.CharField()) ATC_Type = models.CharField() Frequency_MHz = models.DecimalField() Now I want to create a listview but i want to join tables field Airport.name and Airport_Frequency.ICAO to show in frequency list - sql statement: SELECT DISTINCT a.ICAO, b.ICAO, b.Name FROM airport as b, airport_frequency as a WHERE a.ICAO = b.ICAO View: class Airport_FrequencyListView(ListView): model = Airport_Frequency How to refer in the Airport_FrequencyListViewview above to another model? -
<ul class="errorlist"><li>eauthor<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
I am building a CRUD app on Django. I can create, read, and delete just fine, but the update function does not work. I have edited the views.py file (it was a template) to print the error. Here are the relevant pieces of my code: #models.py from django.db import models class Item(models.Model): id = models.AutoField(primary_key=True) etype = models.CharField(max_length=100) etitle = models.CharField(max_length=100) eauthor = models.CharField(max_length=100) estatus = models.CharField(max_length=20) class Meta: db_table = "Item" #views.py ... def edit(request, id): item = Item.objects.get(id=id) return render(request,'edit.html', {'item':item}) def update(request, id): item = Item.objects.get(id=id) form = ItemForm(request.POST, instance = item) print(form.errors) if form.is_valid(): try: form.save() except Exception as e: print(e) return redirect("/items/show") return render(request, 'edit.html', {'item': item}) ... I guess the problem has to be in edit.html file, but I cannot figure it out. #edit.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Index</title> {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"/> </head> <body> <form method="POST" class="post-form" action="http://127.0.0.1:8000/items/update/{{item.id}}"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Update Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Type:</label> <div class="col-sm-4"> <input type="text" name="etype" id="id_etype" required maxlength="100" value="{{ item.etype }}" /> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Title:</label> <div class="col-sm-4"> … -
adding a django format to messages
i am trying to add to my messages.success the username so when he login the message go up and have the username views.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: l_login(request, user) success_url = '/home' messages.success(request, 'You logged in to ') return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html',{}) -
grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself
Hello everyone I am getting the below error. Does anyone know how to fix it npm WARN grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself. When I did Npm INstall I got the below error added 1608 packages from 1128 contributors and audited 1615 packages in 75.474s 61 packages are looking for funding run `npm fund` for details found 3 vulnerabilities (1 low, 1 moderate, 1 high) run `npm audit fix` to fix them, or `npm audit` for details So I did npm audit fix 62 packages are looking for funding run `npm fund` for details fixed 0 of 3 vulnerabilities in 1674 scanned packages 3 vulnerabilities required manual review and could not be updated In the npm WARN. I get the below errors npm WARN grunt-contrib-uglify@0.2.7 requires a peer of grunt@~0.4.0 but none is installed. You must install peer dependencies yourself. Cab Anyone help me fix this. please advise -
'RequestSite' object has no attribute 'root_page'
I have an issue where trying to set up wagtail with nginx and gunicorn. Running the django server on a gunicorn socket fails and get a 502 error at 'website.com/'. but when I execute manage.py runserver on localhost I get 'RequestSite' object has no attribute 'root_page' at 'website.com/local' My settings are below. What am I doing wrong? NGINX upstream app_server { server unix:/etc/systemd/system/gunicorn.sock fail_timeout=0; } server { listen 80; server_name mywebsite.com; keepalive_timeout 5; location /static/ { alias /home/user/static/; } location /media/ { alias /home/user/media/; } location /local/ { include proxy_params; proxy_pass http://localhost:8000; } location / { include proxy_params; proxy_pass http://app_server; } } GUNICORN [Unit] Description=gunicorn Requires=gunicorn.socket After=network.target [Service] Type=simple PIDFile=/run/gunicorn.pid User=user Group=user EnvironmentFile={{etcdir}}/gunicorn.env WorkingDirectory={{projdir}}/ ExecStart={{projdir}}/venv/bin/gunicorn --config {{etcdir}}/gunicorn.conf.py --chdir /home/user/project project.wsgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target gunicorn.conf.py workers = 2 pythonpath = '/home/user/venv/bin/python3' syslog = True bind = ['unix:/etc/systemd/system/gunicorn.sock','127.0.0.1:8000',] umask = 0 loglevel = "info" user = "user" group = "user" PRODUCTION.PY DEBUG = False ALLOWED_HOSTS = ['*',] SITE_ID = 1 SECRET_KEY = os.environ['SECRET_KEY'] MEDIA_ROOT = "/home/user/media" STATIC_ROOT = '/home/user/static' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Headstart to python Django for freshers
I am a fresher graduated in 2016 from affiliated anna university college. I have basic knowledge on web development including javascript, html, css. I am learning python and python django at the moment. Need suggestion on how to start with Python Django. -
ModuleNotFoundError: No module named 'learning_logs/urls'
I'm learning python, I'm reading a book called python crash course and I'm stuck somewhere, it gives this error: ModuleNotFoundError: No module named 'learning_logs/urls' this is my main url file and in the learning_log/url I have the following: I saw many people complaining about the problem but I couldn't find a solution! -
create validator with objects in django
i want to create a validator in a model and get every same name in that model. my try: def unique_value(objects): def innerfn(value): for title in objects.all(): if title == value: raise ValidationError("This title already exists") return innerfn my model: class Tag(models.Model): name = models.CharField(max_length=100, verbose_name="tag name:", validators=[unique_value(objects)]) the error (on the makemigrations): NameError: name 'objects' is not defined I can not use unique = True because it mixes with my other models and raise error with other model -
Reuse the django form request
I have a page that displays a report according to the informed criteria, within that same page I would like to create a "send by email" button, how could I do to take advantage of the same request? -
Django lookup_expr for arrayfield not matching exact string
I have a djago array field, names = ArrayField( CICharField(max_length=255), blank=True, null=True, help_text="Additional names of the person.", ) It has names, "names": [ "Adam Bender", "April Watkins", "Daniel Brooks", "George Booker" ] When I do, names = django_filters.CharFilter(lookup_expr="icontains") and search for "Adam Bender" it matches the record. But when I search for "Adam Bend" then also it is matching. I don't want that to happened. It should match exact name. I tried iexact but it did not work. Please advise.