Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to iterate through numbers in django
I am new to Django. I just want to build an online resume based on the details given by the user. I have separate HTML files for taking the user input and for displaying the resume. I took the user input for the certification field like this: <div class="box"><input type="text" name="certificate1" placeholder="Certificate-name"> <input type="text" name="institute1" placeholder="Institute-name"></div><br> <div class="box"><input type="text" name="certificate2" placeholder="Certicate-name"> <input type="text" name="institute2" placeholder="Institute-name"></div><br> <div class="box"><input type="text" name="certificate3" placeholder="Certicate-name"> <input type="text" name="institute3" placeholder="Institute-name"></div><br> <div class="box"><input type="text" name="certificate4" placeholder="Certicate-name"> <input type="text" name="institute4" placeholder="Institute-name"></div><br> <div class="box"><input type="text" name="certificate5" placeholder="Certificate-name"> <input type="text" name="institute5" placeholder="Institute-name"></div><br> <div class="box"><input type="text" name="certificate6" placeholder="Certicate-name"> <input type="text" name="institute6" placeholder="Institute-name"></div><br> And the code which I have written in views.py file is this: if(request.method=="POST"): dictionary = {str(i):request.POST[i].capitalize() for i in request.POST} return render(request,"form/resume.html",dictionary) And the code which I have written for displaying certifications in the resume is this: {% if certificate1 %} <li>{{certificate1}}, {{institute1}}</li> {% endif %} {% if certificate2 %} <li>{{certificate2}}, {{institute2}}</li> {% endif %} {% if certificate3 %} <li>{{certificate3}}, {{institute3}}</li> {% endif %} {% if certificate4 %} <li>{{certificate4}}, {{institute4}}</li> {% endif %} {% if certificate5 %} <li>{{certificate5}}, {{institute5}}</li> {% endif %} {% if certificate6 %} <li>{{certificate6}}, {{institute6}}</li> {% endif %} But I feel the code that I have … -
I'm optimizing my django project backend, but I got many problems on "list_display" that contains ForeignKey
django masters all around the world I'm Korean developer and started django 3 months ago. Now I'm just a slave of my company. Anyway, I have problem on optimizing django admin project, but no one has experienced the same problem. This is my models "Project", "Answer", "Request". # ------------------------------------------------------------------ # Model : Project # Description : project model # ------------------------------------------------------------------ class Project(models.Model): class Meta: verbose_name = ' project' verbose_name_plural = ' project' def __str__(self): return str(self.id) # ------------------------------------------------------------------ # Model : Request # Description : Request model # ------------------------------------------------------------------ class Request(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, verbose_name='client') project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name='project') product = models.ForeignKey(Subclass, on_delete=models.CASCADE, verbose_name='product') category = models.ManyToManyField(Develop, verbose_name='category') name = models.CharField('name', max_length=256, blank=True, null=True) price = models.CharField('price', max_length=256, blank=True, null=True) day = models.CharField('duedate', max_length=256, blank=True, null=True) content = RichTextUploadingField('content', null=True) file = models.FileField('file', upload_to=request_update_filename, blank=True, null=True) created_at = models.DateTimeField('created_at', default=time) add_meeting = models.BooleanField('add_meeting', default=False, null=True) examine = models.BooleanField('check examing', default=False, null=True) active_save = models.BooleanField('active-save', default=True, null=True) class Meta: verbose_name = ' request' verbose_name_plural = ' requests' def __str__(self): return str(self.name) class Answer(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, verbose_name="client") project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name="project", null=True) partner = models.ForeignKey(Partner, on_delete=models.CASCADE, verbose_name="partner") class Meta: verbose_name = ' Answer' verbose_name_plural = ' Answer' … -
Setting up cx_Oracle and Oracle 11g for Django, name vs host? Where to put Instant Client?
I'm trying to follow this tutorial to connect django with a legacy oracle database a little confused what to put in the Name. In addition, I'm a little confused how to install the Instant Client so that my django/python application will be able to see the instant client. I'm on Windows 10, django 3.0.1, python 3.7 1.) First of all, when I connect to the database with the enterprise manager, I see this (edited): So when I fill in my django, this is what I put(edited): in the Name, am I suppose to put ServerName (following the enterprise manager image) or do I put servername/schema that I'm trying to connect to? 2.) I contacted the admin, and the Oracle database is 11g, and also in Visual Studio, I connected to the database and checked the version, it is So I download the instant client for 11.2.0.4.0 (32 bit) Unzipped it into C:\instantclient_11_2 Added C:\instantclient_11_2 to my System Environment Variables, in the PATH And tried to run the following And I receive the error: But according to the documentation here, I need to set it to lib_dir, but I'm not sure where the lib_dir variable is? is this an environment variable? … -
Django Channels: Use javascript for making a user notification system
I have a chat app system in my project using django channels, But I am trying to do a New Message Notification system, I already read New chat message notification Django Channels, but that doesnt work for me, my single question is, is new chat message notification can be done with pure javascript, using the socket.onmessage? but sending only to the users that are in the chat? -
Image in Django is no longer showing
So i am doing a project in Django and I had some images upload and they use to be there just fine. I haven´t go in to the project for a couple of weeks as I was busy and today when I wanted to continue I realise that all the images come with the little x sign or broken in another browser. I am not sure why. the code I have for the image is this <h6 style="margin-left: 2.5cm; color: rgba(0, 95, 0, 0.8); ">El Día Que Fleko Se Convirtio En Silver Surfer</h6> <a href="{% url 'Fleko' %}"> <img title="El Día Que Fleko Se Convirtio En Silver Surfer" src="{% static 'TresAcordesApp/img/Fleko.jpg' %}" height="250px" width="300px" style="margin-left: 2.5cm;" alt=""> </a> This was working just fine up to today. it supposed to be an image that you can click and it takes you to a video. you can still click and it will take you to the video but I can see the image. THANK YOU very much. :) -
Problem with request.GET.get('text', 'default'), its not returning the exact inserted value in python while working with Django
I want this command request.GET.get('text', 'default') in the python code below to just simply show whatever the user is typing in the text box that I made in the Template file. But when i'm inserting something in the box its just returning 'default' while it should return whatever I exactly put in the insert box. Back end Python File def analyze(request): # Get the text djtext = request.GET.get('text', 'default') analyzed=djtext params = {'purpose': "Removing Punctuations", 'analyzed_text': analyzed} return render(request,'analyze.html',params) Template file of creating the text box <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Template is working</title> </head> <body> <h1> Welcome to text analyzer. Enter your text below</h1> <!--{{ name }} is me and im a pro cause im from {{ place }}--> <!-- This access the dictionary made in views--> <form action='/analyze' method='get'> <textarea style="margin: 0px; width: 1365px; height: 158px;"> </textarea> <input type='checkbox', name='removepunc'> Remove Punctuations <br> <button type='submit'> Analyze Text</button> </form> </body> </html> Template File of the Result Screen <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Analyzing Your Text...</title> </head> <body> <h1>Your Analyzed Text - {{ purpose }}</h1> <p> {{ analyzed_text }} </p> </body> </html> -
ModuleNotFoundError when importing Django project in external python script
I'm trying to import a Django project (named backend) in a python project to use models in the script. When I try to setup django I got a ModuleNotFoundError. I think because django tries to install the INSTALLED_APPS from the django project but doesn't find them (is this correct?). I have no settings.py file in my python project, is that a problem? so I try: import os, sys, django sys.path.append('/Users/sgerrits/PycharmProjects/') os.environ['DJANGO_SETTINGS_MODULE'] = 'backend.backend.settings.development' django.setup() stacktrace: app_1 | backend.backend.settings.development app_1 | Traceback (most recent call last): app_1 | File "/opt/project/store-handler/app.py", line 11, in <module> app_1 | django.setup() app_1 | File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 19, in setup app_1 | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) app_1 | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ app_1 | self._setup(name) app_1 | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup app_1 | self._wrapped = Settings(settings_module) app_1 | File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ app_1 | mod = importlib.import_module(self.SETTINGS_MODULE) app_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module app_1 | return _bootstrap._gcd_import(name[level:], package, level) app_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import app_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load app_1 | File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked app_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed app_1 | File "<frozen importlib._bootstrap>", … -
Django convert list of string numbers into the integers doesn't work
I have a huge problem with scrap data and convert number string to integer. salary = p.find('div', class_='details-body__content').text a = [] x = re.findall(r'[0-9]+', salary) a.append(x) for i in range(len(a)): a[i] = int(a[i]) print(a) This code isn't working and i dunno why, i tried all options from SOF and from google. -
How to set initial values for Django Model Form
I am trying to set initial values for my django model form but when I try in my views.py: add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'}) It doesn't work. If I specify default values in the model they work fine. Models.py: class contact(models.Model): name = models.CharField(max_length=20, blank=True) email = models.EmailField(primary_key=True) tel = PhoneField(null=True, blank=True) contact_relations = [ ('Supplier', 'Supplier'), ('Customer', 'Customer'), ('Other', 'Other'), ] relation = models.CharField(max_length=50, choices=contact_relations) Forms.py: class newContactForm(forms.ModelForm): class Meta: model = contact fields = [ 'name', 'email', 'tel', 'relation', ] widgets = { 'relation': forms.RadioSelect(), } Views.py: def add_contact_view(request): add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'}) if add_contact_form.is_valid(): add_contact_form.save() else: add_contact_form = newContactForm() context = { "add_contact_form":add_contact_form, } return render(request, 'contacts/new_contact.html', context) -
Concat video output does not skip ahead or go backwards like normal video
i ran this basic concat code to combine an image and audio to output an mp4 video but the output video plays perfectly except for the fact that if I want to skip ahead in the video it goes back to the original position. This was run on python audio = ffmpeg.input("beat.mp3") picture = ffmpeg.input("image.jpg") ffmpeg.concat(picture, audio, v=1, a=1).output("video3.mp4").run() -
Django 3.1 admin page appearance issue
Today I have updated Django to latest version 3.1. But for some reason when the logged in to admin page, all I cans see is a weird looking admin page. admin.py Can someone help me what went wrong or what are things I need to modify to get back to original admin page. Thanks in advance -
Django checkbox form doesn't show up
First of all, sorry for the easy question, I'm new on Django and the divine doc doesn't helped me. The fact is, I'm trying to display a checkbox form on a template but despite having followed django's doc to the letter, it refuses to appear Here is my code : forms.py from django.forms import ModelForm from .models import SoinsSelect class SoinsSelectForm(ModelForm): class Meta: model = SoinsSelect fields = '__all__' models.py from django.db import models class SoinsSelect(models.Model): blabla = models.BooleanField(default=False) views.py from soins.forms import SoinsSelectForm from django.shortcuts import render def CreateSoinsSelect(request): if request.method == 'POST': form = SoinsSelectForm(request.POST or None) if form.is_valid(): form.save() else: form = SoinsSelectForm() return render(request, 'profile.html', {'form': form}) profile.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="{% static "css/profile.css"%}"> </head> <body> <div class="nav-right visible-xs"> <div class="button" id="btn"> <div class="bar top"></div> <div class="bar middle"></div> <div class="bar bottom"></div> </div> </div> <!-- nav-right --> <main> <nav> <div class="nav-right hidden-xs"> <div class="button" id="btn"> <div class="bar top"></div> <div class="bar middle"></div> <div class="bar bottom"></div> </div> </div> <!-- nav-right --> </nav> <a href="https://codepen.io/tonkec/" class="ua" target="_blank"> <i class="fa fa-user"></i> </a> <section> <article> <h4>Hello {{ user.forename }}</h4> <p>Here is you data :</p> <p>Username : {{ user.forename }}</p> <p>name : {{ … -
How to use Vue3 on Django without NodeJs?
On Vue2 I just add the CDN then I have Vue available on my js files, but Vue3 I could not do the same - My js files does not detect Vue. How can I solve it in order to use Vue3? -
Updating Django settings using manage.py command
I am creating a Twitter bot and I have a couple of API Key's that I need to store to access the Twitter API. These API Key's need to be stored somewhere in the web server and, when I was looking at ways to do this, I thought of something else. I went to Django's docs to see how to create a manage.py command and then made one, but now I still haven't found a way to make is change the Django's settings even though I've looked at quite a few websites, the best one was https://code.djangoproject.com/wiki/SplitSettings. I'll probably just make a settings_local.py file and store everything there, but I was wondering if it would be possible to do it with the manage.py command because I think that that would be a useful way to get everything working. Here's my current code from django.core.management.base import BaseCommand, CommandError from django.conf import settings class Command(BaseCommand): help = "Configure the server with developer codes to allow for Twitter API connection." def handle(self, *args, **options): api_key = input("API Key: ") secret_key = input("Secret Key: ") settings.configure(TWITTER_API_KEY=api_key, TWITTER_SECRET_KEY=secret_key) self.stdout.write(self.style.SUCCESS( "Successfully added your Twitter API_KEY and SECRET_KEY")) -
Django - Get First image from Foreign related table in Django 3.1
please I am using Django 3.1 and I am trying to figure out, how to get one image from the foreign table - in home view - there should be cards with all vehicles and only first image for each one - as a thumbnail. Here is my models.py: class Vehicle(models.Model): make = models.ForeignKey(Make, on_delete=models.PROTECT) model = models.ForeignKey(Model, on_delete=models.PROTECT) year = models.PositiveSmallIntegerField() ... def first_image(self): return self.image_set.first() class Image(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT) image = models.ImageField(upload_to='images/') In my template, I am trying to get the first image of a Vehicle by: {% for v in vehicles %} <img src="{{ v.first_image.image.url }}" alt=""> {% endfor %} I have also tried {{ v.first_image.url }} but nothing works. I tried to add a print function to first_image (same as return - self.image_set.first()) and it is getting None, or catalog.Image.None When I am printing all images for one vehicle, it works perfectly via: {% for i in images %} <img src="{{ i.image.url }}" alt=""> {% endfor %} views.py: from django.shortcuts import render from .models import Vehicle, Image def home_view(request): vehicles = Vehicle.objects.all() context = { 'vehicles': vehicles, } print(context) return render(request, 'home.html', context) def vehicle_detail_view(request, slug_make, slug_model, slug_vehicle): vehicle = Vehicle.objects.get( make__slug=slug_make, model__slug=slug_model, slug=slug_vehicle) … -
USE_BULK in django-import-export
how to apply USE_BULK in django-import-export please help me I want your advice about this question How to handle vary big files in django-import-export and can I show progress bar to explain ration of uploaded file and can I make result don't show when upload finish to make save auto and not need for press conform -
Formset inside a ModelForm
So lets try to explain: I have a model called inventory, which serves to handle my products and their quantity. And I have another model that I would ask to do a certain service and would need to inform how many products and their quantity would be needed to complete that same service. My problem is, I am using a ModelForm to render my form, but with this I just can select one product in the field items(that is a foreignkey of Inventory) and can't inform how many items would be needed. So, I'd like something to my user select one or more products from my inventory and inform how many them he will need to complete de service. I read about formset and seems to be what I need, but i can't figure out how to put in my code, or inside of my actually modelForm. inventory models: class Inventory(models.Model): name= models.Charfield(max_lenght=100) description = models.TextField() quantity = models.PositiveIntegerField() ...... service models: class Service(models.Model): name = models.Charfield(max_length=100) items = models.ForeignKey(Inventory, on_delete=models.DO_NOTHING) description = models.TextField() date= models.DateField(default=datetime.date.today) .... views: class CreateServiceView(CreateView): model = Service form_class = ServiceModelForm template_name = 'service/create_service.html' success_url = reverse_lazy('service:list_service') template: {% extends 'base.html' %} {% load bootstrap4 … -
Django QuerySet.update() fails on MySQL if a subquery references the base table
I am trying to make this transaction mysql compatible. As mysql don't allow the current operation. MySQL doesn't allow updating the table you are already using in an inner select as the update criteria. Getting this error django.db.utils.OperationalError: (1093, "You can't specify target table 'catalogue_category' for update in FROM clause") Code: included_in_non_public_subtree = self.__class__.objects.filter( is_public=False, path__rstartswith=OuterRef("path"), depth__lt=OuterRef("depth") ) self.get_descendants_and_self().update( ancestors_are_public=Exists( included_in_non_public_subtree.values("id"), negated=True) ) https://github.com/django-oscar/django-oscar/pull/3050#pullrequestreview-461576714 -
User registration fully not working in Django
I am building a Django app with a sign up form. For this, I am adding additional fields to my model like this: models.py class studentInfo(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name="student") student_id = models.IntegerField(primary_key=True, null=False, validators=[MaxValueValidator(99999), MinValueValidator(10000)]) major = models.CharField(max_length=500,null=True, blank=False, default= '------') And my forms.py class UserReg(UserCreationForm): class Meta: model = User fields = ('username', 'email') class StudentReg(forms.ModelForm): class Meta: model = studentInfo fields = ('student_id', 'phone', 'major', 'eof', 'arc') And here is my views.py (It's definitely incorrect but I want to add it to show what I have tried) def signup(request): print("in view") if request.POST: print("in post") userF = UserReg(request.POST) studF = StudentReg(request.POST) if userF.is_valid(): userF.save() userInst = User.objects.get(username = userF.cleaned_data['username']) print(userInst.username) if studF.is_valid(): studF.save() studInst = studentInfo.objects.get(studentInfo__student_id = studF.cleaned_data['student_id']) studInst.user = userInst studInst.save() return redirect('login') else: print('in the user invalid') print(userF.is_valid()) else: userF = UserReg(request.POST) studF = StudentReg(request.POST) context = {'user':userF, 'student':studF} return render(request,'accounts/signup.html', context) The problem I am running into is Django is creating a user but it isn't creating a student. It's requiring an already existing user to be created in order for the student object to be created. Is there a way to validate both forms and create a user and student when … -
How the functions in Django views are executed?
As far as I know we have to call a function to execute it. and just defining a function does not make it to be executed. The question is how do Django views are being executed? I don't see anywhere that we call them. So how does it work? I'd be grateful if anyone could clarify this to me. -
How can i replace this path ('C:/Program Files/Tesseract-OCR/tesseract.exe') in deployment? So that we find tesseract.exe to run the script
In Django, i give these line in my script to run tesseract.exe( " pytesseract.pytesseract.tesseract_cmd ='C:/Program Files/Tesseract-OCR/tesseract.exe' "). how can i replace this path ('C:/Program Files/Tesseract-OCR/tesseract.exe') in deployment? So that we find tesseract.exe to run the script. Can anyone help me which path leads to tesseract.exe to run the line in my script in production -
Date being updated everytime I make change to a product field in django project
This is my models.py: class Product(models.Model): type= models.ForeignKey(Category, on_delete = models.CASCADE) productid=models.CharField(max_length=30) name=models.CharField(max_length=30) fabric=models.CharField(max_length=30) bcode=models.CharField(max_length=4) Gprice=models.IntegerField(null=True,blank=True) added=models.DateTimeField(auto_now=True) I have also registered this model in admin successfully. But every time I update the price the added(time added) changes. Please help me with this I want to store the time when the product was added for first time and I dont want to change that. -
DRF overflowError: date value out of range trough serializer
Hello when a request is sent with data [{"valid_from": "0001-01-01T00:00:00", "valid_to": "0001-01-01T00:00:00"}] How to limit the min year to 2020, I tried adding validators in the model but DRF executes first, so it is not working, how to stop it on DRF level. If they pass the date.min in my serializer it raises overflowError: date value out of range What should I do? -
I join 3 tables with filter in a query on Django
In another question (join 3 tables queryset Python Django), they have answered what I needed, but the answers have grown and have varied a bit from the question, that is why I ask this new question. I need to add a date filter to the query that I have below. Model.py class DivisionModel(models.Model): id = models.PositiveIntegerField(db_column='Id', primary_key=True) division = models.CharField(db_column='Division', max_length=50) class ZoneModel(models.Model): id = models.AutoField(db_column='Id', primary_key=True) zone = models.CharField(db_column='Zone', max_length=50) division = models.ForeignKey(DivisionModel, on_delete=models.DO_NOTHING, db_column='Division_id') class OrderModel(models.Model): zone = models.ForeignKey(ZonaModel, on_delete=models.DO_NOTHING, db_column='Zone_Id') cctt = models.ForeignKey(CCTTModel, on_delete=models.DO_NOTHING, db_column='CCTT_Id') fservice = models.DateTimeField(db_column='FService') ffinishservice= models.DateTimeField(db_column='FFinishService') class CCTTModel(models.Model): status = models.CharField(db_column='Status', max_length=23) Views.py def post(self, request, format=None): respuesta = GenericResponse() respuesta.result = True orderparams = request.data start_date=pedidoparams.get('str_date') finish_date=pedidoparams.get('fnsh_date') pedidos=DivisionModel.objects.values('division').filter( zonemodel__OrderZone__start_date__lte=start_date).filter( zonemodel__OrderZone__finish_date__gte=finish_date ).annotate( orders=Count('zonemodel__ordermodel__cctt'), ge_on_going=Count('zonemodel__ordermodel__cctt', filter=Q(zonemodel__ordermodel__cctt__status="on going")) ).values('division', 'order', 'ge_on_goin').values('division', 'order', 'ge_on_goin') This query return: { "division": "Spain", "orders": 20736, "ge_on_going": 864 } But the real result is: { "division": "Spain", "orders": 2, "ge_on_going": 0 } If I don't add the filter clause with date, the query works fine and returns all the results there are, but I need to put the filter with date. -
Django updating an instance of a model based on user input from a dropdown menu
I have the following model in Django class Medicine(models.Model): Medicine_Name = models.CharField(max_length=100) User_Associated = models.ForeignKey(User, on_delete=models.CASCADE) Tablets_In_Box = models.IntegerField() Dose_in_mg = models.IntegerField() Dose_Tablets = models.IntegerField() Number_Of_Boxes = models.IntegerField() Last_Collected = models.DateField() def __str__(self): return self.Medicine_Name def get_absolute_url(self): return reverse('tracker-home') I am trying to create a form where a user can update the Number_Of_Boxes and Last_Collected fields of a given medicine which they are associated with. I want a dropdown menu where the user can select one of their medicines, and then update those two fields. I created the following modelform. class CollectionForm(forms.ModelForm): Medicine_Name = forms.ModelChoiceField(queryset=Medicine.objects.all()) class Meta: model = Medicine fields = ['Medicine_Name', 'Number_Of_Boxes', 'Last_Collected'] def __init__(self, user = None, *args, **kwargs): super().__init__(*args, **kwargs) if user: self.fields['Medicine_Name'].queryset=Medicine.objects.filter(User_Associated=user) I have the following view for this form. def update(request, *args, **kwargs): instance = Medicine.objects.get(id=pk) if request.method == 'POST': form = CollectionForm(user=request.user, instance=instance, data=request.POST) if form.is_valid(): instance = form.save(commit=False) instance.User_Associated = request.user instance.save() else: form = CollectionForm() context = {'form': form} return render(request, 'tracker/medicine_collection.html', context ) But I am running into problems with the primary key. The instance of the model which needs updating depends on the user input (i.e. the Medicine_Name) which they will choose from a dropdown menu. I don't understand …