Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How destroy dynamic model?
I am looking for a way to dynamically destroy (delete) a dynamic model. I am creating a model via the type operator. Everything works perfectly. When I delete a model, I do the following sequence of actions: I get the model by calling: model = apps.get_model (app_label, name) unregister model from the registry of the admin site deleting the model: del model (own model factory) delete the model from the database: schema_editor.delete_model(model) (successfully) clear the application cache: apps.clear_cache() сlear ContentType сlear the cache of the admin site: reload (import_module (settings.ROOT_URLCONF)) clear_url_caches () But, after all these actions, the model surprisingly remains in the memory. For example, this can be seen in the nested form on the admin site. Am I doing something wrong? -
Structuring Django/React projects beyond simple CRUD app (Conceptual)
I have started a Django project with a couple apps, one of which contains my react. I would like to gain clarity on best practice/professional preference as it pertains to file structure and distinguishing views based on url in full stack apps that use Django and React. Right now, the only js file that seems to interact with the Django Rest API is called App.js, but I would obviously like to expand upon this and create different components that interact with my backend. Do I just fetch data from my api in each component file? Also, to create different views, it seems like in my index.js, I load the static file of the compiled webpack for my main.js. If I want to have different pages, would I need to compile a webpack in a main.js file for each page view? Let's say I want to create an about page and a homepage. Is it best practice to create two django apps that both have react in them, one to serve as the page view and one to serve as the homepage view? If not, what do you suggest? This is my App.js import React, { Component } from "react"; import … -
How to get count of for loop and store it into dictionary which is inside for loop
I am trying to get count of for loop inside each if condition if condition is satisfied it should get the count and store it in a dictionary with diffrent keys example code is given below but it gives me diffrent output not what i want def get(self, request, format=None): queryset = preshift.objects.filter(active=True,is_published=True,date_published=self.request.GET.get('date')).values() data = {} print('/////queryset_count///',queryset.count()) pre_shift_count = 0 for i in queryset: dt = i['date_published_local'].strftime("%H") if int(dt) in range(0,2): pre_shift_count+=1 print('///1////',pre_shift_count) data["zero-2"]= pre_shift_count else: data["zero-2"] = 0 if int(dt) in range(2,4): pre_shift_count+=1 print('///2////',pre_shift_count) data["two-4"] = pre_shift_count else: data["two-4"] = 0 if int(dt) in range(4,6): pre_shift_count+=1 print('///3////',pre_shift_count) data["two-5"] = pre_shift_count else: data["two-5"] = 0 return Response({"preshift":data}) it gives me output like this ('/////queryset_count///',4) (////1//,1) (////3//,0) (////3//,1) (////3//,2) (////3//,3) (////3//,4) (////3//,5) i have four records but it's printing 5 i don't have idea of how to get perfect count of for loop inside condition and i want to store data in dictionary like this { "preshift":{ "zero-2":1, "two-4":0, "two-5":4, } } -
displaying images in django database
I am pretty new to django and now I'm learning how to access images in database and display it using html. I want to show the images as elements of a list for further styling and making the page responsive but I don't want to write each and every image as a list item as there are more than 100 images in database. I've tried the below code but no progress. Please do suggest if any better way of doing it. I have image as a model in my models.py. <div class='gallery'> {% for x in photo %} <ul> <li><img class="images" src="{{x.image.url}}"/></li> </ul> {% endfor %} </div> -
Multiple Checkbox Form Fields with the Same Name in Django
I encountered a scenario where I have a list that I needed to pass over in a form, something like: {% for i in noTureFalse %} <input type="text" name="ids" value="{{ i }}"> {% endfor %} Then, in my view.py: ids = request.POST.getlist('id') for id in ids: print id It works totally fine for text, number, or these types of input fields. But in the case of the radio button like the following, how can I use this technique (as they already have some value fields)? {% for i in noTureFalse %} <div class="form group"> <label>Insert correct Ans: </label> <label for="True">True</label> <input for="True" type="radio" name="correctAns" value="True"> <label for="False">False</label> <input for="False" type="radio" name="correctAns" value="False"> </div> {% endfor %} Actually, I need to pass multiple values with the same name(maybe the list is a good option). -
Django admin page loses styling when travelled to from link
When I travel directly to the admin page of my django website by entering http://localhost:8000/admin/ in my address bar, the admin page is styled as it should be. However, I need to create a link in my navigation bar that takes the user to the admin page but when the admin page is accessed from this nav link the normal admin styling disappears even though it appears to take me to the exact same web address. [1]: https://i.stack.imgur.com/MrdOF.png When I inspect the site it instead seems to be recieving styling from my jquery mobile stylesheet instead. Any idea why this may be the case only when travelling to the admin address from the link? -
How to display a ForeignKey value?
I have got a model PurchaseOrder and Orderline. I can display all values from the OrderLine model, but can`t display the value assigned to the PurchaseOrder model. I have tried many combinations but they do not seem to work. Any ideas why? models.py class PurchaseOrder(models.Model): po_number = models.CharField(max_length=250) title = models.CharField(max_length=250, blank=True, null=True) class OrderLine(models.Model): purchaseorder = models.ForeignKey(PurchaseOrder,related_name="has_lines",on_delete=models.CASCADE) order_item = models.CharField(max_length=100, verbose_name="Line") views.py @login_required(login_url="/login/") def detail_order(request, purchaseorder_id): purchaseorder = PurchaseOrder.objects.get(pk=purchaseorder_id) orderlines = OrderLine.objects.all() purchaseorders = PurchaseOrder.objects.all() context = { 'purchaseorder': purchaseorder, 'purchaseorders': purchaseorders, 'orderlines': orderlines, } return render(request, 'accounting/orders/order_detail.html', context) order_detail.html <tbody> {% for orderline in purchaseorder.orderlines_set.all %} <tr> <td>{{ orderline.id }}</td> <td>{{ orderline.order_item }}</td> </tr> {% endfor %} </tbody> -
How to convert c++ to python [closed]
I am a new programmer in python. I am currently working in the project of converting c++ code to python. Could someone please tell me that What do we write instead of C++ header files in Python? Thanks. -
django media image url not showing up
I cant seem to figure out why my media images are not showing up in my template. I've read many articles but couldnt resolve. I have a model that has a relation with another model that has an imagefield class Ad(models.Model): company = models.ForeignKey(Company, related_name='ads', on_delete=models.CASCADE) title = models.TextField(max_length=240) text_description = models.TextField(max_length=2500) created_at = models.DateTimeField(auto_now=True) slug = models.SlugField(unique=False) The imagefield from Company model gets uploaded to folder called /logos/ that is under /media/ class Company(models.Model): logo = models.ImageField(blank=True, upload_to='logos/') And these are the settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] and urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomePage.as_view(), name='home'), ] if settings.DEBUG: urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Then im trying to loop through images and add to the template: {% for ad in object_list %} <div> {% if ad.company.logo %} <img src="{{ ad.company.logo.url }}" height="100"/> {% endif %} </div> {% endfor %} The result is a blank image (although the concrete object has an image) and the html renders such a tag <img src="/media/logos/security-265130_1920_IBWqpIq.jpg" height="100"> The image does exist and with the correct path and name as shown in rendered img tag. What am I doing wrong here? -
Django : class based view with multiple permissions
I am trying to create a class based view with different permissions per function. I have already created my permissions in a file that I import : utils.py from rest_framework.permissions import BasePermission from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView class IsOwner(BasePermission): """ Check if the user who made the request is owner. Use like that : permission_classes = [IsOwner] """ def has_object_permission(self, request, view, obj): # if request.method in permissions.SAFE_METHODS: # return True return obj.user == request.user class IsAdmin(BasePermission): """ Check if the user who made the request is admin. Use like that : permission_classes = [IsAdmin] """ def has_permission(self, request, view): return request.user.is_admin class BaseView(APIView): """ Check if a user is authenticated """ authentication_classes = [ TokenAuthentication, ] class AdminOrOwnerView(APIView): """ Check if a user is admin or owner """ authentication_classes = ( IsOwner | IsAdmin,) I want to create a class with different method. The GET method would allow admins to have a view of all users. The POST method would allow any user to connect. I have already created the serializer for each of these methods but I cannot assign different permissions per method. This is my class : class Users(APIView): def get(self, request): """Only for … -
Convert CSV file to MongoDB received as an input in a webapp
I how can I create a web app using React and Django that receives a CSV file as an input from the user and the web app should upload it as a MongoDB collection? I want this to be done automatically each time a user enters an input and uploads it. -
Django about Different templates have different results
I'm a super newbie, so please refer to this and read it. I am creating a bulletin board that communicates by DB <> API <> WEB method. Successfully import comments with comment.html. However, comments cannot be imported at {%inlude%} in boardapi_detail.html. Please refer to the picture at the bottom of the article. view.py class Commentapi_list(generic.TemplateView): def get(self, request, *args, **kwargs): data = { 'pk': self.kwargs['pk'], } url = 'http://127.0.0.1:8080/boardapi/' + str(data['pk']) + '/comment/' datas = requests.get(url, params=data).json() # print(datas) # print(type(datas)) df = pd.DataFrame(datas) clist = [tuple(r) for r in df.to_numpy()] print(clist) # print(type(clist)) return render(self.request, 'comment_form.html', { 'comment_list' : clist }) urls.py path('board/<int:pk>/', views.Boardapi_detail.as_view(), name="board_detail") comment.html {% if not comment_list %} <p class="text-center"> There is no comment. </p> {% endif %} <div style="margin:20px 0;"> {% for i in comment_list %} <table width="100%" cellpadding="0" cellspacing="0" class="tbl_replist" id="reply_list_layer"> <tbody> <tr style="height:45px;border-top:solid 1px #dddddd;"> <td style="padding-left: 10px;border-top: 1px solid #eee;width: 114px;">{{ i.1 }}</td> <td style="vertical-align: top;border-top: 1px solid #eee;padding: 10px 0;">{{ i.2 }} <span style="color: #999;font-size: 11px;display: block;">{{ i.3 }}</span> </td> </tr> {% if user.username == i.c_writer or user.is_staff %} <a href="/board/{{ i.0 }}/delete/" class="btn btn-outline-success">delete</a> {% endif %} </tbody> </table> {% endfor %} </div> boardapi_detail.html {% if not board_detail %} <p … -
Django Framework - How to enable user to overwrite existing values if values already exists
I am in a process to learn Django Framework and I want to understand how can I provide user with a pop up when data integrity is breached due to entry being placed for similar primary key. I've the following model. I've created a conjugate key of date and station. Suppose the user inputs another entry for same primary key I want to give user a choice to overwrite the existing values or cancel and return to form. I am confused based on the structure how can I achieve that? At following block from views.py else: context['form'] = properties_Form return render(request, "form.html", context) I tried adding context['form']= InputForm(instance=man_hour) but that didn't helped in order to replace. I went through update_or_create() method but I can't figure out how can I show a pop up in case a entry is being made for already existing primary key and provide user with an option to return to form or overwrite with new values. model.py from django.db import models from django import forms from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class ManHour(models.Model): class Meta: unique_together = (('date', 'station'),) station_choices = ( ('KHI','Karachi'), ('ISB', 'Islamabad'), … -
Django ForeignKey null=True IntegrityError
I am making a comment and reply system, where the comments should have parent as null in the database and the replies have the id of the parent comment. Below is my comment model, for your reference. When I am trying to post the comment via my form, I get IntegrityError. I tried putting both blank=True and null=True, but the error is still there. Also, I have figured out from the documentation and other articles that null=True should work, not blank=True. I cannot understand why I am getting the error and how to fix it. Thank you in advance. class BlogComment(models.Model): sno= models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User, on_delete=models.CASCADE) post=models.ForeignKey(Post, on_delete=models.CASCADE) parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp= models.DateTimeField(default=now) -
how can we update one to one relationship models db data from django?
i am new to django and i created onetoOneField relationship model with inbuilt User model of django but i cant figure out how can i update that model class table value. My model class category(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) TYPES = [ ("BASIC","BASIC"), ("PLUS","PLUS"), ("PRO","PRO") ] User_Type = models.CharField(max_length=40,choices=TYPES,default="BASIC") Product_Limit = models.IntegerField(default=0) Amount_Paid = models.IntegerField(default=0) Tried these 2 cases but getting some error #key = category.objects.update_or_create(id=request.user.id,User_Type= request.user.category.User_Type,Product_Limit=2,Amount_Paid=request.user.category.Amount_Paid) user = request.user.category.update_or_create(Product_Limit=10) -
Django: How to convert HTML date from request to Python string
I having trouble converting Date from HTML to Python String to use it in query I want to send query to MySQL with Date argument. roomList=Room.objects.raw( "select room.id " +"from room join client_room on room.id=client_room.room_id " +"where client_room.date_in>'"+request.GET.get("date_out")+ ..."#argument-date_out I recieve Date from HTML <p> <label>Enter first date</label><br> <input type="date" name="date_in" value="{{date1}}"/> </p> <p> <label>Enter second date</label><br> <input type="date" name="date_out" value="{{date2}}"/> </p> While printing Date alone it prints correctly print(request.GET.get("date_in")) 2021-04-01#Terminal But if trying to assign and/or concatenate it returns NoneType date=request.GET.get("date_in") print("Date is " + date) can only concatenate str (not "NoneType") to str #HTML Response -
pylint (pylint_django) does not work when --django-settings-module flag is specified
I am using newest version of pylint_django released few days ago: Package Version ----------------------------- ---------- pylint 2.7.4 pylint-django 2.4.3 pylint-plugin-utils 0.6 When I enabled pylint in VSC with pylint_diango extension I get this error Django was not configured. For more information runpylint --load-plugins=pylint_django --help-msg=django-not-configured I followed these instructions to fix that and added following lines to my settings.json: { ... "python.linting.pylintArgs": [ "--load-plugins=pylint_django" "--django-settings-module=wapp.settings" ] } However after specifying --django-settings-module=wapp.settings flag pylint stops working. My Django project structure (root directory which is opened in VSC) looks like this: . ├── ... ├── manage.py ├── media │ └── profile_pictures ├── requirements.txt ├── ... ├── venv └── wapp ├── asgi.py ├── __init__.py ├── __pycache__ ├── secrets.py ├── settings.py ├── urls.py └── wsgi.py I've also tried to specify DJANGO_SETTINGS_MODULE environment variable but it seemed to have no effect. I've also tried to run pylint directly from command line to see if the flags are working. When I run pylint path/to/some/python_file.py linter produced correct output, but when I tried pylint --load-plugins=pylint_django path/to/some/python_file.py I got an error ModuleNotFoundError: No module named 'wapp'. Does anyone stumbled upon similar problem? -
Storing python list in django model using sqlite
I have a python list of integers and want to store it in an sqlite db. myList = [T1_sum,T2_sum,T3_sum,T4_sum,T5_sum,T6_sum,T7_sum,T8_sum,T9_sum,T10_sum] sortedlist = sorted(myList, reverse=True) print(sortedlist) How can I make a django model that will sort this list? -
Django dynamic URL dispatcher within javascript
Im trying to have a dynamic url dispatcher such as: "{% url 'url_name' 'variable' %}" where variable is set dynamically within my javascript. What I want to do is basically redirect to a different page when a <select> value is changed. $(document).ready(function() { $('#select').change(function() { var id = $('#select').val(); window.location.replace("{% url 'url_name' 'id' %}"); }); }); I can't do it with a simple string concat as such: "{% url 'url_name' '" + id + "' %}" as it returns this error Reverse for 'url_name' with arguments '('" + id + "',)' not found. The select itself is being filled with backend data: <select id="select"> {% for item in list %} <option value="{{item.id}}">{{item.name}}</option> {% endfor %} </select> I cant figure out what the syntax for this is. -
Connect ML model to Django
I created a LDA model in a Jupyter notebook and I want to know how to connect that code for different databases in a Django web app. I don't want to pass the model as a .pkl because I want to train the model with different data which will be inputed by the end user. Also, I need to display in the web app the diagrams I generated in the Jupyter notebook, and don't know how. -
How to show results by clicking an html button and run paramiko python script and show results in html table using django? I'm absolute beginner
in the first, I'm an absolute beginner with Django and need to do a basic web to get results by clicking on the HTML button and that will execute the python code and showing the results in each row of the HTML table so the result, for example, Diyala will update the 5Mbps to the real speed from python script and the Kut also and so on for all row. the image below showing the website and get traffic button enter image description here can anyone help me, please here is my python code import paramiko def traff(ipaddr, uName, pWord): Baghdad = paramiko.SSHClient() Baghdad.set_missing_host_key_policy(paramiko.AutoAddPolicy()) Baghdad.connect(ipaddr, username=uName, password=pWord) stdin, stdout, stderr = Baghdad.exec_command('queue type print from=Internet-P20 value-list') for line in stdout: first_line = stdout.readlines()[1].rstrip().strip() print("Baghdad INT:", first_line[10:]) Baghdad.close() # print("Baghdad INT:") traff('172.22.1.86','user', 'pass') # print("BAGHDAD FNA P20") Baghdad = paramiko.SSHClient() Baghdad.set_missing_host_key_policy(paramiko.AutoAddPolicy()) Baghdad.connect('172.22.1.86', username='user', password='pass') stdin, stdout, stderr = Baghdad.exec_command('queue type print from=FNA-P20 value-list') for line in stdout: first_line = stdout.readlines()[1].rstrip().strip() print("Baghdad FNA:", first_line[10:]) Baghdad.close() # print("BAGHDAD CDN P20") Baghdad = paramiko.SSHClient() Baghdad.set_missing_host_key_policy(paramiko.AutoAddPolicy()) Baghdad.connect('172.22.1.86', username='user', password='pass') stdin, stdout, stderr = Baghdad.exec_command('queue type print from=CDN-P20 value-list') for line in stdout: first_line = stdout.readlines()[1].rstrip().strip() print("Baghdad CDN:", first_line[10:]) Baghdad.close() # print("BAGHDAD GGC P20") Baghdad = … -
Django form - get field from model
I printet a form where a customer choose a product, is it possible to print in a table: Product Number | Product (formField) | Quantity (formField) | Price how can I just print Product Number and Price as text which related to an instance of a form field? The form fields are already printed with an instance of products. -
How can I filter __in django ORM by records list?
I expect query like this: SELECT field1, field2, field3 FROM mytable WHERE (field1, field2) NOT IN( (1, 1), (2, 2) ); django==1.9.13 My current solution is: qs = MyTable.objects.all() for (field1, field2) in data: # List[Tuple[int, int]] qs = qs.exclude(field1=field1, field2=field2) -
How to print html invoice in django [closed]
How to print html invoices in django web application without dialogue box? I have already done exporting html to pdf using weasyprint. But its response populates a new window. I want print it without any dialogue box or anything. -
Django RestAPI - AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned
I am New to Django Rest Framework. And Am trying to Build RESTapis for my project. However I am getting following error - AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'rest_framework.utils.serializer_helpers.ReturnDict'> Underlying code generating this error is as follows - View Details are as follows - class SymbolInformation(APIView): ''' Returns the Symbol Information ''' def get(self, request, symbolname='NIFTY50'): # Capturing Inputs in Appropriate Cases symbolname = symbolname.upper() (companyname, symbol, tablename, close, change, returns, upperband, lowerband, has_fno, weekly_expiry, weekly_future, lotsize, isIndex, stepvalue) = get_symbol_details(symbolname=symbolname) data = SymbolInformationSerializer() print(companyname, symbol, tablename, close, change, returns, upperband, lowerband, has_fno, weekly_expiry, weekly_future, lotsize, isIndex, stepvalue) data = {'companyname': companyname, 'symbol': symbol, 'tablename': tablename, 'close': close, 'change': change, 'returns': returns, 'upperband': upperband, 'lowerband': lowerband, 'has_fno': has_fno, 'weekly_expiry': weekly_expiry, 'weekly_future': weekly_future, 'lotsize': lotsize, 'isIndex': isIndex, 'stepvalue': stepvalue} print(data) output = SymbolInformationSerializer(data) print(output.data) return(output.data) Actual data returned by the get_symbol_details function is as follows - NIFTY 50 NIFTY NIFTY 14504.80 194.00 1.36 15955.28 13054.32 True True False {0: 75, 1: 75, 2: 75} True 50 data dictionary is as follows - {'companyname': 'NIFTY 50', 'symbol': 'NIFTY', 'tablename': 'NIFTY', 'close': Decimal('14504.80'), 'change': Decimal('194.00'), 'returns': Decimal('1.36'), 'upperband': 15955.28, 'lowerband': 13054.32, …