Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django using generic views, "POST /''/ HTTP/1.1" 405 0, Method Not Allowed (POST)
Trying to define Create, Edit and list page for each model I have, after using the Generic view in Django UpdateView and CreateView. after save when forwarding to the listview an HTTP ERROR 405 appears without saving any data. I am using Django UpdateView for update form, CreateView for add and SingleTableView for the list. Models.py class PartnerOrganization(TimeStampedModel): name = models.CharField( max_length=100, unique=True, verbose_name=_('Name')) coordinator = models.ForeignKey( Coordinator, blank=False, null=True, related_name='+', verbose_name=_('Coordinator') ) land_phone_number = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner land phone number') ) fax_number = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner fax number') ) email = models.CharField( max_length=100, blank=True, null=True, verbose_name=_('Partner email') ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=False, null=True, related_name='+', verbose_name=_('Created by') ) class Meta: ordering = ['name'] def __unicode__(self): return self.name def get_absolute_url(self): return reverse("learningcenters:teacher_list") In Views.py class ListingPartnerView(LoginRequiredMixin, GroupRequiredMixin, FilterView, ExportMixin, SingleTableView, RequestConfig): table_class = PartnerTable model = PartnerOrganization template_name = 'learningcenters/partner/list.html' table = BootstrapTable(PartnerOrganization.objects.all(), order_by='id') # filterset_class = TeacherFilter group_required = [u"UNICEF"] def get_queryset(self): force_default_language(self.request) if self.request.user.groups.filter(name__in=['UNICEF']).exists(): return PartnerOrganization.objects.all() class AddPartnerView(LoginRequiredMixin, GroupRequiredMixin, CreateView): template_name = 'bootstrap4/common_form.html' form_class = PartnerForm queryset = PartnerOrganization.objects.all() # success_url = '/learningcenters/teacher/list/' group_required = [u"UNICEF"] def get_absolute_url(self): # return reverse("learningcenters:teacher_update", kwargs={"pk": self.id}) return reverse("learningcenters:partner_list") def form_valid(self, form): print(form.cleaned_data) form.save(self.request) return super(AddPartnerView, self).form_valid(form) class … -
Django JsonField Array data query
I have a jsonfield in Postgres db and data like below: income_info = [ { "id": "1", "name": "A", "min_income": 22000 }, { "id": "2", "name": "B", "min_income": 40000 }, { "id": "3", "name": "C", "min_income": 22000 } ] Now want to use gte and lte over the django orm queryset. Already tried Employee.objects.filter(income_info__min_income__lte = 4000000) but did not work at all. -
Receive Radio button value in React and Django
I have two types of users in my app i.e. supplier and teacher and a signup form in my react which contains Radio buttons to select either of them but I am unable to save the value of the radio buttons in my django ORM Here's the Code: SignUpForm.js import React from 'react'; import PropTypes from 'prop-types'; class SignupForm extends React.Component { state = { username: '', password: '', type: '', }; handle_change = e => { const name = e.target.name; const value = e.target.value; this.setState(prevstate => { const newState = { ...prevstate }; newState[name] = value; console.log(newState); return newState; }); }; render() { return ( <form onSubmit={e => this.props.handle_signup(e, this.state)}> <h4>Sign Up</h4> <label htmlFor="username">Username</label> <input type="text" name="username" value={this.state.username} onChange={this.handle_change} /> <label htmlFor="password">Password</label> <input type="password" name="password" value={this.state.password} onChange={this.handle_change} /> <label htmlFor="type">User type</label> <input type="radio" name="type" value="1" checked={this.state.type == "1"} onChange={this.handle_change} />Shipper <input type="radio" name="type" value="0" checked={this.state.type == "0"} onChange={this.handle_change} />Supplier <input type="submit" /> </form> ); } } export default SignupForm; SignupForm.propTypes = { handle_signup: PropTypes.func.isRequired }; Serializers.py from rest_framework import serializers from .models import Quiz from rest_framework import serializers from rest_framework_jwt.settings import api_settings from .models import User class TodoSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields = ('id', 'origin', 'destination', 'scheduled_date') … -
How do fix "Installed 0 object(s) (of 4) from 1 fixture(s)"?
I am trying to install a fixture. Django finds the fixture file but does not install the file. My model is this: class TipoCondominio(models.Model): descricao = models.CharField(max_length=30) criado = models.DateTimeField(auto_now_add=True) alterado = models.DateTimeField(auto_now=True) class Meta: db_table = 'tipo_condominio' def __str__(self): return self.descricao I set in the settings.py file the path: FIXTURE_DIRS = ( os.path.join(BASE_DIR, "fixtures",), ) My fixtures file is this: [ { "model" : "tipos.TipoCondominio", "pk" : 1, "fields" : { "descricao" : "Residencial" } }, { "model" : "tipos.TipoCondominio", "pk" : 2, "fields" : { "descricao" : "Comercial" } }, { "model" : "tipos.TipoCondominio", "pk" : 3, "fields" : { "descricao" : "Ambos" } }, { "model" : "tipos.TipoCondominio", "pk" : 4, "fields" : { "descricao" : "Outro" } } ] When I run the command: python manage.py loaddata tipo_condominio.json I recive: Installed 0 object(s) (of 4) from 1 fixture(s) And... The fixtures don't install in database. I would like the fixtures to be installed. Can anyone help? -
How can I solve the following problem?:UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list
Good morning, I present the following warning and I have not been able to solve it, it adds ordering properties and nothing: C: \ Users \ P05016 \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ site-packages \ rest_framework \ pagination.py: 198: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: QuerySet. paginator = self.django_paginator_class (queryset, page_size) class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination ordering = ['id_interface'] filterset_class=InterfacesFilter -
Create pagination for django elastic search result and send response?
I have implemented Django-elastic-search-dsl into my project and it works fine, but now i want my result to be paginated. I have tries basic django pagination and it did not work, so any ideas will be helpful. This is my views.py for search def search(request): if request.method == 'GET': q = request.GET.get('q') if q: p = Q("multi_match", query=q, fields=['title', 'description', 'status', 'media_source'], type='phrase_prefix') s = PostDocument.search().query(p) response = s.execute() else: response = '' response_list = [] for items in response: response_list.append({"title": items.title, "preview_path": items.preview_path, "description": items.description, "start_date": items.start_date, "end_date": items.end_date, "status": items.status, "media_source": items.media_source, "thumbnail_path": items.thumbnail_path, "published_date": items.published_date}) return HttpResponse( json.dumps(response_list, indent=4, sort_keys=True, default=str), status=200, content_type="application/json" ) Expected results : To send response data with pagination Actual results : Only search query result data. -
CSS attributes in HTML page show blank (style=""), when they are not | NGINX + Django [on hold]
All static files in the project are being loaded (how do I know this? Bootstrap, and Fontawesome, which I have locally, work fine), everything seems to be in order, but, for some reason, all the CSS attributes in the HTML pages are rendered blank when in the source code this is not the case. I haven't been able to find an answer online, and since I don't really know what files to include from my settings, I think a simple code sample of the problem should suffice. html source: <div style="width:100px;"></div> html live: <div style=""></div> -
How to add Id_card_number input field in django admin page whenever I add new user in admin?
I have a problem which I am searching for so many days but not finding an answer. I want new field to be appeared by the name of Id_card_number whenever I click add user in django admin page. Remember that Id_card_number is appearing in registration page but it not appearing in django admin page. Please help. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id_card_number = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id_card_number'] register.html <form method="POST"> {%csrf_token%} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-size: 50px">Join Today</legend><br> {{form|crispy}}<br> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> -
ModuleNotFoundError: No module named 'app_name'
I created a new app using python manage.py startapp associations I added it to installed apps but when I try to call the models inside management commands -fill_brands_table, I'm getting these error: from associations.models import Brand ModuleNotFoundError: No module named 'associations' settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'associations', ] management command -fill_brands_table: from django.core.management import BaseCommand from associations.models import Brand #failed here directory structure: associations/ management/ commands/ fill_brands_table.py __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py -
How can I import background from background_tasks in django. method gives error
I want to use django background-task but from background_task import background gives error How can I remove this error from my code. So far I have followed the documentation and have implemented this. views.py from background_task import background @background(schedule=60) def main(request): # First we have to create our client client =RestApiClient(version='9.0') settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'offense', 'background_task', ] Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\kiran.tanweer\appdata\local\programs\python\python37-32\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\kiran.tanweer\appdata\local\programs\python\python37-32\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\kiran.tanweer\Envs\dash\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\kiran.tanweer\Envs\dash\lib\importlib\__init__.py", line 127, in … -
Django WeasyPrint - Export filtered list
So I've created a pdf file from a ListView called "OrderListView". Now I would like to pass a queryset to the pdf file. I rewrote my listview as a function view for more clarity. I need to find a way to pass the queryset to the pdf view. I'm using django-filter to create the filtered view. I have the following; filters.py class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = { 'start_date': ['gte'], 'end_date': ['lte'], } views.py from .filters import * # View to show a filtered list using django-filter def order_list(request): order_list = Order.objects.all() order_filter = OrderFilter(request.GET, queryset=order_list) return render(request, 'orders/order_list.html', { 'filter': order_filter, }) # View to create a pdf file from the filtered view using WeasyPrint def order_list_pdf(request): order_list = Order.objects.all() order_filter = OrderFilter(request.GET, queryset=order_list) response = HttpResponse(content_type="application/pdf") response['Content-Inline'] = 'attachment; filename=filtered_list.pdf'.format() html = render_to_string('pdf/pdf_booking_list_arrivals.html', { 'filtered_list': order_list, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response So I have tried using query = request.GET.get('q','') And pass the query with the url <a class="btn" href="{% url 'order_list_pdf'?q={{ query }} %}">Create PDF</a> This does create the query in the url but does not filter the list. The generated pdf is working, I just need to find a way to … -
How can I use two variables in the urls.py with Django?
Hello I have this line in my urls.py using Django : re_path(r'exporting/(?P<var1>)/(?P<var2>.+)', views.myfunction, name='myfunction') And actually in my js file the url looks like something like this : window.location = Url + 'pdf/myfunction/' + var1 + '/' + var2 + ''; But it does not work when I try to see the page... Could you help me please ? Thank you very much ! -
django - how to display list objects from model in 'base.html' and extends it to all other templates
I have a navbar in "base.html" and i want to list objects from model on it, so this list be visible on all other template that extends 'base.html' 'base.html' <nav> {% for category in categories %} <a href="#">{{ category.category_name }}</a> {% endfor %} </nav> models.py class Categories(models.Model): category_name = models.CharField(max_length=100, null=True) views.py class NavbarView(ListView): model = Categories template_name = 'base.html' context_object_name = 'categories' urls.py path('nav/', views.NavbarView.as_view(), name='nav') this makes categories list visible only on 'nav/' urls but not in all templates that extends 'base.html how can i do this ? thanks -
'Save html form data in database' django
I'm trying to save name and email from HTML from using django in postgres database, in action tag, function name is mentiond but insted of using that function, django is passing that data to a new page of same function name HTML <form class="newsletter_form d-flex flex-md-row flex-column align-items-start justify-content-between" action="subscribe" method="post"> {%csrf_token%} <div class="d-flex flex-md-row flex-column align-items-start justify-content-between"> <div> <input name="subname" type="text" class="newsletter_input newsletter_input_name" id="newsletter_input_name" placeholder="Name" required="required"> <div class="input_border"></div> </div> <div> <input name="subemail" type="email" class="newsletter_input newsletter_input_email" id="newsletter_input_email" placeholder="Your e-mail" required="required"> <div class="input_border"></div> </div> </div> <div><button type="submit" class="newsletter_button">subscribe</button></div> </form> views.py def subscribe(request): if request.method == 'POST': subname = request.POST['subname'] subemail = request.POST['subemail'] sub = User.objects.create_user(subname=subname, subemail=subemail) sub.save(); return redirect('/') else: return redirect('/') url.py from django.urls import path from . import views urlpatterns = [ path("register", views.register, name='register'), path("login", views.login, name='login'), path("logout", views.logout, name='logout'), path("subscribe", views.subscribe, name='subscribe') ] this is error "image" [1]: https://imgur.com/a/8kh1Qbe "tooltip" -
How to split one form fields into multiple fields of a model in django?
This question is similar to Using multiple input fields for one model's attribute with django and How to render two form fields as one field in Django forms? What I need is basically the opposite of MultiValueField where I can save data from one form field - Name into two model fields - Firstname, Lastname. I'm unable to find any such thing like the opposite of MultiValueField. Can someone please suggest me what is the better way to do it. -
Value error on Image field when trying to comvert model to dict
I have 2 models, 1st is Garage class Garage(models.Model): name = models.CharField(verbose_name=_('Garage'), max_length=200) @property def cars(self) -> list: from django.forms.models import model_to_dict cars = [] for i in Car.objects.filter(garage=self.id): cars.append(model_to_dict(i)) return cars def __str__(self): return self.name class Meta: verbose_name = _('Garage') My 2nd model is Car, class Car(models.Model): name = models.CharField(verbose_name=_('Car Name'), max_length=200) garage = models.ForeignKey(verbose_name=_('Garage'), to=Garage, on_delete=models.PROTECT) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2) image = models.ImageField(verbose_name=_('Select Image'), upload_to='cars/', default=None) def __str__(self): return self.name class Meta: verbose_name = _("Car") verbose_name_plural = _("Cars") Now, when I try to run, the property 'cars' in the Garage model throws ValueError. ValueError: The 'image' attribute has no file associated with it. The complete error log is: Traceback (most recent call last): File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/PycharmProjects/venv/lib/python3.7/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/response.py", line 72, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/renderers.py", line 107, in render allow_nan=not self.strict, separators=separators File "/home/PycharmProjects/venv/lib/python3.7/site-packages/rest_framework/utils/json.py", line 28, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.7/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.7/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File … -
CSRF Fails after setting up Django app on Apache
After creating app in django and ensuring that everything works i tried to serve my app on remote server. The stack over there is Apache with mod-wsgi-py3. After setting up Apache with documentation provided by mod_wsgi i am having problems with mod-wsgi To make sure that i dont have any problem with my app i checked on standard admin page in Django. The only open domain from that server to access is 'https://app.web.corpnet.pl:15003/app/' so all my uri's use this as a root. I think that the problem is either in django settings (allowed hosts?) or apache conf so im pasting these: ALLOWED_HOSTS = ['localhost', 'app.tnweb.corpnet.pl', 'app.tnweb.corpnet.pl:15003', 'app.corpnet.pl', 'corpnet.pl'] Problem is described by django debug as: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Referer checking failed - https://app.tnweb.corpnet.pl:15003/app/admin/login/?next=/app/admin/ does not match any trusted origin -
how to validate a user in URL field
This is my URL and that 21 is the id of my current user if I make a change in that number I put 20 it shows me the profile of id 20th user. what validation should I use? http://127.0.0.1:8000/profile/21 path('profile/<int:pk>', views.profile, name='profile') Do not tell me to remove int pk because I need it for another reason. -
How to add text input field in django admin page?
I am trying to add Id field whenever I add new user in django admin user page. I have done this in forms.py but it is showing me whenever I add new user in it. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id'] -
Django fresh login required on accessing profile page
I am new to django and writing authentication system for my application. Right now I have built the basic login/logout functionality. What I want is that whenever a logged in user wants to access their profile page, they should be asked to confirm their password. I have searched this on django docs but I was not able to find any resource on how to achieve. I know flask has a fresh_login_required decorator which does this, just wondering if it is possible to do the same thing with django as well. -
Filtering an API List View queryset according to latest timestamp AND Q lookup fields
I am trying to overwrite my get_queryset method in my generic API List View. I want to query by two fields and get the most recent item. More specifically I want to Query by project name and by graph name and get only the most recent element. I am trying to achieve this with Q lookup fields like so: class ListGraphDataAPI(ListAPIView): serializer_class = GraphSerializer def get_queryset(self, *args, **kwargs): queryset_list = Graph.objects.all() query = self.request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(name__icontains=query)& Q(project__graph__name__exact=query) ).distinct() return queryset_list This works in so far that I can filter by name of my graph. the line Q(project__graph__name__exact=query) does nothing though. THe problem is that it is a foreign key relation. Like so: class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) timestamp = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.name @property def nodes(self): return self.node_set.all() @property def edges(self): return self.edge_set.all() In my URL I type http://localhost:8000/graph-data/list/graph/?q=Graph2&q=project2 My data struture (unfiltered) looks like so: [ { "project": "project1", "name": "Graph1", "description": "Graph belongs to Projekt1", "nodes": [ { "id": 43, "name": "25", "graph": 94 } ], "edges": [ { "id": 24, "name": "EdgeForGraph1", "graph": 94, "source": 43, "target": 43 } ] }, { … -
How to run a function in the background-Django
I want to run an API call after every 5 mins in the app. I want to generate a notification whenever new data is added to the database through the API.So to check this I need to run the task in background to make it a real time application. How can I achieve this task in Django? I am facing multiple errors while using django background_tasks so I don't want to use it. Celery is not compatible with windows. Is there any other option whose tutorial is available also -
Как правильно написать модель Order в Django? [on hold]
Я написал некоторую логику работы интернет магазина на Django. На данный момент при создании заказа, в панели администратора создается заказ, который содержит в себе корзину, в свою очередь в корзине содержатся items, которые выступают в роли товарных позиций в заказе. Номер заказа - Order.id(self.id) сейчас он выглядит так (Заказ № 20), я пытаюсь вместо общего заказа, вывести в панель все товарные позиции и присвоить им номера по типу: Заказ № 20 - 1, Заказ № 20 - 2 и так далее. Все позиции должны быть должны быть в каждой строчке, и со своим порядковым номером. def str(self):return "Заказ № {0} - {1}".format(str(self.id), self.items.items.count()) В данном случае возвращается общее количество items в заказе: Например: В заказе под № 20 есть 4 позиции => Заказ № 20 - 4 Мой models.py class Category(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(blank=True) def __str__(self): return self.name class Meta: verbose_name = 'Категории товаров'# Единственное число verbose_name_plural = 'Категории товаров'# Множественное число def get_absolute_url(self): return reverse('category_detail', kwargs={"category_slug": self.slug}) def pre_save_category_slug(sender, instance, *args, **kwargs): if not instance.slug: slug = slugify(translit(str(instance.name), reversed=True)) instance.slug = slug pre_save.connect(pre_save_category_slug, sender=Category) Здесь модель брендов категорий товаров: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: verbose_name = 'Производители' verbose_name_plural = 'Производители' … -
Modelformset with dynamic form addition saves only the first form
I have two forms on one page, each with its own submit button. With JS script I can dynamically add a new formset for each of the two form. I am faced with a situation where I can add as many new forms as I want for the form that is displayed first on the page and all are saved. For the second forms list, only the first form from the formset list is saved. template.html <form method="post" action="">{% csrf_token %} {{ formset_planguage.management_form }} <div id="form_set_lang"> {% for form in formset_planguage.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more_lang"> <div id="empty_form_lang" style="display:none"> <table class='no_error'> {{ formset_planguage.empty_form }} </table> </div> <input class='btn btn-primary' type="submit" name="language" value="Submit"/> </form> <form method="post" action="">{% csrf_token %} {{ formset_framework.management_form }} <div id="form_set_framework"> {% for form in formset_framework.forms %} {{form.non_field_errors}} {{form.errors}} <table class='no_error'> {{ form }} </table> {% endfor %} </div> <input type="button" value="Add More" id="add_more_framework"> <div id="empty_form_framework" style="display:none"> <table class='no_error'> {{ formset_framework.empty_form }} </table> </div> <input class='btn btn-primary' type="submit" name="framework" value="Submit"/> </form> <script> $('#add_more_framework').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set_framework').append($('#empty_form_framework').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> <script> $('#add_more_lang').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set_lang').append($('#empty_form_lang').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) … -
Customize django admin select foreign key popup
I need to customize popup for select raw_id_field foreign key I have my admin like this: class SecondMyModel(models.Model): name = models.CharField(max_length=30) class MyModel(models.Model): switch_date = models.DateField() old_value = models.ForeignKey(SecondMyModel) class MyModelAdminForm(forms.ModelForm): class Meta(object): model = MyModel fields = ('old_value', 'switch_date') @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm list_display = ('id', 'old_value', 'switch_date') ordering = ('switch_date',) fieldsets = ( (None, { 'fields': ('old_value', 'switch_date'), 'classes': ('suit-tab', 'suit-tab-general'), }), ) raw_id_fields = ('old_value',) When I'm trying to add new MyModel I need to select 'old_value'. How can I change select foreign key popup for having opportunity to select 'old_value' by click on its id field or its name field? (not only 'id' or only 'name')