Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF what's the difference between serializers(many=True) vs ListField(serializer())
When should I use each of the following? * MySerializer(many=True) * serializers.ListField(child=MySerializer()) -
Django fetch data from table that refers the given table as foreign key
I have seen several examples of using select_related to query foriegn key related data in queryset. Including this example. But I want to do it in reverse way as explained below. name = models.CharField(max_length=50) author = models.ForeignKey(Author) class Author(models.Model): name = models.CharField(max_length=50) I have seen queryset to fetch the data while querying the Book because Author is specified in books.Like this books = Book.objects.all().select_related("author") But I need to query Author and then get all the books related with it.Is there any way to do that. -
Page not found at /posts even though View, template and Url config in defined
I'm building a simple blog app and trying to use slugs in the URL. I have defined the URL as well as the view and the template, however when I try to access the URL /blog/posts, it throws a 404 that too from an entirely different view. All other URLs work, just having an issue with above mentioned one. url.py urlpatterns = [ path('',views.IndexView.as_view(),name='index'), path('create/',views.PostCreateView.as_view(),name='blog-create'), path('posts/',views.UserPosts.as_view(),name='user-posts'), path('<slug:slug>',views.PostDetailView.as_view(),name='blog-detail'), path('list/',views.PostListView.as_view(),name='blog-list'), path('<slug:slug>/comment/',views.create_comment,name='comment'), ] Associated Views in order class PostDetailView(LoginRequiredMixin,generic.DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' slug_url_kwarg = 'slug' slug_field = 'slug' class UserPosts(LoginRequiredMixin,generic.ListView): model = Post context_object_name = 'posts' template_name = 'blog/user_post_list.html' def get_queryset(self): posts = super().get_queryset() queryset = posts.objects.all(user= self.request.user) return queryset the 404 error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/posts Raised by: blog.views.PostDetailView No post found found matching the query template directory tree blog/ templates/ blog/ user_post_list.html Also earlier I had a problem with path('/list') as well however it got solved when I removed the '/' from the slug URL, I don't know why it worked, can anyone explain? -
DJANGO - How to display a text form field next to checked checkboxes
I am creating an application that allows you to add predefined services to an invoice. When creating a new invoice, you can select services using checkboxes. I would like to add the text field to specify the quantity after selecting the checkbox. So you check the checkbox and text field appears next to it where you can enter the quantity. I would like to store this data in the database after creating a new invoice. I am not sure how can I achieve this. Do I need JS or only Django is enough? models.py class Service(models.Model): nazwa = models.CharField(max_length=100) cena = models.FloatField() def __str__(self): return f'{self.nazwa} - cena: {self.cena}zł' class Invoice(models.Model): forma_platnosci_wybor = [ ('przelew', 'przelew'), ('gotowka', 'gotówka') ] numer = models.CharField(max_length=30) firma = models.ForeignKey(Company, on_delete=models.CASCADE) forma_platnosci = models.CharField(verbose_name='forma płatności', max_length=75, choices=forma_platnosci_wybor) data_badania = models.DateField() data_wystawienia_faktury = models.DateTimeField() usluga = models.ManyToManyField(Service, verbose_name='usługi') rabat = models.IntegerField(verbose_name='rabat [%]', blank=True, null=True) def __str__(self): return self.numer forms.py class NewInvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = '__all__' exclude = ['numer', 'data_wystawienia_faktury'] widgets = { 'usluga' : forms.CheckboxSelectMultiple, 'data_badania' : DateInput(), } -
Send CSV to JSON Converted data in django rest framework
I am trying to work on a directory in which the csv is read by pandas and then after applying some filters the data is converted into json and send the same to the frontend: Here's how I am doing it class TransportView(APIView): def get(self, request, format=None): state = request.GET["state"] city = request.GET["city"] data = pd.read_csv(r"abc.csv", error_bad_lines=False) data = data.fillna("-") data = data[(data["State"]=="foo") & (data["City"]=="bar")].reset_index().to_json(orient='records') print("data ", data) return Response(data) How can I do it more efficiently such that the data being sent is in much more cleaner Format? -
Insert data into sqlite using dump file
I have a mysql dump file and for some reason in need to migrate to django sqlite. Not sure how to restore the data using dump file in sqlite. Everywhere I can find restoring in mysql psql..... -
how to create serializer of registering new user
How can I write this code in a serialized view its code to register the new user but I don't know how to work with 2 models in same serializers. def createDonerView(request): template = 'doner/create_doner.html' form1 = CreateUserForm() form2 = CreateDonerForm() if request.method == 'POST': form1 = CreateUserForm(request.POST) form2 = CreateDonerForm(request.POST) if form1.is_valid() and form2.is_valid(): user = form1.save() profile = form2.save(commit=False) profile.user = user profile.save() return redirect('index') -
Django script does not refresh html page with jQuery
I have created a django app that give me the possibility to collect data (using a form) and display it in a table. In the table I have a button, "EDIT" that give me the possibility, using jQuery, to edit the value filled. To do that I have created a table using a includes html property as following: <table class="table table-sm" id="myTable" style="width:100%"> <thead> <tr> <th>Codice Commessa</th> <th>Ragione Sociale/Nome e Cognome</th> <th></th> </tr> </thead> <tbody> {% include 'commesse/includes/partial_book_list.html' %} </tbody> <tfoot> </tfoot> </table> The partial_book_list.html have the following code: {% for commessa in commesse %} <tr> <td>{{commessa.codice_commessa}}</td> <td>{{commessa.nome_cliente}}</td> <td> <button type="button" class="btn btn-warning btn-sm js-update-book" data-url="{% url 'book_update' commessa.id %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> </tr> {% endfor %} The edit button is linked to an ajax call that give me the possibility to modify the data. All works great but when I try to save the edit form instead refresh the partial_book_list.html, all data in table disappear and I have to refresh the page to show them again. Where is the issue in my code: var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { … -
How to configure my Burp suite to listen on port 8000?
I'm developing a website with Django so I need to analyze the request. For that how should I configure my Burp Suite. Now, I had set proxy on my browser as 127.0.0.1:8080 and Burp Suite is also on 127.0.0.1:8080 but it can't capture the request from the Django application which is running on 127.0.0.1:8000. How to intercept the request with Burp suite and how to configure the browser and Burp suite -
Django Select2 not working for formset when click on add more
I'm creating a formset in which one of the field in select2 field and when i clicked on add more, i'm cloning that row. All the other columns are cloning but the select 2 is not displaying. function newSelect2WidgetInFormset (cell, prefix) { var $cell = $(cell), $script = $cell.find("script"), $input = $cell.find("input[type=hidden][id^=id_]"), scriptText, newId, newScriptText; // Remove old container $cell.find(".select2-container").remove(); **scriptText = $script.text();** --------------------- This script was coming blank and it could not generate the select2 field newId = $input.attr("id"); console.log("Before", scriptText); newScriptText = scriptText.replace(/id_[\d\w\-]+/g, newId); $script.text(newScriptText); console.log("After", newScriptText); if (scriptText === newScriptText) { console.warn("New script and old have some code"); console.warn("Should had been changed to ", newId); } // Script evaluation forced evaluation is needed because // inserting elements with script tag does not make the browser // to execute them eval(newScriptText); // swal("Script", newScriptText, "info"); } Note:- We have recently updated the django_select2 from 4.2.2 to latest version. When i checked inside the code the Select2Mixin has the render method which appends render_js_code function s += self.render_js_code(id_, name, value, attrs, choices) But in the latest version, i couldn't find the render method and even the render_js_code. What is the replace of that and how can we create a … -
How to set different labels in django DateRangeWidget
I have a form in my project and I want to display a start and stop label on my templates, what I mean by that is I want the start label to be next to start dateinput and stop label to be next to stop dateinput below are my codes. filter.py from django_filters import widgets import django_filters class DuesFilter(django_filters.FilterSet): payment_date = django_filters.DateFromToRangeFilter( label='Date (Between)', widget=widgets.DateRangeWidget(attrs={'type':'date', 'class':'form-control'}) ) my template <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text">date</div> {{ form.payment_date }} </div> </div> </div> -
Receive a user input and triggered actions by a specific field changes using Django Signals
I have to received a user input, token and if any role/permission changes in the model, I have to blacklist the token. As per me, there will be a post_save signals where I will receive the input from user and check if that specific field [role_name/permission_name] change in the db, I should blacklist the token or do other stuff. Only if that field change then I should blacklist the token, not if another fields (i.e details) changes. class UserRole(models.Model): name = models.CharField(unique=True, max_length=100, null=False, blank=False, ) details = models.CharField(max_length=300,null=False, blank=False, ) permissions = MultiSelectField(choices=ROLES_RELT_PERMISSIONS,blank=False, null=False) objects = RoleManager() def __str__(self): return self.name ROLES_RELT_PERMISSIONS = [ ('create_user_role', ('Create User Role')), ('edit_user_role', ('Edit User Role')), ('delete_user_role', ('Delete User Role')) ] //Add signal only if role/permission change. Dont trigger if role_details change def expire_token(token): if token: //blacklist the token else: //invalid token Any inputs would be appreciated. thank you! -
Django forms auto Reload at night
I want to create a django form that auto-saves all the records in database at night with timestamp and reloads the fresh form for next day. Can you please suggest how can I be able to achieve it? -
ModuleNotFoundError: No module named 'distutils.util'
got a problem when creating requirement file for my project in Pycharm IDE. -
Optimize django query with Exists, Subquery and OuterRef
I need help optimize this django query . The code and use case is as follows: My code: user_enrolments = UserEnrolment.objects.filter( enrolment__enrollable__id__in=course_ids_taught_by_teacher, course_progresses__module_progresses__module=instance).only("id").annotate( submitted_attempt=Exists( AssignmentModuleProgress.objects .annotate(user=OuterRef('id')) .filter( module_progress=Subquery( ModuleProgress.objects.get(module=instance, user=OuterRef('user'))), is_submitted=True) )) return user_enrolments.filter(submitted_attempt=True).count() course_progresses - > Many to Many to UserEnrolment, module_progress - > Many to Many to CourseProgress and instance is current AssignmentModule in serializer iteration. I want to get the submitted users count in the serializer , so im using a serializer method field. To get the submitted users count, I want to check if an entry exists in AssignmentModuleProgress table with module_progress = ModuleProgress.objects.get(module=instance, user=OuterRef('user')) User is a field in UserEnrolments Table and user should refer to current user in the user_enrolments annotation iteration. Im returning the count after filtering True condition of is_submitted. As of now im getting the following error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
Why static files from node_modules don't work?
I have installed Bootstrap, jQuery and Popper.js by npm for my Django project. And my Django project doesn't load them. How can I fix that? -
Django runserver fails without any error message
I have been working a project using python3 and django. I'm using the debian environment. The problem is python3 manage.py runserver provides the following output. Watching for file changes with StatReloader Performing system checks... Using TensorFlow backend. Any ideas as to what might be causing this? I get this in terminal. No error message -
Check if Foreign Key is used; if not -> delete
I have a Model: class Author(models.Model): name = models.CharField(max_length=4000) class Book(models.Model): book_name = models.CharField(max_length=4000) author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=1,related_name="Author") now, if i want to delete an author i need the system check if that pk is not used as FK in another model. def delete_author(request, pk) auth = get_object_or_404(Author, pk=pk) ### here must check if is erasable before delete auth.delete() return render(request, '...') For example I have 2 Author: John and Mike and 1 book: Simple_book writed by John Author Mike can be erasable, John no Can someone help me? -
Which column will become foreign key when we made a compete table as a foreign key to one of the column of other table in Django?
class Webpage(models.Model): topic = models.ForeignKey(Topic) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage) date = models.DateField() def __str__(self): return str(self.date) Here in my accessrecord name column which column from Webpage table will become my foreign key?? Please explain how this is working. because in sql query we explicitly define which column is going to become foreign key. -
Cannot run Django app. ERR_CONNECTION_REFUSED
What I want to achieve I want to run a Django app by AWS EC2, Nginx and Gunicorn. The problem that is occurring I started Nginx and Gunicorn successfully (that was checked by systemctl status andps ax | grep gunicorn, respectively), but when I open http://<ElasticIP>/ from chrome, I get the following error. This site can’t be reached. <ElasticIP> refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED My /etc/nginx/nginx.conf is as follows. Also, I have opened 80th port. server { listen 80; server_name <Elastic IP>; root /usr/share/nginx/html; include /etc/nginx/default.d/*.conf; location /static { alias /usr/share/nginx/html/static; } location /media { alias /usr/share/nginx/html/media; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x _forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8000; } ... ... } I would be grateful if you could help me out. -
You are running 32-bit Python on a 64-bit OS error message when I try to run django project in vscode
what I'm wondering is I downloaded the python -64bit for mac OS. but It seems like it was working when i run the vscode for django project. I don`t know why that works like this. How can i change python -32bit to the one -64bit. I've already done redownload the python -64bit for mac os to solve this problem. But I couldn`t solve this problem. I want to give some advice from you. thank you. -
pipenv doesn't install django in ubuntu 19.04
Cannot install django using pipenvstrong text -
django.db.utils.IntegrityError: null value in column "created_by_id" violates not-null constraint
i am trying to add some values to my table by using manage.py shell and this is my model : class Posts(models.Model): title = models.CharField(max_length=90) post_type = models.CharField(max_length= 80) body = models.TextField(max_length=4000) img = models.ImageField(upload_to = "images/") created_by= models.ForeignKey(User,related_name='posts' , on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) then i got this : django.db.utils.IntegrityError: null value in column "created_by_id" violates not-null constraint -
CBV or FBV for this form
I would like to know your opiniom about which is the best practice in this particular case: I have a blog site and there is the feature for sharing a post by email: To do this I have a FBV and a GCBV (both work and behave the same). FVB: def post_share(request, post_id): post = get_object_or_404(Post, pk=post_id, status='publicado') post_url = request.build_absolute_uri(post.get_absolute_url()) if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): form.send_mail(post, post_url) return HttpResponseRedirect('/blog') else: form = EmailPostForm() return render(request, 'blog/post_share.html', {'post': post, 'form': form}) GCBV: class SharePostView(SingleObjectMixin, FormView): form_class = EmailPostForm template_name = 'blog/post_share.html' success_url = '/blog' context_object_name = 'posts' queryset = Post.published.all() def get(self, request, *args, **kwargs): post = self.get_object() context = {'post': post, 'form': self.form_class} return render(request, self.template_name, context) def form_valid(self, form): post = self.get_object() post_url = self.request.build_absolute_uri(post.get_absolute_url()) form.send_mail(post, post_url) return super(SharePostView, self).form_valid(form)` In one hand, I think FBV is more simple, in the other hand, I think GCBV is more 'profesional' What, in your opinion should be the best Django chioce? Thanks you! -
i cant login to my Django User credentials
I following the tutorial of https://developer.mozilla.org/id/docs/Learn/Server-side/Django/Authentication I already following that site step by step and now i have reached Login Template stage, but i've some problem that i cant login, Django tell me that 'Your username and password didn't match. Please try again. ' even though I login using valid credentials my login.html {% load static %} <html> <head> <title>Login Page</title> <link rel="stylesheet" type="text/css" href="{% static 'style login.css' %}"> <body> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <div class="loginbox"> <img src="{% static 'avatar.png' %}" class="avatar"> <h1>Login Here</h1> <form method="post" action="{% url 'login'%}"> {% csrf_token %} <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="{{ next }} Login"> <a href="">Don't have an account</a> </form> </div> </body> </head> </html>