Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelChoiceField in ModelFormSet not selecting initial value when using custom ModelForm
So I am using a ModelFormSet to show a list of forms based on a predefined ModelForm. I need to customize the two fields in the forms, and therefore I have created this ModelForm: # forms.py class StudentRelationshipForm(forms.ModelForm): # the row below causes the issue: classroom = forms.ModelChoiceField(queryset=Classroom.objects.all(), widget=forms.Select(attrs={'class':'form-control border-0 bg-white text-black h5'}), to_field_name='clarsroom_name', disabled=True, required=True) student_type = forms.ChoiceField(choices=StudentRelatuionship.STUDENT_TYPES, widget=forms.Select(attrs={'class': 'form-control'}), required=True) class Meta: model = StudentRelatuionship fields = [ 'classroom', 'student_type', ] I am creating the ModelFormSet in the following view: # views.py .... class MyView(DetailView): def get_context_data(self, **kwargs): classroom_list = [ a list of classrooms goes here ] initial_formset_data = [] for classroom in related_companies: initial_formset_data.append({'classroom': classroom.pk}) StudentRelationshipFormSet = modelformset_factory(StudenrRelatuionship, form=StudentRelatuionshipForm, fields=['classroom', 'student_type'], extra=formset_extras) context['investor_relationships_formset'] = StudentRelationshipFormSet(queryset=StudentRelatuionship.objects.filter(student=self.request.user.user_profile, classroom__in=classroom_list), initial=initial_formset_data) .... Basically the problem that I have is that when I specify the classroom field in StudentRelationshipForm in forms.py, the HTML Select widget's default value becomes ---------. However, if I remove the row from forms.py, the HTML select widget correclty selects the classroom name from the database when editing an existing instance. How could I overcome this? The reason why I need the row is to specify that the field should be disabled. If there is another way to … -
Django + Apache + Ubuntu | ModuleNotFoundError: No module named 'myproject.settings'
I am running a django app on apache using wsgi on an ubuntu 18.04 aws ec2 instance. I have tested the django app on the development server and it works fine. When I run it on apache, it says that there was an error running wsgi.py, no module named myproject.settings. I am guessing this is an issue with how the directory is setup/apache can't get access to the settings.py file, but I am new to apache so I do not know. error.log: [Tue Aug 16 19:45:59.789014 2022] [mpm_event:notice] [pid 9672:tid 140130027445184] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Aug 16 19:45:59.789098 2022] [core:notice] [pid 9672:tid 140130027445184] AH00094: Command line: '/usr/sbin/apache2' [Tue Aug 16 19:46:07.705559 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] mod_wsgi (pid=9675): Target WSGI script '/home/ubuntu/django/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Tue Aug 16 19:46:07.705632 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] mod_wsgi (pid=9675): Exception occurred processing WSGI script '/home/ubuntu/django/myproject/myproject/wsgi.py'. [Tue Aug 16 19:46:07.706225 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] Traceback (most recent call last): [Tue Aug 16 19:46:07.706273 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] File "/home/ubuntu/django/myproject/myproject/wsgi.py", line 16, in <module> [Tue Aug 16 19:46:07.706279 2022] [wsgi:error] [pid 9675:tid 140129892517632] [remote 98.33.108.178:64905] … -
Django runserver+Celery worker+Celery beat not running at the same time (with broker and backend redis)
{proj name}/settings/celery.py My project name is 'cole_rochman' and versions of packages are django==2.2.8, celery==4.3.0, redis==3.3.11, django-celery-results==1.1.2. I'm using broker url with aws redis. BROKER_URL = '{primary endpoint}', CELERY_RESULT_BACKEND = 'django-db'. I'm also using aws ec2 server. I opened three linux servers and wrote command 'python manage.py runserver 0.0.0.0:8000', 'celery -A {proj name} worker -l INFO', 'celery -A {proj name} beat -l INFO' each. Django and celery separately runs with no problem but when running them together, server stops. Please help me about the reason why this happens. -
3 django model filterset with django-filter
I have 3 different django models and I want to filter using django-filter. The ORM query I wrote below works without any problems. but how can i do this with django-filter (filters.FilterSet) ? Employee.objects.filter(companyrecord__company__cname__icontains="ompanyname") THIS IS WORKS it is work for me in ORM. But how can i do this in filter set. I wrote above what I want to do My Models: class Employee(models.Model): employee_name = models.CharField(...) class CompanyRecord(models.Model): employee = models.ForeignKey(Employee) company = models.ForeignKey(Company) class Company(models.Model): cname = models.CharField(...) My FilterSet: class EmployeeFilter(filters.FilterSet): full_name = filters.CharFilter(field_name="full_name", lookup_expr='icontains') class Meta: model = Employee fields = ['full_name'] -
Prevent capitalization in model field's verbose_name
I use the following template tag: @register.simple_tag def get_verbose_field_name(instance, field_name): """ Returns verbose_name for a field. """ return instance._meta.get_field(field_name).verbose_name.title() Assume I have defined a model field lorem_ipsum with the field's verbose_name="FOO bar". Then, when I run {% get_verbose_field_name object "lorem_ipsum" %} in the template in a table's <th> element, I receive "Foo Bar". However, I want to keep the verbose name exactly how I defined it—in this example as "FOO bar". How can one disable auto-capitalization of verbose names? -
any change in CSS are not reflecting in django project
I have installed whitenoise on my project and settings for my projects for static file is, settings.py, STATIC_URL = '/static/' STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles')) STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))] STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Media files MEDIA_URL = '/media/' MEDIA_ROOT = str(BASE_DIR.joinpath('media')) in urls.py, ( + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) this is also added, problem is that the project is ok with older css but if I make any changes it have no effect,how to solve it -
Can I expand an HTML table to display more data from another django model?
I have the below HTML code, which creates a table by looping through the data from a Django SQL based model. I'd like to add a plus button to each row, allowing each to expand to show a few rows of data from a DIFFERENT model based on matching household id's. I've tried many different jquery functions along with adding the another body to the table with a new loop for the new model data, but I can't seem to get my desired result. Any help would be appreciated! Example desired result: expanding row image Code: <div class="container" style="height:600px;width:1200px;overflow:scroll;max-height:500px"> <table position="relative" class="table table-bordered"> <thead> <tr> <th>Household</th> <th>Name</th> <th>Account Number</th> <th>Basic Materials %</th> <th>Communication Services %</th> <th>Consumer Cyclical %</th> <th>Consumer Defensive %</th> <th>Energy %</th> <th>Financial Services %</th> <th>Healthcare %</th> <th>Industrials %</th> <th>Real Estate %</th> <th>Technology %</th> <th>Utilities %</th> </tr> </thead> <tbody> {% for i in sectors %} <tr> <td>{{ i.household }}</td> <td>{{ i.owner }}</td> <td>{{ i.account_num }}</td> <td>{{ i.basic_materials }}</td> <td>{{ i.communication_services }}</td> <td>{{ i.consumer_cyclical }}</td> <td>{{ i.consumer_defensive }}</td> <td>{{ i.energy }}</td> <td>{{ i.financial_services }}</td> <td>{{ i.healthcare }}</td> <td>{{ i.industrials }}</td> <td>{{ i.real_estate }}</td> <td>{{ i.technology }}</td> </tr> {% endfor %} </tbody> </table> </div> These are a few links i have … -
Django publish to KAFKA instead of save to database
We are trying to develop a microservice architecture in Django rest framework where all writes to a SQL database are done by publishing messages to topics on a Apache Kafka messaging system, and all reads are done directly from an SQL database. This is being done for several reasons, but most importantly it's to have an event log history through Kafka, and to avoid delays due to slower write cycles (reads to databases are usually much faster than writes). Using signals, it's quite easy to call a Kafka producer method in Django which will publish an event on Kafka showing the model data to be written to db. However, we don't know how to avoid having the save() method write anything to the database. We don't want to completely override the save() method as it may cause issues when dealing with ManytoMany relationships. Does someone have a simple suggestion to avoid database writes but still do database reads in Django? Please keep in mind that we still want to use the conventional method to read from the SQL database using Django models. Any suggestions would be valuable! Thanks in advance. -
Cannot access foreign key elements in html templates DJANGO
Views: def search_devis(request): devis = Devis.objects.all() commercial = User.objects.all() client = Client.objects.all() context={ 'devis': devis, 'commercial': commercial, 'client_': client, } return render(request, "manage_devis/search_devis.html",context ) Models: class Devis(models.Model): titre = models.CharField(max_length=30, ) date_ecriture = models.DateField(auto_now_add=True) date_expiration = models.DateField() client = models.ForeignKey(Client, name="CLIENT_FK", default=1 ,on_delete=models.SET_DEFAULT) total = models.DecimalField(max_digits=10, decimal_places=2) commercial = models.ForeignKey(User, name="COMMERCIALFK", default=1 ,on_delete=models.SET_DEFAULT) def __str__(self): return "DV"+str(self.pk) Templates: {% for devis_ in devis %} <tr> <th scope="row"><a href="{% url 'view_devis' devis_.pk %}">DV{{devis_.id }}</a></th> <td>{{ devis_.date_ecriture }}</td> <td>{{ devis_.date_expiration }}</td> <td>{{devis_.client.nom}}</td> <td>{{ devis_.total}} DH</td> <td>{{ devis_.commercial.last_name}}</td> </tr> {% endfor %} I can't display the attributes of the foreign key object, no value in it. nothing appear in the column. I'm using postgresql database. -
HTML For Loop to add Image from Django Database
I am working on passing through a logo into my html code, however whenever I pass it through into html, a little blue question mark appears instead. I was wondering how to pass through the logo into the src. Thanks for the help. class LoansOutstanding(models.Model): company_name = models.CharField("Company Name", max_length=50, default="") company_logo_url = models.ImageField("Company Logo", upload_to="main/None", height_field=None, width_field=None, max_length=100, blank=True, null=True) Views.py def number(request, number): loans_in_security = LoansOutstanding.objects.filter(number=number) return render(request, template_name='main/number.html', context={"loans_in_securities": loans_in_security}) HTML <div class="profile-details"> <div class="profile-image-pane"> <ul> {% for loans in loans_in_securities %} {% if forloop.first %} <li><img class="profile-image" src="{{loans.company_logo_url}}"/></li> {% endif %} {% endfor %} </ul> </div> </div> -
Django: How to override the MIME type of a user uploaded file?
Users on my web dev forum can upload HTML files as attachments to their posts, to show their code. This is done through a Django FileField. How can I ensure that these uploads are then served with "text/plain" content type, rather than "text/html"? Because the purpose is for other people to look at the source code, not the rendered HTML. -
how to translate each and every row of csv file
some words of the row are getting translated, sometimes and sometimes not. from googletrans import Translator myfile=open("ElectricCarData_Norm.csv") f=myfile.readlines() translator=Translator() with open("Electric.csv", 'w',encoding="utf-8") as op: for line in f: #print(line) translation = translator.translate(line, src='en',dest='hi').text #print(line," ",translation) op.write(translation) op.write('\n') -
My usertype user and doctor is not setting true while registering user
I am a new bie in django, creating doctor appointment project. I have extend the abstractuser and set user type is_patient and is_doctor, user register and doctor register form is different. I want if the user register through user form is_user should set True if user register through doctor form is_doctor should set true. But its not setting true everytime registering. Below is my code. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import User # Create your models here. class User(AbstractUser): is_user = models.BooleanField(default=False) is_doctor = models.BooleanField( default=False) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class User_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) User.is_user = True fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=100,blank=False) address = models.TextField(max_length=500,blank=False) gender = models.CharField(max_length=7, blank=False) phone = models.CharField(max_length=12,unique=True,blank=False) Username = models.CharField(max_length=100,blank=False,unique=True) Userpassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname class dr_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) user.is_doctor = True fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) image = models.ImageField() specialisation = models.CharField(max_length=100,blank=False) qualificaton = models.CharField(max_length=100,blank=False) phone = models.CharField(max_length=12,blank=False,unique=True) gender = models.CharField(max_length=7,blank=False) address = models.TextField(max_length=500,blank=False) state = models.CharField(max_length=50,blank=False) city = models.CharField(max_length=50,blank=False) zip = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=50,blank=False) dUsername = models.CharField(max_length=100,blank=False,unique=True) dPassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname views.py def register(request): if request.method == "POST": fname = … -
Django unable to bind uploaded file
Clarification: I'm developing on top of the django admin module. I implemented a csv model upload using a simple FileField form, and read the uploaded text file with a TextIOWrapper without any problems. I am trying to add an intermediate screen warning the user of potential data loss. I'm basing it off the admin delete action confirmation screen. The problem I'm having is passing the in-memory uploaded file to the intermediate screen to access it upon user confirmation. I tried doing this with a bound form but the uploaded data seems to vanish. I am using a very simple form: class CsvImportForm(forms.Form): csv_file = forms.FileField() overwrite = forms.BooleanField() I have no problem when serving the GET view. Now comes the funny part. When processing the same view for a POST request, I try to bind the form as per the documentation, and pass it to the template builder: def import_csv(self, request, form_url="", extra_context=None): ... if request.method == "POST": form = CsvImportForm(request.POST, request.FILES) context.update({'form': form}) ... return TemplateResponse( request, "admin/import_confirm.html", context ) The import_csv method is part of my ModelAdmin subclass, and gets called by overriding the get_urls method. The template builds the form like so: <form action="{{ form_url }}" method="post" … -
How do I use HTTP status code enum as django model field choices?
I would like one of my django models to have a field like this: status = models.ImageField(choices=Status, max_length=20) but instead it would take directly from the HTTPStatus class -
how to bind data from a form vue js with Django using post axios?
I want to develop an interface that uploads a file with Vue js from my backend in django, I can't figure out the problem. but here is the error I got: "POST http://127.0.0.1:8000/upload/ 500 (Internal Server Error)" here the class "upload" in view.py: def upload(request): obj = None dict={} if request.method == 'POST': repo = Repository(username="fedoraAdmin",password="fedora2022") obj = repo.get_object(type=FileObject) obj.file.content = request.FILES['file'] obj.file.mimetype=request.FILES['file'].content_type obj.file.label=request.FILES['file'].name obj.label = request.POST['label'] obj.save() dict=obj.index_data() print(dict) return JsonResponse(dict) my form in forms.py: class UploadForm(forms.Form): label = forms.CharField(max_length=255, # fedora label maxes out at 255 characters help_text='Preliminary title for the new object. 255 characters max.') file = forms.FileField() Finally, my vue js code: <template> <div class="container"> <h1 class="title mb-6">Uploader</h1> <div> <form @submit.prevent="submitFile" enctype="multipart/form-data"> <input type="file" @change="uploadFile" ref="file"> <button>Upload!</button> </form> </div> </div> </template> <script> import axios from 'axios' export default { name: 'archivage', mounted() { document.title = 'Archivage | fedora' } , methods: { uploadFile() { this.file = this.$refs.file.files[0]; this.label=this.$refs.file.files[0].name }, performUpload() { const formData = { label: this.label, file: this.file} axios .post('/upload/',formData) .then(response => { console.log(response.data) ; }) .catch(error => { console.log(error) }) }, submitFile: function(){ this.performUpload() }, } } </script> -
Looping through nested dictionary in Django
I am trying out an implementation. Although I have figured the logic out, I am having issues representing it programatically. I need your help or guidance. Below is the detailed explanation of my code and what i am trying to achieve, please pardon me as it would be a long read. What I want to achieve I want to create an endpoint - /order/tradeadvisor/{{producer_order_id}}, so that if the endpoint is hit, then it should first record the producer_order_id in a variable, then it should go to the Order model and loop through it fetching all order_id, user_id with the user_type=1. After that it should, now produce a a single record where, the user caprice is equal to producer floorprice(where the producer is the logged in user) and then the user needed engery is equal to the producers surplus and then store this record in the Trade table. What i have done User.model: class User(AbstractBaseUser, PermissionsMixin): dso = models.ForeignKey(to=Dso,related_name='dso',null=True,on_delete=models.CASCADE) name = models.CharField(max_length=70) address = models.CharField(max_length=70) roleId = models.IntegerField(default=1) customerId = models.CharField(max_length=70, blank=False, default='') floorPrice = models.DecimalField(max_digits=10, max_length=255, decimal_places=2, null=True) capPrice = models.DecimalField(max_digits=10, max_length=255, decimal_places=2, null=True) tradeStrategy = models.CharField(max_length=255, null=True) username=models.CharField(max_length=255, unique=True, db_index=True) email=models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Django ORM: slow SQL request using an update with a list of ids
I have some database speed issues when doing an update with Django. My request takes about 15s to be executed, updating ~1000 rows, which is quite slow Here is a simplified version of my code myList = Model.objects.filter( ... )[:nb] myListIds = [] for object in myList: ... myListIds.append(object.pk) Model.objects.filter( pk__in=myListIds ).update( ... ) I tried to look at the SQL request generated by Django, but it didn't teach me anything What am I doing wrong here ? -
Is There a way to store the username in a django model? [closed]
I am trying to store the user who submitted the form in the database model using django from django.db import models # Create your models here. class Message(models.Model): sent_by = #should hold the username msg = models.CharField(max_length=255) -
How to select multiple rows in a table and link them in the database?
I have a large table with different records. I want to be able to select multiple records (radio button) and link them together by clicking on a "link" button. In the background, there is a LinkId column which would be set to some consequent integer. What is the best design decision and which plugin/form/etc should I use? I'm not very familiar with Django. Thanks. -
Formatting ouput table in template from django.model
I am creating a currency exchange rate aggregator app. I have got next models. class Bank(models.Model): bank_name = models.CharField( max_length=30, blank=False, unique=True, ) class ExchangeRate(models.Model): USD_in = 'USD_in' USD_out = 'USD_out' EUR_in = 'EUR_in' EUR_out = 'EUR_out' RUB_in = 'RUB_in' RUB_out = 'RUB_out' USD_EUR_in = 'USD_EUR_in' USD_EUR_out = 'USD_EUR_out' exchange_choise = [ (USD_in, 'USD_in'), (USD_out, 'USD_out'), (EUR_in, 'EUR_in'), (EUR_out, 'EUR_out'), (RUB_in, 'RUB_in'), (RUB_out, 'RUB_out'), (USD_EUR_in, 'USD_EUR_in'), (USD_EUR_out, 'USD_EUR_out'), ] datetime = models.DateTimeField( auto_now_add=True, blank=False, ) exchange_type = models.CharField( max_length=12, choices=exchange_choise, ) rate = models.FloatField() bank_id = models.ForeignKey( Bank, on_delete=models.CASCADE, ) quantity = models.IntegerField( default=1, ) Basically two tables. One stores bank names, another exchanging currencies and their rates. So if I will output data from model as it is I will get next picture: If I would put it in html table, it would look like this. Notice, that each currency exchange rate takes one row (datetime, currency, rate, bank). And I want that each bank would have all its currency exchange rates in one row like in the picture bellow. I wonder, how can I do this? Do I need to perform some join operation or to write code in template to format it like this. View class: class … -
why FileSystemStorage() in django adding % forcefully in url of image
D:/Experiment/todoproject/media/download%202_f9xn1jm.jfif percentage % in url but not showing in name when i check it it is same image it should adjust name but this % sign is not name of image and that's why @shared_task(bind=True) def test_fun(self,url,id1): if not url== None: path_to_image ="D:/Experiment/todoproject"+url print(path_to_image) try: Image.open(path_to_image) not running -
How to save json data in Django database using queryset
I have this json data { 'items_data': [ {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4', 'tax_code': 'GST 18', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra', 'invoice_number': 'TES-0822-97', 'tax_no': '18', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 36, 'SGST': 36}, {'item': 'Datalogger', 'hsn': '123', 'unit_name': 'BAG', 'unit_price': '100', 'quantity': '4', 'tax_code': 'GST 28', 'base_discount': '4', 'discount_value': 16, 'amount': 384, 'state': 'Maharashtra', 'invoice_number': 'TES-0822-97', 'tax_no': '28', 'tax_name': 'GST', 'base_Amount': 400, 'CGST': 56, 'SGST': 56}], 'invoice_num': 'TES-0822-97', 'gst_data': [ {'tax_no': '18', 'totalGST': 72, 'total_base_amount': 400, 'cgst': 36, 'sgst': 36}, {'tax_no': '28', 'totalGST': 112, 'total_base_amount': 400, 'cgst': 56, 'sgst': 56} ] } Now I want to get items data and store into database by query set. how can I save this by using query set objects? I am doing this code def get_invoice_items(request): json_body = json.loads(request.body) print(json_body) for data in json_body["items_data"]: print(data) items=Items_Details.objects.bulk_create(data) print(items) return JsonResponse({"message" : "Request Handled.."}) but getting error -
How to post/delete data from form into database using Django?
I am using a form to post a record to my database in Django. The form looks something like this: <form> <div>Field 1</div> <input/> <div>Field 2</div> <input/> ... <a id='save'>Save</a> </form> I am using an event listener to let me know when this Save link has been clicked. When it is clicked, I would like to store the fields as a record in the database. Here is my JS: const savebtn = document.querySelector('#save'); savebtn.addEventListener('click', showSelected); function showSelected(e) { // post record to database here window.location.replace("/"); // redirect to home page I am hoping to use some python to post this record like shown below: e = Entry() e.field1 = 1 e.field2 = 2 e.save() But I don't know how I can access a python function within JS. I'm thinking maybe a template tag could work here but can't figure out how to use it. Ideally I wouldn't have to rewrite the form as the formatting is kind of specific, is there a way to make this work? -
How to add nested serializer field
I have a nested serializer which creates the objects like they are supposed to but also return an error. Models: class Trip(models.Model): startTime = models.DateTimeField() endTime = models.DateTimeField() def __str__(self): return str(self.startTime) + " - " + str(self.endTime) class TripFaceDetection(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE, blank=True) firstFace = models.DateTimeField() lastFace = models.DateTimeField() faceCount = models.IntegerField() Serializers: class TripSerializer(serializers.ModelSerializer): faces = TripFaceDetectionSerializer() class Meta: model = Trip fields = ('id', 'startTime', 'endTime', 'faces') def create(self, validated_data): face_data = validated_data.pop('faces') trip = Trip.objects.create(**validated_data) TripFaceDetection.objects.create(trip=trip, **face_data) return trip The objects are created but I also get the error: backend_1 | AttributeError: Got AttributeError when attempting to get a value for field faces on serializer TripSerializer. backend_1 | The serializer field might be named incorrectly and not match any attribute or key on the Trip instance. I understand I don't have the field within the Trip model, but I expect that since I define the field in the serializer and create it in the create method that it shouldn't return this error. How can I get rid of this error while using faces for both reading/writing as well as leaving my model structure as-is?