Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django cart quantity model for order and for item
thanks for your time. i got a shopping-cart app with Order->Pedido and Item models. And those are related through ManytoManyField. when the first time any user add a product to his cart the Item object gets created. So i set a quantity field on the Item model to get increassed +1 every time that Item has been ordered. So i could get how many times that item got ordered. i'm trying to get a field that shows me how many Items of that Item are in the cart at that order (and them sum and checkout the order). And a field to shows me how many of that item have already been ordered in all time. should i create a Quantity model? i've read some questions and still kinda lost. products/Models.py: class Produto (models.Model): model = models.ForeignKey(Modelo, on_delete=models.CASCADE, related_name='mod') nome = models.CharField(max_length=200) preco = models.DecimalField(max_digits=5, decimal_places=2) created_time = models.DateTimeField(auto_now=True) updated_time = models.DateTimeField(auto_now_add=True) shoppingcart/Models.py: class Item(models.Model): product = models.OneToOneField(Produto, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) date_ordered = models.DateTimeField(null=True) quantity = models.PositiveIntegerField(default=1) def __str__(self): return self.product.nome class Pedido(models.Model): ref_code = models.CharField(max_length=15) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(Item) date_ordered = models.DateTimeField(auto_now=True) shopping_cart/views.py: @login_required(login_url='/accounts/automatic') def add_to_cart(request, **kwargs): … -
If statement in template Django now
I have created 2 apps: 1. Score for uploading posts by users 2. Core for uploading items by users In the home.html I am trying to add a button only if there are posts submitted by user to appear Here is the template: {% if not posts %} <a href="{% url 'score:user-posts' item.designer.username %}"> <button style="margin-top: 10px;text-transform: none;" button type="button" class="btn btn-success btn-sm btn-block"> Click Here</button></a> {% else %} {% endif %} Here are the core app views.py: class HomeView(ListView): model = Item paginate_by = 12 template_name = "home.html" ordering = ['-timestamp'] here are the score post models: class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to="media") title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True, max_length=120) -
Error saving cidrfield field from django admin interface
The issue I am facing is trying to save a cidrfield (imported from netfields) in the djanog admin interface. I have the following models: from django.db import models from netfields import CidrAddressField # Create your models here. class Zone(models.Model): zone_text = models.CharField(max_length = 20, unique = True ) def __str__(self): return self.zone_text class Vlan(models.Model): zone = models.ForeignKey(Zone, on_delete=models.CASCADE) vlan_id = models.IntegerField(default = 0, unique = True ) subnet = CidrAddressField( unique = True ) def __str__(self): return str(self.vlan_id) I am able to create a new Vlan entry from the django shell: >>> v = Vlan.objects.create(zone=z, vlan_id="2", subnet="192.168.2.0/24") >>> type(v.zone) <class 'network.models.Zone'> >>> type(v.vlan_id) <class 'str'> >>> type(v.subnet) <class 'ipaddress.IPv4Network'> >>> But when I attempt to add a new Vlan entry via the django Admin interface, I receive the following error: InterfaceError at /admin/network/zone/1/change/ Error binding parameter 0 - probably unsupported type. Request Method: POST Request URL: http://127.0.0.1:8000/admin/network/zone/1/change/ Django Version: 3.0.6 Exception Type: InterfaceError Exception Value: Error binding parameter 0 - probably unsupported type. Exception Location: C:\Users\elijah\python_projects\project1\lib\site-packages\django\db\backends\sqlite3\operations.py in _quote_params_for_last_executed_query, line 141 Python Executable: C:\Users\elijah\python_projects\project1\Scripts\python.exe Python Version: 3.8.2 This django site is running on my local machine using sqlite3 as the DB. Any idea what I'm missing? Any help is greatly appreciated. -
How to add Data in Django Relation table?
I have 2 tables in my Database, first is city and the second is builder, I have some data store in my builder table, and the city name is stored in the city table. Now, When I will submit builder data then each builder can have multiple cities, so I want to create another table builder_city, where data will be store in this format id,city_id, builder_id, It means when I will submit my form then builder names will be store in builder table and the selected multiple cities from builder form will be store in builder_city table with builder_id and city_id. Please let me know how I can do this. I am doing this, Please check my views.py code.. def add_builder(request): city=City.objects.all() if request.method == 'POST': name = request.POST.get('name') slug = request.POST.get('slug') meta_title = request.POST.get('meta_title') meta_desc = request.POST.get('meta_desc') meta_keyword = request.POST.get('meta_keyword') bldlogo = request.POST.get('bldlogo') data = SubCategory(name=name, slug=slug, meta_desc=meta_desc, meta_title=meta_title, meta_keyword=meta_keyword, bldlogo=bldlogo) data.save() return redirect('/dashboard/builder') else: return render(request, 'adminpanel/builder/create.html', {'city':city}) -
Django Bootstrap Modal Ajax - 1st time it works perfectly, 2nd time - no luck
I am using Django 2.2 with Bootstrap. This is the approach used for Opening a modal window , User updates the data, User saves it Underlying table from where the window was opened is updated and modal window is closed Till here everything works perfectly, however, the issue occurs when you click the same button to open the window. Here when you click the button, nothing happens ! This is the javascript file. $("#modal-risk-profile").on("submit", ".form-risk-profile", function () { var form = $(this); $.ajax({ url:form.attr("action"), data:form.serialize(), type:form.attr("method"), dataType:'json', success: function(data) { console.log(data.form_is_valid); if(data.form_is_valid) { console.log(data.html_planner_client_list); $("#id_client_table tbody").html(data.html_planner_client_list); // if you remove this line, modal window appears without any issues $("#modal-risk-profile").modal("hide"); console.log("I have returned with success"); } else { console.log("I am in else"); $("#modal-risk-profile .modal-content").html(html_form); } } }); return false; }); The output of the html_planner_client_list is as follows: <tr> <td> Rajesh </td> <td> 01-04-2000 </td> <td> Bangalore </td> <td> ramachandran.test@gmail.com </td> <td> Salaried </td> <td class="text-center"> <button class="button-risk-profile btn btn-danger btn-sm py-0" style="font-size:0.9em" data-url="/client/riskprofileplanner/19/"> Take Questionnaire </button> </td> <td> Subramanian</td> <td class="text-left"> <a href="/client/client_select/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Select </a> <a href="/client/client_edit/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Edit </a> <a href="/client/client_report/19/" class="btn btn-primary btn-sm py-0" style="font-size: 0.9em;">Report </a> <button class="button-choose-planner … -
Django cannot find GDAL on windows 10 64 bit
I am using PyCharm and Python 3.8 - 64 bit. I am trying to learn to implement GeoDjango and Leaflet with a Postgis database. I have a postgresql database with postgis extension. I also have psycopg2 installed following the comments from this earlier thread of mine. psycopg2 not detected by postgres django In settings.py, DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my-database', 'USER': 'my-user', 'PASSWORD': 'my-password', 'HOST': 'localhost', 'PORT': '5432', } } When I try to run python manage.py makemigrations I get the following error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\HP\PycharmProjects\GeoDjango and Leaflet\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", … -
Django - Manually set the values of ManyToMany Field on form submit (multiple inputs to one field)
The hardest question i asked so far. I have a Book Model with a many to many relationship to my Tag model. I need to split the tags by type, in diferent inputs () and then mix all the inputs in the single ManyToMany Field of my book model. My Book Model: class Book(models.Model): project = models.ForeignKey(Project, on_delete=models.PROTECT, verbose_name="Proyecto") user = models.ForeignKey(UserSap, on_delete=models.PROTECT, verbose_name="Autor principal") authors = models.ManyToManyField(Account, blank=True, verbose_name="Otros Autores") title = models.CharField(max_length=220, verbose_name="Titulo del libro") editorial = models.CharField(max_length=220, verbose_name="Editorial") isbn = models.CharField(max_length=17, verbose_name="ISBN") publicationYear = models.CharField(max_length=4, verbose_name="Año de publicacion") tags = models.ManyToManyField(Tag, blank=True, verbose_name="Etiquetas") file = models.FileField(upload_to="archiving/", verbose_name="Libro (PDF)") created = models.DateTimeField(auto_now_add=True) product = models.CharField(default="book", editable=False, max_length=15) def __str__(self): return self.title def get_absolute_url(self): return reverse("book:book-detail", kwargs={"id": self.id}) MY Tag Model: Tag.tag mean the type of tag ( the rightmost column inputs represents the type of tags) class Tag(models.Model): name = models.CharField( max_length=100, verbose_name="Nombre de la etiqueta") tag = models.CharField(max_length=10, verbose_name="Tipo") def __str__(self): return f'{self.name}' def get_absolute_url(self): return reverse("tag:tag-detail", kwargs={"id": self.id}) My create View: I tryed doing this by querying the multiple inputs into the tables their scooped then got the objects and add em to the many to many fields before saving the whole new book in def … -
How to add a reply to a comment in a post section in Django
I am trying to add a reply to comments on a post section for a post I have commented out the reply that I have added in the views.py as it is not working at all The templates are working perfectly but with every new reply comment is added not a reply so the issue is with the views I guess I have added a reply section to the comment models as following: models.py class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey( User, on_delete=models.CASCADE) reply = models.ForeignKey( 'Comment', on_delete=models.CASCADE, null=True, related_name="replies") content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.post.title, str(self.user.username)) here is the views: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') #reply_id = self.request.POST.get('comment_id') comment_qs = None #if reply_id: #comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class …