Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django returns only the id field instead of the entire object when queryset is used in subquery
Let's say I have the following query in Django: qs = Product.objects.filter( pk__in=Book.objects.order_by("code", "-version").distinct("code"), release_year__isnull=False ) which reads: Out of the latest products, give me the ones with a release year. I'm curious why the subquery does NOT require me to convert the latest products to pk values like so: pk__in=Book.objects.order_by("code", "-version").distinct("code").values_list("pk", flat=True) Looking at the raw SQL subquery using qs.query, looks like this is done for me automatically: SELECT DISTINCT ON ("core_product"."code") "core_product"."id" # only the id field is returned FROM "core_product" ORDER BY "core_product"."code" ASC, "core_product"."version" DESC Is this stated anywhere in the docs? I'm wondering which one of these variations is considered "best practice" or if there's another a better alternative (should I use Django's Subquery expression anywhere?). The former solution is less verbose but the latter solution is more explicit. -
Access Ubuntu django server in VM from Windows
I have a Django server up and running in my Ubuntu VM using python manage.py runserver 0.0.0.0:8000 I can access this in the VM browser. When I try to access using Windows browser the connection is never established. How do I make this happen? -
Getting Type error Failed to fetch in fetch Api
I am getting an error in fetch API while calling the django server. The request used here is: async function analyse() { await fetch("http://localhost:8000/classify/", { method: 'POST', body: JSON.stringify({ premise: document.getElementById('pre').value, hypothesis: document.getElementById('hypo').value, }), headers: { "Content-Type": "application/json; charset=UTF-8", "Authorization":"Basic c2hhc2h2YXQ6cGFuZGV5 } }).then(function (response) { console.log(response); return response.json() }).then(function (text) { console.log(text); }).catch(err => { console.log(err) }) It is returning an error with Type Error. The request is getting to the django server and the response is printed to the terminal correctly. But it is not returning the response to the browser. def post(self, request): print(request.data) print(request.data["premise"]) print(request.data["hypothesis"]) data = [[request.data["premise"], request.data["hypothesis"]], ['i am good', 'I am great']] temp_data = pd.DataFrame(data, columns=['premise', 'hypothesis']) temp_dataset = MyDataset(temp_data, PredictorConfig.tokenizer, labels=False) temp_dataloader = DataLoader(dataset=temp_dataset, sampler=BatchSampler( SequentialSampler(temp_dataset), batch_size=8, drop_last=False), shuffle=False) temp_preds = submission_predict(PredictorConfig.model, temp_dataloader, PredictorConfig.device) print(temp_preds[0]) return JsonResponse({"result":temp_preds[0]}) What to do here? -
Django admin, page not found in custom view
I encountered very annoying problem. I have created my own AdminSite like this: from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistics/', self.admin_view(self.statistics), name='statistics'), ] return urls + my_urls def statistics(self, request): context = dict( self.each_context(request), ) return TemplateResponse(request, 'admin/statistics.html', context) I have created my own AdminConfig and assigned it into my INSTALLED_APPS, created html file, then in my root urls added it like this: urlpatterns = [ url(r'^admin/', admin.site.urls), ] I have logged in into my admin page and when I'm trying to open localhost:8000/admin/statistics I receive this: Page not found (404) Request URL: http://localhost:8000/admin/statistics/ Why this is happening? Did I miss something? -
Calculated fieds in python django
I have a Table in my database with fields id, body_temp, and status, and its defined by the following class: class Temperature(models.Model): ... id = models.AutoField(primary_key=True) body_temp = models.DecimalField(max_digits=3, decimal_places=1) status = models.CharField(max_length=20) ... the field body_temp will be populated by means of a form, on the other hand, I want the field status to store a string based on the value entered in the field body_temp. if the temperature value entered in the field body_temp is less than 38, I want the field status to store a string normal. However, if the temperature value entered in the field body_temp is greater or eaqual to 38, I want the field status to store a string suspect. How can I do this? -
How can the user view details of other users complaints in django
When a user clicks on the other users complaint, how can he view that particular complaints details without being able to edit it? when the user clicks on any one of the cards, a page with that complaints details should open but the user should not be able to edit it. What do I type into the view for that? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber forms.py: class DateInput(forms.DateInput): input_type = 'date' class ComplaintForm(ModelForm): class Meta: model = Complaint fields = '__all__' widgets = { 'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}), 'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}), 'eventdate': DateInput(), 'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}), 'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}), 'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}), 'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}), 'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}), 'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}), 'patient_problem': forms.TextInput(attrs={'placeholder': 'Enter Patient Problem'}), … -
FileNotFoundError: [Errno 2] No such file or directory: 'books.json'
I am new to Django I get an error file not found when trying to read a json file that is in the same directory as views.py # Load books from JSON file with open('/books.json') as file: books = json.load(file) def index(request): return render(request, 'books/index.html', books) -
How to make a view know when a model instance in another view is saved
I am working with an API that does not send the response directly(maybe that's an api standard). For a crude example: def callbackview(request): #This view will receive the actual required data from the api server, and save response to #the db(there might be a better way to do this) # Actually uses drf to parse/save the data ... return Response(...) def apisenderview(request): #send the api request resp=requests.get("https://api_url.com/api",{"callbackurl":"callbackview",...}) ... The issue is that the response received by resp in apisenderview is simply the server queue details. What I think I need is a way for apisenderview to know when the API server has sent a response to callbackview. A solution I am considering is: ... def apisenderview(request): #send the api request resp=requests.get("https://api_url.com/api",{"callbackurl":"callbackview"}) callbackinstance=None: while not callbackinstance: callbackqs=callbackmodel.objects.filter(queue_id=resp.queue_id) if callbackqs.exists(): callbackinstance=callbackqs.first() #Continue with view operations ... However, the solution above may have too many db calls(I haven't tested it yet).How do I optimize this process to ensure minimal apisenderview response time? -
How to remove duplicates in django /postgres while the primary key is a String
In the below table, id is my primary key , The item A with date 2021/07/22 is duplicated in the below , I want that to be removed. In short the combination of item and date should be unique id item date price qwtywte A 2021/07/22 102 afdsgfg B 2021/07/22 210 hgasdah A 2021/07/22 102 basjhjs A 2021/07/21 114 vsjdsjg B 2021/07/21 250 I am ok with solution from sql query or in django ORM query -
Django Elastic Beanstalk Deployment Error Due to INSTALLED_APPS in Settings
I'm deploying a Django application through the Elastic Beanstalk CLI but have an error with an app I include in the INSTALLED_APPS in the settings.py file. Here's the layout of my django project: django3 |--- manage.py |--- requirements.txt |--- .ebextensions |--- 01_python.config |--- appone |--- migrations |--- __init__.py |--- templates |--- index.html |--- __init__.py |--- admin.py |--- apps.py |--- forms.py |--- models.py |--- tests.py |--- urls.py |--- views.py |--- django3 |--- __init__.py |--- asgi.py |--- settings.py |--- urls.py |--- wsgi.py When I run the django project locally everything works fine, but when I attempt to deploy to Elastic Beanstalk I get this error: ModuleNotFoundError: No module named 'appone' This is preceded in the logs at some point with these lines: apps.populate(settings.INSTALLED_APPS) app_config = AppConfig.create(entry) so it seems it's attempting to make an entry for the appone app but the name for it in the apps.py I have is incorrect. My apps.py file is this: from django.apps import AppConfig class ApponeConfig(AppConfig): #default_auto_field = 'django.db.models.BigAutoField' name = 'appone' And my settings.py file INSTALLED_APPS is this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appone' ] I found some similar issues like this one: Django : Can't import 'module'. Check that module … -
Open source professional networking platforms like "LinkedIn" or "Xing"
Which open-source professional networking platforms like "LinkedIn" or "Xing" which built on using new technologies (Not PHP/WordPress). Open source should be built in the new latest technology that saves time and manpower efforts during customization, fast loading, database connectivity, etc. I would greatly appreciate it if you kindly give me some suggestions on this research data. -
Django Rest framework why to use [closed]
I want to know why to use Django rest framework even though I can use normal models print("hello world") -
Django rest framework: serializer does not include id field in response data
I am learning Django rest framework and have created the following serializer: class EventCreateSerializer(serializers.ModelSerializer): organiser = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Event fields = ['id', 'name', 'description', 'date', 'organiser'] def save(self, **kwargs): name = self.validated_data['name'] description = self.validated_data['description'] date = self.validated_data['date'] organiser = self.data['organiser'] organiser_account = Account.objects.get(username=organiser) if not organiser_account: raise serializers.ValidationError('Error setting the organiser field') event = Event.objects.create(name=name, description=description, date=date, organiser=organiser_account) event.save() return event Notice how 'id' is included as a field. Now I have the following view: class EventCreateView(APIView): permission_classes = [IsAuthenticated] def post(self, request, format=None): context = { 'request': self.request } serializer = EventCreateSerializer(data=request.data, context=context) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'fail': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) So when I make a post request to the appropriate url, I get back a response that include serializer.data. However, this does not contain the 'id' field (but it does contain the other fields). The model used has an automatically generated id field. I want the response to include the id field, how can I achieve this? -
Integrating a plugin in netbox
I am creating a plugin in netbox. I have run the setup.py file below as prescribed by the documentation from setuptools import find_packages, setup setup( name='netbox_ipdevcir_plugin', version='0.1', description='A plugin to add many2many models for IP Address, Device and Circuits', url='https://gitlab.openaccess.com', author='Author', license='Apache 2.0', install_requires=[], packages=find_packages(), include_package_data=True, zip_safe=False, ) and have gotten the following: root@username:/opt/netbox/netbox/netbox_ipdevcir_plugin# python3 setup.py develop running develop running egg_info writing netbox_ipdevcir_plugin.egg-info/PKG-INFO writing dependency_links to netbox_ipdevcir_plugin.egg-info/dependency_links.txt writing top-level names to netbox_ipdevcir_plugin.egg-info/top_level.txt reading manifest file 'netbox_ipdevcir_plugin.egg-info/SOURCES.txt' writing manifest file 'netbox_ipdevcir_plugin.egg-info/SOURCES.txt' running build_ext Creating /usr/local/lib/python3.8/dist-packages/netbox-ipdevcir-plugin.egg-link (link to .) netbox-ipdevcir-plugin 0.1 is already the active version in easy-install.pth Installed /opt/netbox/netbox/netbox_ipdevcir_plugin Processing dependencies for netbox-ipdevcir-plugin==0.1 Finished processing dependencies for netbox-ipdevcir-plugin==0.1 root@username:/opt/netbox/netbox/netbox_ipdevcir_plugin# I have then created models which i want now need to sync through the command ./manage.py makemigrations netbox_ipdevcir_plugin and i am getting (venv) root@username:/opt/netbox/netbox# ./manage.py makemigrations netbox_ipdevcir_plugin Traceback (most recent call last): File "/opt/netbox/netbox/netbox/settings.py", line 613, in plugin_config = plugin.config AttributeError: module 'netbox_ipdevcir_plugin' has no attribute 'config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/netbox/venv/lib/python3.8/site-packages/django/core/management/base.py", … -
How to use Django/Rest Framework to search a database table without specifying a column?
Initial question: Following the Django documentation, to get a QuerySet of blog entries from the year 2006, we can use filter() like so: Entry.objects.filter(pub_date__year=2006) Retrieving specific objects with filter, it is assumed that we know which column to search in. How can we search for an object if we do not know which column it could be in? For a small number of columns, we could chain the filters like so: Entry.objects.filter(column1='foo').filter(column2='foo') With +30 columns, this seems highly repetitive. What is a better way of doing this? A follow up question: Given that in urlpatterns we find the following path: path('foo/bar/<str:object>/', views.ViewObject.as_view()) And ViewObject uses the Rest Framework generic views: class ViewObject(generics.RetrieveUpdateDestroyAPIView): serializer_class = ObjectSerializer ... queryset = ? How can we construct the ViewObject view such that parameter <str:object> is used to search for a value in all columns of a database table? -
Django Restframework with nested json
Iam using Django with Restframework. Iam trying to get a json output from serializers in a nested manner with key as one of the fields from model. I acheived the nested JSON but the json key for them is troubling me. Here is my code and expected results out of it: Models.py class Tags(models.Model): tagId = models.CharField(primary_key=True, max_length=100, default=1) section = models.CharField(max_length=100,default=1) def __str__(self): return self.section class TagItem(models.Model): section= models.ForeignKey(Tags, on_delete=models.CASCADE,default=1,related_name="items") select = models.BooleanField(default=False) name = models.CharField(max_length=50) def __str__(self): return self.name serializers.py class TagItemModelSerializer(serializers.ModelSerializer): class Meta: model = TagItem fields = '__all__' class TagModelSerializer(serializers.ModelSerializer): items = TagItemModelSerializer(many=True) class Meta: model = Tags fields = ['pk','section', 'items'] Expected output: { "crafts" : { //craft is comming from Tag model's "section" "id": 1, "section": "crafts", "items": [ { "id": "10", "select": false, "name": "Wood", "category": "crafts" }, ] }, "states" : { "id": 2, "section": "states", "items": [ { "id": "20", "select": false, "name": "Andhra Pradesh", "category": "states" } ] }, "others" : { "id": 3, "section": "others", "items": [ { "id": "30", "select": false, "name": "Volunteer", "category": "others" } ] } } Current output: [ //cant get the key of Tag model's "section" { "pk": "1", "section": "states", "items": [ { … -
My form redirects the page to the API url used on the form (action="some url") after submitting, how to fix this? Django VanillaJS
This is what my page looks like: I have a sidebar which can change the contents of the page depending on the button clicked. When I click on About the page will look like this: So I made this with Vanilla JS using inner.HTML. PROBLEM: When I refresh the page, meaning the inner.HTML is not happening yet because I never clicked any buttons on the sidebar yet. My form submits properly and it does not redirect me to the API url used on the form. But, when I tried to click the About button and click Home button and try to submit the form again, it redirects me now to the API page used on the form. My guess is, there is something wrong with my vanillajs using inner.HTML. CODE looks like this: HTML: {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block script %} <script type="text/javascript" src="{% static 'js/cms/cms.js' %}"></script> {% endblock %} {% block style %} <link rel="stylesheet" type="text/css" href="{% static 'css/cms.css' %}"> {% endblock %} {% block content %} <div class="container"> <div class="sticky-sidebar-page"> <div class="sidebar"> <h3>Manage Site Contents</h3> <div class="list-group"> <button class="list-group-item list-group-item-action active" aria-current="true" onClick="showHomeContent()" id="homeButton">Home</button> <button class="list-group-item list-group-item-action" aria-current="true" onClick="showAboutContent()" … -
Django: Can't save file to FileField
According to Django Docs, I'm trying to save File or ContentFile to FileField. When I access FileField it doesn't give me a FieldFile proxy, so I don't have a save method like all examples. Can I use djangonic :) way to solve this? (Django 3.2) Model: class Report(InModelFileStorageMixin, models.Model): ... class InModelFileStorageMixin: file = models.FileField( _('Report File'), blank=True, null=True, ) My exception is: ipdb> obj.file.save *** AttributeError: 'FileField' object has no attribute 'save' -
How to avoid Django NoReverseMatch Error?
I am confused with Django redirect. The idea is to redirect users to an external URL, but I always get the NoReverseMatch Error. My urls.py from django.urls import path from . import views from django.views.generic.base import RedirectView path('home', views.home_view, name="home"), # redirect user from home to go-to-django path('go-to-django/', RedirectView.as_view(url='https://www.djangoproject.com/'), name='go-to-django'), # some dummy url my views.py from django.urls import reverse from django.shortcuts import redirect, render def home_view(request): return redirect(reverse('go-to-django')) -
Django - multiple queries with pagination
After updating from Django 1.9 to 3.2.5 my advanced search function doesn't work with pagination anymore. I have two search functions. One which is always available in the header to search for project names and is included in my base.html template. The other one is an advanced search function which allows to search for specific criterias e.g. department, project name, status, etc. all works fine as long as there is no pagination. the normal search function works with pagination but the advanced doesn't. The problem seems the return of the query, which returns one list for mutliple queries starting with q=['','','']. Because my form fields in my advanced search have different names e.g. qD,qS, etc. the parts of the list can't be properly assigned. url return when doing advanced search before changing page: http://127.0.0.1:8000/advanced_search/?csrfmiddlewaretoken=rzIvrOJdUMHwwxaSR18hy48mPTNCORXjaMYigqELXKRlKzNhBpEjbVSueQGHs7yl&qD=corporate&qC=&qN=&qT=&qS=&qA=&qCD= url return when doing advanced search after changing page: http://127.0.0.1:8000/advanced_search/?page=2&q=(None,%20%27corporate%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27,%20%27%27) here my django and html code: views.py # normal search def search(request): template = 'MAR_Projects/projects.html' query = request.GET.get('q') if query: filtered_projects = table_projects.objects.filter(Q(Project_Code__icontains=query) | Q(Project_Name__icontains=query)) else: filtered_projects = table_projects.objects.all().order_by('-Project_Creation') searchResultCount = filtered_projects.count pages = pagination(request, filtered_projects) context = {'items': pages[0], 'page_range': pages[1], 'query': query, 'searchResultCount':searchResultCount } return render(request, template, context) #advanced search def advanced_search(request): template = … -
The complaints on the view complaints page are not showing up
I am creating a complaint management system where users can enter their complaints as well as view and edit them and also view other users complaints. On the page where the users can view others complaint, no complaints or data is showing up. What do I do? This should be showing up : But this is what is showing up: My models.py: class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "msi.jpg", null = True, blank= True, upload_to= 'static/profileimages') first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: class OtherPeoplesComplaints(TemplateView): model = Complaint form_class = … -
Django makemigrations show no changes detected after table rename in mysql
I have a Django application with a My-SQL database. recently I alter the table_name with the help of MySQL query in the MySQL-shell, after this when I run makemigration and migrate command terminal says "No changes detected". how can i reolve this issue and create again this table with help of django makemigration and migrate. -
how to change booleanfield to use bootstrap switch toggle
I want to change booleanfield model to use bootstrap switch toggle. # model blank_on_off = models.BooleanField(default=False) If i click on the button like above, then blank_on_off which is false changes to true and if i click one more time then changes again false. I think I should use JavaScript, how should I approach it? Thanks. -
DateTime picker in pure Django
I need to have a picker for DateTimeField, but I dont really know how to do it. Ive tried admin widget but I think I did it wrong. The closest thing to a solution was: models.py class MyModel(models.Model): myfield = models.DateTimeField() forms.py class MyModelForm(forms.ModelForm): class Meta: widgets = {'myfield': forms.widgets.SplitDateTimeWidget( date_attrs={'type': 'date'}. time_attrs={'type': 'time'})} It shows me a working picker, but when I try to press save button it says me an error: AttributeError: 'list' object has no attribute 'strip' -
Why serialization in djano rest framework is costly in terms of performance?
class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() serializer_class=SalesDataSummarySerializer response = writeSerializedDataToCSV(response, headers, fieldnames,serializer_class.data) I am trying to convert response into csv and it takes around 5 minutes for 25k records, Where as the below code takes around 15-18 seconds, Here I am manually looping and creating a json. class SalesDataSummaryViewSet(viewsets.ReadOnlyModelViewSet): queryset=SalesDataSummary.objects.all() queryset_list=[] for data in queryset: queryset_dict={} queryset_dict['number']=data.number queryset_dict['name']=data.name queryset_dict['time']=data.time queryset_dict['code']=data.code queryset_dict['uuid']=data.uuid queryset_list.append(queryset_dict) response = writeSerializedDataToCSV(response, headers, fieldnames,queryset_list)