Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selected item changes after sort
I am making Django app and i have a quesiton i have made a select menu to sort by prices. When I click submit button it sorts but it also go back to the default selected item. views.py def sortView(request): if request.method == "GET": try: min_price = int(request.GET.get('min-price')) max_price = int(request.GET.get('max-price')) items = Item.objects.filter(Q(price__gte=min_price) & Q(price__lte=max_price)) except: sorting_method = request.GET.get('select') if sorting_method == 'v1': items = Item.objects.order_by('price') elif sorting_method == 'v2': items = Item.objects.order_by('-price') print(sorting_method) return render(request, 'shop/sort.html', {'items': items}) HTML: It is in a 'form' so it is not the issue. <label class="sort__dropdown" for="cars">Sorting method</label> <select name="select"> <option value="v1">Price: low to high</option> <option value="v2">Price: high to low</option> </select> <button class="sort__submit">SORT</button> -
How To Effectively Serve React Files on The Same Port as Python Backend
I've created a backend with Python's Django that effectively runs a single API page on port 8000. I've also created a frontend that effectively renders a single page on port 3000. My goal is to have my Django serve my React files all on port 8000. To try and achieve this, I added the following to my settings.py REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = [ os.path.join(REACT_APP_DIR, 'build', 'static'), ] So, I ran npm run build in my frontend, and then ran python3 manage.py runserver 0.0.0.0:8000 where my manage.py is located; however, the npm build is still on the port 4000, and my Django is still rendering its files on port 8000. Thanks, if you could let me know the right way, or point me in the right direction, that would be great! Happy coding. -
Deploying Django website on Host Monster shared account
How can I deploy my Django website on host monster account? I know it can be on a shared host monster, but I cant find a way to push it into production. -
How to pass foreign key from form in Django
Used FlatAndMeter as foreign key in Rented in new function flat variable stores the id(primary key for FlatAndMter key -
A Django view is being called when I don't want it to be - why?
I am working on the cs50 web development Network assignment. Essentially it is a barebones twitter copycat. I have an issue where a view from views.py is being called when I do not intend it to be called. I know below I am posting more than is needed of my code below, but I feel I need to since I don't know where the problem area is. The views.py function follow_count() is being called eventually when I call the index view but cannot determine why. I.e. it is called every time the homepage is loaded. I do not want it to be called until it is specifically called by the clicked event listener in the js file. I cannot figure out what is causing follow_count() to run early, every time I load the index view. As I follow the path of different functions calling each other, it doesn't appear that anything is calling follow_count() yet it runs anyway. views.py: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render from django.urls import reverse from .models import User, Post, Profile def index(request): print("index running in python") if request.method … -
ckeditor from id not loading in insertAdjacentHTML
Thanks in advanced I want to have ckeditor comment box inside replay textarea and its not loading. every thing load textarea loads but ckeditor not loading with that id i think it loads once at page render. Before click on replay enter image description here after clicking on replay button form appears enter image description here my ckeditor main comment form enter image description here my comment form javascript <script> function formExit() { document.getElementById('newForm').remove(); } function myFunction(id) { if (document.contains(document.getElementById("newForm"))) { document.getElementById("newForm").remove(); } var a = document.getElementById(id); a.insertAdjacentHTML('afterend', ' \ <form id="newForm" method="post"> \ <div class="re_form"> \ <h2>Replay:</h2> \ <button type="button" class="btn re_form_close bg-red" onclick="formExit()"> \ Close \ </button> \ <p> \ <select name="parent" class="d-none" id="id_parentt"> \ <option value="' + id + '" selected="' + id + '"></option> \ </select> \ </p> \ <p> \ \ <textarea placeholder="Comment here" name="body" id="id_body" class="re_form_textarea"></textarea>\ </p> \ {% csrf_token %} \ <button type="submit" class="btn btn-primary btn-lg btn-block bg-olive">Submit</button> \ </div> \ </form> \ '); } $('#myForm').trigger("reset"); </script> at this above line see id="id_body" here ckeditor loads but it showing empty textbox without ckeditor <textarea placeholder="Comment here" name="body" id="id_body" class="re_form_textarea"></textarea>\ my replay form <button class="bg-yellow btn" onClick="myFunction({{ node.id }})">Reply</button> -
I created a custom Signup and Sign in form, and model to store a new user. I can't do login in django using custom login template form?? plz suggest
which are the best option to create my own user's register model and login models and functionality, please suggest to me one best and simple way ? and how to validate forms? I tried and created signup forms, models and login. signup is worked but I don't know how to do login. So I need help to do these functionalities. -
query set lost when page changes in Django
I created a search system for my objects called Property and it filters and search through my objects well in first page but when I change pagination or ordering or changing page all filters gone and it sends all objects to template is there anyway to fix this? here is my code views.py class SearchView(ListView): model = Property template_name = 'property/properties-list.html' context_object_name = 'properties' ordering = '-pub_date' paginate_by = 8 def get_context_data(self, *args, **kwargs): context = super(SearchView, self).get_context_data(*args, **kwargs) """somthing""" return context def get_paginate_by(self, queryset): if self.request.GET.get("paginate_by") == "": return self.paginate_by return self.request.GET.get("paginate_by", self.paginate_by) def get_ordering(self): ordering = super(SearchView, self).get_ordering() if self.request.GET.get('sort_by') == "Name": return ('-title') elif self.request.GET.get('sort_by') == "Price": return ('-price') elif self.request.GET.get('sort_by') == "Date": return ('-pub_date') else: return self.ordering def get_queryset(self): location = self.request.GET.get('location') category = self.request.GET.get('category') look_for = self.request.GET.get('look_for') if location or category or look_for: if look_for == '' and category == '': queryset = Property.objects.filter(Q(city__icontains = location)) elif look_for == '': queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category)) elif category == '': queryset = Property.objects.filter(Q(city__icontains = location) & Q(property_status = look_for)) else: queryset = Property.objects.filter(Q(city__icontains = location) & Q(category__slug = category) & Q(property_status = look_for)) else: queryset = Property.objects.all() return queryset Obviously I'm new … -
slug not auto generate after add page in django
I tried to add page for posts blog article for my django site.But it's slug model is not autogenerate after add it into the add post page but it work well in admin page. example in title field when i type how to master python fastly it will auto generated in slug field with "-" in only admin page.but when I type same thing on add post page it won't generate slug automatically. mycode models.py from django.db import models from django.contrib.auth.models import User from django_summernote.fields import SummernoteTextField from django.urls import reverse from django.template.defaultfilters import slugify STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) title_type = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home') views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' admin page And add post page -
Как добавить форму в django, для добавления пользователем разного товара? [closed]
models - тут несколько моделей и не понимаю как их перевести в View и на сам сайт class Product(models.Model): class Meta: abstract = True category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.CASCADE) title = models.CharField(max_length=255,verbose_name='Наименование') slug = models.SlugField(unique=True) image = models.ImageField(verbose_name='Изображение') description = models.TextField(verbose_name='Описание', null=True) price = models.DecimalField(max_digits = 9, decimal_places=2,verbose_name='Цена') class Notebook(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') Processor_freq = models.CharField(max_length=255, verbose_name='Частота ЦП') class SmartPhones(Product): diagonal = models.CharField(max_length=255, verbose_name='Диагональ') display = models.CharField(max_length=255, verbose_name='Тип дисплея') sd = models.BooleanField(default=True) -
beat: Connection error: Error while reading from socket: (104, 'Connection reset by peer')
I am deploying my Django backend on Heroku and I have used celery and Redis as a broker. But I am getting these errors on the worker log: 2021-08-23T17:43:05.148602+00:00 app[worker.1]: [2021-08-23 17:43:05,148: ERROR/Beat] beat: Connection error: Error while reading from socket: (104, 'Connection reset by peer'). Trying again in 32.0 seconds... 2021-08-23T17:43:35.862615+00:00 app[worker.1]: [2021-08-23 17:43:35,862: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-52-22-18-101.compute-1.amazonaws.com:30320//: Error while reading from socket: (104, 'Connection reset by peer'). 2021-08-23T17:43:35.862624+00:00 app[worker.1]: Trying again in 32.00 seconds... (16/100) setting.py: CELERY_BROKER_URL = 'redis://:*******.compute-1.amazonaws.com:port' CELERY_RESULT_BACKEND = 'redis://:***********.compute-1.amazonaws.com:port' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SELERLIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' BROKER_POOL_LIMIT = None celery.py : from __future__ import absolute_import from datetime import timezone import os from celery import Celery from django.conf import settings from celery.schedules import crontab, schedule # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'NewsApi.settings') app = Celery('NewsApi') app.conf.beat_schedule = { 'add-every-1-hour': { 'task': 'Api.tasks.task_news_update', 'schedule': crontab(minute=0, hour='*/1'), } } app.conf.update(timezone = 'Asia/Kolkata') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) -
How to set entry point after building the image in docker?
I'm trying to dockerize my django application and my Django has a dependency with GDAL and I added the dependency command in Dockerfile. The content in Dockerfile FROM ubuntu RUN apt-get update RUN apt install python -y RUN apt install python3-pip -y RUN apt install python3-dev libpq-dev -y RUN apt-get install gdal-bin RUN apt-get install libgdal-dev RUN apt install sudo WORKDIR /app COPY . /app RUN pip3 install -r requirements.txt ENTRYPOINT ["python3","manage.py" , "runserver" , "0.0.0.0:8000"] So, the problem here is that 6th line will ask for timezone like to select from 1-99 how can I pass those too as an argument in this file. So, to solve the above issue I remove line 6 and 7 and also the last line and installed it via docker run -it <image_name> and I committed it to a new image and now I can't execute the command I need which is python3 manage.py runserver 0.0.0.0:8000. -
Forwading ManyToMany model field in django-autocomplete-light
models.py class InvestmentGroup(models.Model): name = models.CharField(max_length=200, blank=True, null=True) persons = models.ManyToManyField('Person', blank=True, related_name='investment_groups') lead_investor = models.ForeignKey( 'Person', blank=True, null=True, on_delete=models.CASCADE, related_name='lead_investment_groups' ) forms.py class InvestmentGroupModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(InvestmentGroupModelForm, self).__init__(*args, **kwargs) class Meta: model = models.InvestmentGroup fields = '__all__' widgets = { "lead_investor": autocomplete.ModelSelect2( url="lead-investor-autocomplete", forward=["name"] ) } AutoCompleteview class LeadInvestorAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return models.Person.objects.none() qs = models.Person.objects.all() persons = self.forwarded.get('persons', None) print(persons) # Output: [] if persons: qs = qs.filter(person__in=persons) return qs I am getting empty values if I forward many to many field like this but works for other fields like name or foreign keys. Is it possible to forward ManyToMany field? -
Pass searched query to another view
I am building a small and simple Question and Answer Web App and I am trying to implement a search page. I have successfully created a search page. When i search question title than results are showing fine below the search field. BUT I am trying to show the answers of the searched tag on another page. I am trying to put a link below all the results to show the answers of the searched query, but still unable to make it. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) quest = models.ForeignKey(Question,on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def search(request): query = request.GET.get('q') answer = '' objs = '' if query: objs = Question.objects.filter(tags__name__icontains=query) answer = Answer.objects.filter(quest__tags__name__icontains=query) context = {'objs': objs,'answer':answer} return render(request, 'search.html', context) search.html <form action="{% url 'search' %}" method="get"> <input name="q" type="text"> {% for qas in objs %} {{ qas.title }} {% endfor %} {% for ans in answer %} {{ ans.ans }} {% endfor %} This view is showing answers in single page ( In searched pages ). I was thinking about creating a new view which will associate with the search view and will pass the … -
I need to override the save method for a specific model in django model(admin section)
I need to override the save method in the admin section. its related to documents. I need the save button to update some fields in database for me and beside that to send an email to the user that I have choosed .the model section is like this: class Documents (models.Model): applicant_email = models.EmailField(max_length=254) user_email = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) request_title = models.CharField(max_length=500) DOC_STATUS = ((0, 'Sent'), (1, 'Uploaded'), (2, 'Done')) request_status = models.SmallIntegerField(choices=DOC_STATUS) class Meta: verbose_name_plural = "Document Request" and here is the admin section: @admin.register(Documents) class DocumentsAdmin(admin.ModelAdmin): list_display = ('applicant_email','request_title', 'user_email','request_status') Where should I override the save method? in model section or in the admin part? and what's the code that do this? A complete and accurate answer would be appreciated. thanks -
Get all the data from model of searched tag on another page
I am building a Simple Question and Answer Web App and I implement a feature of search tags and it will show all the questions associated with it. And Now I am trying to show all the data of models in other page which is attached with that searched tag. Then I make a query of another model with searched tag but it is showing. Field 'id' expected a number but got 'first_post'. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') tags = TaggableManager() class Answer(models.Model): answer_user = models.ForeignKey(User,on_delete=models.CASCADE) quest = models.ForeignKey(Question,on_delete=models.CASCADE) body = models.CharField(max_length=30) views.py def search(request): query = request.GET.get('q') answer = '' objs = '' if query: objs = Question.objects.filter(tags__name__icontains=query) answer = Answer.objects.filter(quest=query) context = {'objs': objs,'answer':answer} return render(request, 'search.html', context) When i run this then it is showing Field 'id' expected a number but got 'first_post'. What i am trying to do :- I am trying to make a page of search and if i search a tag then a link of another page of all the answers of the searched tags, But i have no idea how can i attach two views so one page can show results and another can show answers. Any … -
Django ORM filter by singular field name
Is it possible to filter a model by some additional/singular version of field name? For example, using model like (where authors is CharField which contains python-list, e.g. ['Johnny']): class Movie(models.Model): title = models.CharField(max_length=100, null=False, blank=False) actors = models.CharField(max_length=250, null=True, blank=True) And query something like Movie.objects.filter(input), where input is <QueryDict: {'actor': ["['Johnny']", "['Pablo']"]}> Anyone has idea how to solve it? Thanks in advance. -
I'm working on a website similar to flat.io, what do these characters signify? [closed]
I'm working on a website similar to flat.io, I wanted to know, what do these string of characters signify and why are they displayed when a user creates a new document? -
How to use multiple toggle switches created dynamically?
I am a beginner in Frontend. I am implementing toggle switches in HTML,CSS and Vanilla Javascript. Structure: I create an HTML with "n" number of rows depending on the data in my django database. Each row has some data like name, id, status. Status column has toggle switches for each row. I have implemented the toggle switch which works fine for one single toggle switch. Problem: When there are multiple rows, and hence, multiple toggle switches, only the first toggle switch is getting toggled not the others. When I click on other toggle switches then also the first one gets triggered. I want all toggle switches to work separately and to detect it in my vanilla javascript. What I know: I know that we need unique id for each toggle switches but I don't know how to do that when I don't know how many rows I will have and how to detect all of them in JS code. Code: Here is the link to my codepen for this problem: ToggleSwitch Any help will be appreciated. Thank you in advance!. -
I can`t reorder apps in Djnago-admin
I can`t admin apps reorder my apps. In django admin home I have the message "Site administration You don’t have permission to view or edit anything." DEFAULT_APPS = ( 'admin_reorder', ) MIDDLEWARE = [ 'admin_reorder.middleware.ModelAdminReorder', ] ADMIN_REORDER = ( "apps.accounts", "apps.questions", "apps.exams", "apps.settings" ) -
How to serialize the aggregated record in Django rest framework?
model class Metric(models.Model): date = models.DateField() channel = models.CharField(max_length=50) country = models.CharField(max_length=10) os = models.CharField(max_length=10) impressions = models.IntegerField() clicks = models.IntegerField() def __str__(self): return "{} - {}".format(self.date, self.channel) My view class MetricViewSet(viewsets.ModelViewSet): serializer_class = MetricSerializer queryset = Metric.objects.all() filter_backends = [DjangoFilterBackend] filterset_class = MetricFilter My serializer class MetricSerializer(serializers.ModelSerializer): class Meta: model = Metric fields = '__all__' I need to group by one or more columns: date, channel, country, operating system and serialize it. Can someone help me with how I can do it? -
Override url.html in Django Admin
I have overridden the template url.html(template path: /admin/widgets/url.html) file of Django Admin. Now I need to keep that overridden file in my project folder so that whenever the functionality of url.html file is needed, the admin app should look into the overridden template(present inside the project folder) but not the template from Django Admin templates present inside the site-packages folder. Here is my settings.py file settings for templates: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [ os.path.join(BASE_DIR, "company", "app2"), os.path.join(BASE_DIR, "company", "app2", "templates"), ], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] I have placed the overridden file in the following path in my project: compnay -> app2 -> templates -> admin -> widgets -> url.html url.html is present in the widgets folder. The changes made in the overridden template aren't being reflected in the Django Admin UI(For example, in the url.html file, I kept target="_blank" attribute inside the anchor tag to open the corresponding link in a new tab. These changes aren't being reflected.). So, I think it's not taking overridden template present inside my project. What should I do to take the overridden url.html file present in my project folder? -
Django money and ordering by min-max price
Hello i am making Django e-commerce app and i have a problem i wanted to make sorting thing. The problem is i do not know how to get prices between min-price - max-price and filter items. HTML: <div class="sort__prices"> <input class="sort__min-price" type="number" name="min-price" placeholder="minimum price"> <input class="sort__max-price" type="number" name="max-price" placeholder="maximum price"> </div> <button class="submit">sort</button> views: def sortView(request): if request.method == "GET": min_price = request.GET.get('min-price') max_price = request.GET.get('max-price') items = Item.objects.all().filter(price=min_price) return render(request, 'shop/sort.html', {'items': items}) -
djanog-machina search returns no result
I have followed all the steps given in this Tutorial but the search feature for my project is not working. Whereas the example project given by django-machina is working fine with search. So can someone tell me what is the missing thing. I have also rebuild and updated the index. But still my search is not giving any results. It is always 0 results with no error. -
How do django ORM functions interact with db and parse sql code?
I'm somewhat new at programming and just for fun, tried to figure out how the django library works. I went to see how to ORM functions are implemented. I followed the functions to BaseManger, which inherits from Generic[_T]. But then I got stuck. Here's what is in BaseManager for something like get() def get(self, *args: Any, **kwargs: Any) -> _T: ... I assumed something is happening in the parent class Generic, but this is what I got: class Generic: """Abstract base class for generic types. A generic type is typically declared by inheriting from this class parameterized with one or more type variables. For example, a generic mapping type might be defined as:: class Mapping(Generic[KT, VT]): def __getitem__(self, key: KT) -> VT: ... # Etc. This class can then be used as follows:: def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT: try: return mapping[key] except KeyError: return default """ __slots__ = () _is_protocol = False @_tp_cache def __class_getitem__(cls, params): if not isinstance(params, tuple): params = (params,) if not params and cls is not Tuple: raise TypeError( f"Parameter list to {cls.__qualname__}[...] cannot be empty") msg = "Parameters to generic types must be types." params = tuple(_type_check(p, msg) for p …