Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to inner join multi tables or merge multi serializers in Django?
i have this code here for the models: class Users(models.Model): first_name = models.CharField(max_length=32, blank=True, null=True) last_name = models.CharField(max_length=32, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) class Images(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) encoded_pic = models.JSONField( encoder=None, default=dict, blank=True, null=True) pic_thumbnail_path = models.CharField(max_length=222, blank=True, null=True) class WorkingDays(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) day = models.DateField(blank=True, null=True) enter_time = models.DateTimeField(blank=True, null=True) exit_time = models.CharField(max_length=32, blank=True, null=True) class Departments(models.Model): user= models.ForeignKey(Users, on_delete=models.RESTRICT) department_name = models.CharField(max_length=32, blank=True, null=True) These are the serializers: class UserssSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' class ImagesSerializer(serializers.ModelSerializer): class Meta: model = Images fields = '__all__' class WorkingDaysSerializer(serializers.ModelSerializer): class Meta: model = WorkingDays fields = '__all__' class DepartmentsSerializer(serializers.ModelSerializer): class Meta: model = WorkingDays fields = '__all__' I tried this code but it only returns the images fields not the others data=Images.objects.filter(user_id__workingdays=pk).values() What i want to do is to inner join images, workingdays and departments table using user_id field also is there away to merge serializers of all these 3 tables to make the serializer returns all the fields from all the 3 tables? -
Nginx server does not recognize static Django files
I'm setting up an AWS server and I finished the tutorial provided by DigitalOcean, however my server doesn't recognize my static files and displays a page with styles only via CDN (Tailwind) Nginx Configuration: server { listen 80; server_name xxxxxxxxxxxxx; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /home/ubuntu/Filmes/static; } location /media { root /home/ubuntu/Filmes; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } My project settings.py: import os STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR / "static") Structure when running python manage.py collectstatic: - static |------ admin |------ css |------ images |------ js |------ staticfiles.json Tutorial:https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 -
generic createview and django form only rendering a button in a template
I have encountered a funny challenge, as am building some apps where they want track some expenses and revenues profits ... I used generic views to create and get details and delete, all work fine with expenses, but I copied the same code and I used it for revenues from expenses you can't imagine this view is rendering a button only yet it has a form, NOTE SAME CODE WORK WELL ON EXPENSES. I even exchanged templates but it kept rendering the former content even after changing the template. it doesn't matter what's in the template the view just renders the same thing even when I remove the form, even when I put pass. class AccountsRevenueCreate(CreateView): template_name='dashboard/expense_create.html' model= AccountsExpense success_url = reverse_lazy('dashboard:expenses') form_class=AccountsExpenseForm and the form class AccountsRevenueForm(forms.ModelForm): class Meta: model = AccountsRevenue fields = '__all__' and in the template <div class="row"> <div class="col-12"> <h5 class="form-title"><span>revenue Update </span></h5> </div> <form method="post", action="{% url 'dashboard:revenue_add' %}"> {% csrf_token %} {% comment %} {{ form|crispy }} {% endcomment %} {{ form.as_p }} <button type="submit" class="btn btn-primary col-12 col-sm-12">Save </button> </form> </div> and the URLs path ('accounts/revenues/create/', AccountsRevenueCreate.as_view(), name='revenue_create'), I have chosen to show you only where the problem is not paste unnecessary … -
Django Template Variables to Javascript File
Currently I have my Django project set up so that the JS variables that depend on template variables are first defined under a script tag in the HTML template. Then, when the template runs, the JS variable gets created and added to the Javascript context, causing other external JS scripts to be able to use said variable without declaring it anywhere. Html template: <body> content </body> <script> const var = "{{ my_template_var }}"; </script> <script type="module" src="{% url 'app_name/index.js' %}"></script> JS Script (app_name/index.js) console.log(var) // Prints value of "my_template_var" in the form of a string However, I dont like the fact that the var variable in the JS script just "magically" has the value defined in the template when it runs (there's no actual statement saying const var = something). Is there any way that I can include a declaration in my JS file (not a comment) so that its a bit clearer to the rest of the developers from where the variable is coming from? (NOTE: I'm mainly doing this as well because when using Typescript, those variables appear as undefined, even though they are receiving a value from somewhere) -
Suitescript url.resolveTaskLink and line breaks
I am using url.resolveTaskLink to convert a custom record to a sales order. On the custom record there is a text area field where there a line breaks but when I convert it over to a sales order - instead of performing the line breaks I am getting a tag. I tried using replace like this but it did not work: var fixpuaddress = puaddress.replace(/&lt;br&gt;/g," "); How can I have it do the actual carriage return? -
I want to access the files inside the zip file and send it back to Django backend
I want to access the file extracted from a zip file and post it to the database, this code is for extracting the files, I don't know how to access the files: var reader = new FileReader(); reader.onload = function (ev) { JSZip.loadAsync(ev.target.result).then(function (zip) { var zipfile_names = new Array(); var shpfile_names = new Array(); var BreakException = {}; var allFiles = new Array(); try { zip.forEach(function (relativePath, zipEntry) { $("#div1").hide(); document.getElementById("div2").hidden = false; $("#div2").show(); //CONTROL THAT FILE EXTENSIONS ARE ALL SHAPEFILE VALID var allowed_shp_extensions = ['shp', 'shx', 'dbf', 'sbn', 'sbx', 'fbn', 'fbx', 'ain', 'aih', 'atx', 'ixs', 'mxs', 'prj', 'xml', 'cpg'] var shpext = ['shp'] // check the zipEntry is a file if ((zipEntry.name.includes('.') == true) && (zipEntry.dir == false)) { var split_filename = zipEntry.name.split('.') if (allowed_shp_extensions.includes(split_filename[split_filename.length - 1]) == true) { var name_extract = zipEntry.name.replace(/^.*[\\\/]/, '') zipfile_names.push(name_extract) } allFiles.push(zipEntry.name); };});``` -
Profile table not being created for extended User model in django
I am facing this problem in django where even though there is a Profile model in my models.py file which extends the django User model still on running the 'makemigration' and 'migrate' commands the Profile table is not being generated in database. This is my models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) clg_name = models.CharField(max_length=200) class Student(models.Model): name = models.CharField(max_length=100, blank=False) enrollment_number = models.IntegerField(unique=True, null=True, blank=False) clg_name = models.CharField(max_length=200, blank=False) program_name = models.CharField(max_length=30, blank=False) class Result(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) sem = models.IntegerField() exam_name = models.CharField(max_length=30) percnt = models.FloatField(null=True) cgpa = models.FloatField(null=True) class Marks(models.Model): result = models.ForeignKey(Result, on_delete=models.CASCADE) course_name = models.CharField(max_length=100, null=True) course_code = models.IntegerField(null=True) course_credit = models.IntegerField(null=True) grade = models.FloatField(null=True) Here is the output of py manage.py makemigration account: Migrations for 'account': account\migrations\0001_initial.py - Create model Result - Create model Profile - Create model Marks And this is the output of py manage.py migrate: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. -
Django Multi Step Form duplicate key value
I'm attempting to implement a multi-step form on Django and am relatively new to the language but am having difficulty when it comes to saving to the data to the backend. Any help would be much appreciated. Spend around 8 hours trying to figure this out myself. I need to pass the code and name from model Books to People and then insert the other required information on step 2 as this is a separate table model. There is a foreign key connecting People to Books via the id. Views.py #Step1 def step1(request): initial={'code': request.session.get('code', None), } form = PrimaryForm(request.POST or None, initial=initial) if request.method == 'POST': if form.is_valid(): return HttpResponseRedirect(reverse('main_app:step2')) return render(request, 'step1.html', {'form': form}) #Step2 def step2(request): form = SecondaryForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form1 = form.save(commit=False) form2 = People.objects.create(code=request.session['code']) form1.save() return HttpResponseRedirect(reverse('main_app:finished')) return render(request, 'step2.html', {'form': form}) Forms.py #models/forms class PrimaryForm(forms.ModelForm): class Meta: model = People fields = ('id','code','name',) class SecondaryForm(forms.ModelForm): class Meta: model = Books fields = ('type','title',) exclude = ('book_id',) Error message insert or update on table "PEOPLE" violates foreign key constraint DETAIL: Key (id_id_id)=(0) is not present in table "PEOPLE". The code, name should pass through the forms and at … -
Query all related elements in Django Admin
I have a custom user model at the top of the hierarchy. Underneath the user model, there are 3 different profiles that are created at signup. Two of the three Profiles are able to upload data and store the URL into the PDF_Files database. Now, I want to query all the information related to a unique custom user ID and show it in the admin panel at one place. For example: [Custom_User] User_Id (1) -> [Profile_2] User_Id (1) -> [Pdf_Files] User_id (1) | File_Url (media/filexy.pdf) -
COMMENTS_XTD_MAX_THREAD_LEVEL not working properly--replies are not nesting under comment
The commenting system works fine, the comments are being processed and displayed the blog_details view just fine. It's the level/nesting or the reply comment is what's not working. I've been playing with the settings for over two nights now, reading the docs over and over again trying different things to no avail. I'm beginning to suspect that there may be an issue with my project. If someone could just look at my code and point out the issue. I'm using this package with my test blog app so I set the settings as follows. settings.py SITE_ID = 1; COMMENTS_APP = 'django_comments_xtd' COMMENTS_XTD_MAX_THREAD_LEVEL = 2 # site wide default COMMENTS_XTD_MAX_THREAD_LEVEL_BY_APP_MODEL = { # Objects of the app blog, model post, can be nested # up to thread level 1. 'blog.post_details': 1, } html {% load comments %} {% load comments_xtd %} {% block title %}{{ post_details.title }}{% endblock %} <div class="pb-3"> <h1 class="page-header text-center">{{ post_details.title }}</h1> <p class="small text-center">{{ post_details.publish|date:"l, j F Y" }}</p> </div> <div> {{ post_details.body|linebreaks }} </div> {% get_comment_count for post_details as comment_count %} <div class="py-4 text-center"> <a href="{}">Back to the post list</a> &nbsp;&sdot;&nbsp; {{ comment_count }} comment{{ comment_count|pluralize }} ha{{ comment_count|pluralize:"s,ve"}} been posted. </div> {% if post_details.allow_comments … -
Containerized Django Migrations
What are the best practices for managing django schema/data migrations in a containerized deployment? We are having issues with multiple containers attempting to run the migrate command on deploy and running our migrations in parallel. I was surprised to learn that django doesn't coordinate this internally to prevent the migrations from being run by two containers at the same time. We are using AWS ECS and struggling to automatically identify one container as the master node from which to run our migrations. -
How to write javascript's FileReader() reader.result object to a file at server side using python?
I'm writing a Jupyterlab extension, in one of its functionality, I'm trying to write file upload functionality which reads the user-selected file and write back to the server. To accomplish the job it uses javascript's FileReader API and then passes the object to python using JSON.stringify(). However, I'm able to write a file on the server side using a test string but not able to write a file using the file content due to the object compatibility issue. This code contains both javascript and server-side code. readFile(data) { let file = data.files[0]; let reader = new FileReader(); reader.readAsText(file); reader.onload = async function() { console.log(reader.result); console.log('OK'); var InitialData = await KernelSideDataObjects(`import json\nfile = open('test.txt', 'wb+')\nfile.write('test')`); //var InitialData = await KernelSideDataObjects(`import json\nfile = open('test.txt', 'wb+')\nfile.write(${JSON.stringify(reader.result)})`); // console.log(reader.readAsDataURL(file)) }; reader.onerror = function() { console.log(reader.error); }; } How can I translate or decode reader.result into a python-compatible manner to write file content in a file? Thanks -
Django perform CRUD on multiple models
Is it possible to perform CRUD operations on multiple Django models without creating an html template and writing a View function for each and every operation. For example, say you have the following model: class Employee(models.Model): name = models.CharField() age = models.IntegerField() With this one model, to perform CRUD operations, you would define a function for each operation in views.py (4 functions) and create a template for each, i.e., create_employee.html, retrieve_employee.html, update_employee.html, delete_employee.html. Now, say instead of just an Employee model, there's 20 models that you want to be able to perform CRUD operations on. Do you have to create CRUD functions for each model in views.py and also create a template for each operation for each model? Or is there a simpler way? For example, create one function per model in views.py that performs the CRUD operations and one template per model? -
how to initiate a pdf download with an api call from react frontend to a drf backend - django rest framework
I have an app that uses django rest framework for the backend and react for the frontend. I use the react production build and integrate it with django to serve it. My app has an download pdf functionality. I am using xhtml2pdf for generating pdfs. I refered a tutorial and wrote the below codes to generate the pdf which working fine for the time being react code below the href points to the url in django <DownPdf href={`/${cat}/download-pdf/${id}/`}> <i className="far fa-file-pdf"></i> Download PDF </DownPdf> urls.py path('download-pdf/<str:pk>/', views.download_citation_as_pdf, name='download-pdf'), views.py @api_view(['GET']) # @permission_classes([IsAuthenticated]) def download_citation_as_pdf(request, pk): try: query = Civil.objects.get(id=pk) serial = Full_Detail_Serial(query, many=False) print(serial.data['title']) data={ "serial_data" : query, "site":request.get_host() } pdf = render_to_pdf('citationPdfEmail.html', data) # below returns the pdf view in browser # return HttpResponse(pdf, content_type='application/pdf') # to start force download if pdf: print('pdf is returned to the view') response = HttpResponse(pdf, content_type = 'application/pdf') filename = f"sl_%s.pdf" %(serial.data['title']) content = "inline; filename= '%s'" %(filename) """ the double quotes is used to enclose %s beacause the title may contain commas and other special characters. Single quotes cannot be used to enclose %s and double quotes should be used other with it will throw an error. """ content = 'attachement; filename= … -
User Login Authentication using Django Model and form
I am trying to setup user authentication for the login page using forms and comparing it to my database value but it does not work. I also tried using this particular questions User Login Authentication using forms and Django logic to solve my problem but it didn't help. Models.py from django.db import models from django.contrib.auth.password_validation import validate_password class student(models.Model): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) matric_number = models.CharField(max_length=9) email = models.EmailField(max_length=50) password1 = models.CharField(max_length=255, validators=[validate_password]) password2 = models.CharField(max_length=255) def __str__(self): return (self.matric_number) This view saves user info to database def student(request): if request.method == 'POST': form = studentForm(request.POST) if form.is_valid(): sign_up = form.save(commit=False) #sign_up.password1 = make_password(form.cleaned_data['password1']) #sign_up.password2 = make_password(form.cleaned_data['password2']) sign_up.status = 1 sign_up.save() user = form.cleaned_data.get('matric_number') messages.success(request, "Account was created for "+str(user)) return redirect(signin) else: form = studentForm() return render(request, 'Student.html',{ "form": form }) This is the signin view def signin(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') try: student = student.object.get(username=username, password=password) return redirect(files) except: messages.success(request, "Error") else: form = LoginForm() return render(request, "SignIn.html",{ "form":form }) This is my form.py class studentForm(forms.ModelForm): class Meta: model=student fields="__all__" widgets={ 'first_name':forms.TextInput(attrs={'placeholder': 'Enter Your First Name'}), 'last_name':forms.TextInput(attrs={'placeholder': 'Enter Your Last Name'}), 'matric_number':forms.TextInput(attrs={'placeholder': 'Enter Your Matric … -
parameters not showing up in swagger-ui django
I am trying to show APIs on swagger-ui in Django but for some reason, parameters are not showing up. I am attaching the snippet for a clear view. Code is as follows in which I am using 3 variables: def myfunc(request): fromDate = request.GET['fromDate'] toDate = request.GET['toDate'] dealershipId = request.GET['dealershipId'] cursor = connection.cursor() cursor.execute("exec proc_LoadJobCardbyDateRange @Fromdate='"+fromDate+"', @Todate='"+toDate+"', @DealershipId="+dealershipId) result = cursor.fetchall() data = { 'message': 'Data Retrieved Successfully', 'job_card': result } return Response(data, status=status.HTTP_200_OK) Also, I am not using any serializer or models here. May be that's why parameters are not showing up as it's not linking with any model or serializer but I am new to do this so I don't know. Please help so I can show parameters in the swagger-ui. -
Display django messages with HTMX
I want django messages to be displayed at the left bottom of the viewport when a new record is created. The problem is that the record creation only updates a portion of the html with HTMX, so the message only shows up when I reload the entire page. How can I make it show when the HTMX loads? Thanks!! -
Django Datatable with Json Detail, Update and Delete View for each row
I managed to build a datatable with data from JSON. What I am now trying to achieve is to add buttons with Detail, Update and DeleteView for each row. Please see the code attached. My question is, how can I create buttons from JS to HTML template with specific URLs for each row? models.py from django.db import models class Employee(models.Model): GENDER = ( ('M', 'M'), ('F', 'F') ) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) occupation = models.CharField(max_length=100) salary = models.CharField(max_length=100) gender = models.CharField(max_length=100, null = True, choices=GENDER) def __str__(self): return self.name def get_data(self): return { 'id':self.id, 'name':self.name, 'email':self.email, 'occupation':self.occupation, 'salary':self.salary, 'gender':self.gender, 'option':self.gender, } views.py def home(request): employees = Employee.objects.all() return render(request,"home.html") def employee_json(request): employees = Employee.objects.all() data = [employee.get_data() for employee in employees] response = {'data':data} return JsonResponse(response) HTML {% extends 'base.html' %} {% block navbar-content %} <i style="color: yellowgreen;" class="fas fa-user-alt"></i>&nbsp;&nbsp; Employee list {% endblock navbar-content %} {% block content %} <div class="container novi_rn"> <div class="modal fade" tabindex="-1" role="dialog" id="modal"> <div class="modal-dialog modal-l modal-dialog-centered" role="document"> <div class="modal-content"></div> </div> </div> </div> <div class="container"> <button id="add-item-rn" class="btn btn-secondary gumb" type="button" name="button">DODAVANJE ARTIKALA</button>&nbsp&nbsp&nbsp <script type="text/javascript"> $(document).ready(function() { $("#add-item-rn").modalForm({ formURL: "{% url 'create' %}" }); }); </script> <br><br><br> <table class="table … -
How to import all url paths from urls.py and store it in a list in a view in views.py
I want to store in a dict all the urls defined in main_urlpatterns within url.py: main_urlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login_view, name='login')] So in the view.py i created a function like follows: from app_productora.urls import main_urlpatterns def siteurls_view(request): url_list=main_urlpatterns context = { 'url_list':url_list } return render(request, 'siteurls.html', context) But i have a circular problem between the import of the views.py in url.py and the import of the url.py in views.py. Any idea? -
NetSuite: Create button to send PDF of Invoice using SuiteScript
Create a Button on Invoice called SEND EMAIL using SuiteScript. Only show this button to View Mode and when User is Administrator. If user click that button, it should send an email with Invoice PDF Attachment. -
How to upload scrapy spiders to Django app on Azure
Is where any way I can allow users to upload spiders to Django app? It should look like this: user uploads a zip package with python files and after successful upload scripts would create a task and run all functions independently. Then it would save scraped data to the database. How can I do something like this? Do I need to create a virtual machine or there is another way of doing it in Django and Azure? -
Django signals. Please help me how to refresh the html page of the user when receiving the signal
Good afternoon! I just started to learn Django framework. I have a question. I can't seem to connect the separate commands application, which runs through the python manage.py command I made to the server. The idea is to dynamically update the page. The data from the bot goes into sqllite and from there, when you go to a new page, it is parsed and displayed. At the moment the data is working fine, but I want to update the page where the user is or add a message when adding a record to the database. Tried to do through the signals, but as there are 2 different scripts server and bot, the update b.d. displayed only in the code or bot, or when reloading the page. @receiver(post_save, sender=Message) def update(created, **kwargs): msg = Message.objects.order_by("data") obj = msg.latest('data') print(obj.user_id) I put this code in the view. Signal code. def messenger_full(request, parameter): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): form.save() return redirect(f'/messenger/{us_id}') else: pass form = MessageForm() us_id = parameter msg = Message.objects.order_by("data").filter(user_id=us_id) obj = msg.latest('data') obj.is_read = True obj.save() username = msg[0].user_info img_id = msg[(len(msg) - 1)].img return render(request, 'page2/messenger.html', {'msg': msg, 'username': username, 'img_id': img_id, 'us_id': us_id, 'form': … -
Why my test_views works alone, but not when I run all of my tests?
I'm writing tests to ensure that my view is rendered and its context data is there when I access the link. All these tests are working, when I run them in their current dir, but when I run all my tests, these view tests give me an error in the context data. def cve_factory(): cve = Cve.objects.create( name='test', ) cve.save() return cve def vuln_to_test_context(): vuln = Vuln.objects.create( cve=cve, ) vuln.save() return vuln class PublicVulnViewTests(TestCase): def test_vulns_page_if_cvss_nonexistent(self): package = Package.objects.create(name='django') cve = cve_factory() vuln = vuln_to_test_context(cve=cve, package=package) response = self.client.get(f"/vulnerabilities/{cve.name}/{cve.id}/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context_data['highlightedCVSS'], None) self.assertEqual(response.context_data['severity'], None) This is an example of one of my tests and it is working, because I am accessing its URL correctly, but when I run all tests, the context data is not accessed because it does not exist in my response. self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 update_date = response.context_data['severity'] AttributeError: 'HttpResponseNotFound' object has no attribute 'context_data' I do not have TestCase from other directories being imported from unnitest or anything different, my TestCase is always being imported from Django.tests. -
Is Azure Cache for Redis is fine for setting up dynamic spider in Django and Celery on Azure
I am trying to figure out how can set up a project where I will be scrapping data from multiple websites using multiple spiders. Each spider has different configuration and gets different type of data (depending on website). I am using playwright to get the data. My idea is to use Celery to create tasks and schedule them so it will scrape data at particular time and day. Then the data will be sent to database and user will be able to download the output file. The whole project will be deployed to Azure and from what I am reading I will need Azure Cache for Redis. I will be also using rotating proxy to access data from websites. My questions are: Is Azure Cache for Redis a good option for such project. If not then what else can I use? What is the most efficient way to store scraped data from pages? I am currently using MongoDB but it is quite expensive solution. The reason for using noSQL is that each spider is different and scrape different type of data and in relational database it would be inefficient to add columns every time I am scrapping data from new … -
M2M field doesn't get updated
I was trying to update an M2M field but it just doesn't get updated neither from admin panel nor the serializer! We have a "Book" model which has a "Category" field that is M2M to BookCategory Model this is my model: class Book(models.Model): #... category = models.ManyToManyField('BookCategory', related_name='bookCategory') def __str__(self): return self.name class BookCategory(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey('BookCategory', on_delete=models.PROTECT, null=True, blank=True) description = models.TextField() def __str__(self): return self.name and this is my view: class BookChange(RetrieveUpdateDestroyAPIView): serializer_class = BookSerializer lookup_field = 'pk' def get_queryset(self): return Book.objects.all() and the Model Serializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' The funny thing is that when I remove the current category it works but it doesn't add the new ones I also tried Overriding the serializer.save() in def update Can you help me out?