Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How do I query specific arguments using Django RESTQL?
I'm working on a project that displays data in a table with headers. For this purpose, I chose Django RESTQL because it allows me to use pagination, sorting, and filtering. I'm able to filter by column but I can't filter by specifics. Like, if I wanted to only see the results that contain 'hello' in the name. When I run the test query, it's as if I only queried for columns and not the specific attributes. What I've Tried: https://github.com/yezyilomo/django-restql-playground-backend/blob/master/api/views.py I've tried looking at the devs backend code and everything seems similar. I'm not sure what I'm doing wrong. It must be the way I'm setting up the query in Postman or something simple. I used the following docs for the syntax. Test query: {{baseUrl}}/series/?query=(name: 'hello'){id, name} Serializer: class SeriesSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = Series fields = ['id', 'name', 'removed', 'active'] views: class SeriesViewSet(QueryArgumentsMixin, viewsets.ModelViewSet): queryset = Series.objects.all().order_by('-id') serializer_class = SeriesSerializer filter_fields = { 'id': ['exact', 'lt', 'gt'], 'name': ['exact', 'contains'], } -
How to bulk_update queryset values
# Count mandate for each delegate, multiply it by score delegate_votes = PollVotingTypeRanking.objects.filter(author_delegate__poll=poll).values('pk').annotate( score=F('priority') * Count('author_delegate__created_by__groupuserdelegator', filter=~Q(author_delegate__created_by__groupuserdelegator__delegator__pollvoting__poll=poll) & Q(author_delegate__created_by__groupuserdelegator__tags__in=[poll.tag]))) # Set score to the same as priority for user votes user_votes = PollVotingTypeRanking.objects.filter(author__poll=poll ).values('pk').annotate(score=F('priority')) PollVotingTypeRanking.objects.bulk_update(delegate_votes | user_votes, fields=('score',)) Attempting to update the values for delegate_votes and user_votes, how do i do that? Currently im getting the error 'dict' object has no attribute pk -
I cannot import from one app to another . why cant I do it?
This is my directory : I want to import The groups class model in group directory from here : from django.db import models from django.utils.text import slugify from django.urls import reverse import misaka from django.contrib.auth import get_user_model User=get_user_model() from django import template register = template.Library() # GROUPS MODULES.PY. class Group(models.Model): name= models.CharField(max_length=255,unique=True) slug= models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True, default= 'NOT_PROVIDED') description_html = models.TextField(editable=False,default='', blank=True) members = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs={'slug':self.slug}) class Meta: ordering = ['name'] and place it here in the posts/ models.py: from django.db import models from django.urls import reverse import misaka from groups import Groups #POST MODULES.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='post', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message= models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True , blank=True , on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = {'-created_at'} unique_together = ['user','message'] on Pycharm in the import 'from groups import Group' is underlined red. I have no idea why its not working. also this is the settings : -
How to set placeholder for django integerfield
I have a model form: class CaseForm(ModelForm): class Meta: model = Case fields = ["sex", "age"] With corresponding model: class Case(TimeStampedModel): id = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False ) user = models.ForeignKey( get_user_model(), blank=False, null=True, on_delete=models.SET_NULL) age = models.IntegerField("Age") SEX_CHOICES = [ ("male", "Male"), ("female", "Female"), ('', "Sex") ] sex = models.CharField("Sex", max_length=20, choices=SEX_CHOICES, blank=False) This displays a placeholder of 'Sex' for one field and I would like to display the a similar placeholder for 'Age'. One method I have seen is: class CaseForm(ModelForm): age = IntegerField(label='Age', widget=TextInput(attrs={'placeholder': 'Age'})) class Meta: model = Case fields = ["sex", "age"] However when this is rendered, although 'Age' is there as a placeholder, the field no longer behaves like an integer field. Any advice on the correct method appreciated -
How do I sync a docker volume to update when my local files are updated? Django, nginx
Sorry, it seems like answered question, but I couldn't find not outdated solution or the one that could help me (especially with django). I have to manually re-make volume so my docker server will update. My php friend told me I should make a synchronized volume, but I just don't understand how compose.yml volumes services: back: volumes: - blog-django:/usr/src/app - blog-static:/usr/src/app/static nginx: volumes: - blog-static:/usr/src/app/static db: volumes: - pgdata:/var/lib/postgresql/data/ volumes: blog-django: blog-static: pgdata: Project copied in volume by COPY . . -
Page not found (404)The current path, {% url 'post_detail' post.pk % }, didn’t match any of these
[hi i am new to django and i am facing a problem when using primary keys.project name is blog project and app is blog this is my code.] this is the screenshot of the error when i click on a heading:1 please help me #blog/urls.py from django.urls import path from .views import BlogListView,BlogDetailView urlpatterns = [ path("post/<int:pk>/",BlogDetailView.as_view(),name = "post_detail"), path('', BlogListView.as_view(), name = "home"), ] #blog/templates/home.html {% extends 'base.html' %} <style> .post-entry{ color:antiquewhite; } </style> {% block content %} {% for post in object_list %} <div class = "post-entry"> <h2><a href = "{% url 'post_detail/' post.pk % }">{{post.title}}</a></h2> <p>{{post.body}}</p> </div> {% endfor %} {% endblock content %} -
Can we add add objects to django queryset like we do to python list. I have an empty django queryset, now I want to add objects to it
This is how I have initialized an Empty Queryset now I want to add objects to it. How can I do that. from django.db.models.query import EmptyQuerySet