Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to get total cart item in ecommerce
I am trying to add the total item in the cart, but I am getting <property object at 0x000001CFFDED8228>: could anybody help? View.py class checkout(ListView): model = OrderItem template_name = 'product/checkout.html' def get_context_data(self, **kwargs): context = super(checkout, self).get_context_data(**kwargs) context['orderQty'] = Order.get_cart_items return context model.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null = True, blank=False) transaction_id = models.CharField(max_length= 200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum(item.quantity for item in orderitems) return total size_choices = (('small', 'S'), ('medium', 'M'), ('large', 'L')) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) quantity = models.IntegerField(default=0, blank=True, null=True) size = models.CharField(max_length= 200,choices= size_choices, default=0) @property def get_total(self): total = self.product.price *self.quantity return total template.html: <div class="row-1"> <div style="flex:2;"><strong>Total Items</strong>:<span style="float: right;">{{orderQty}}</span></div> <hr> <div style="flex:2;"><strong>SubTotal</strong>:<span style="float: right;">$387</span></div> <hr> <div style="flex:2; margin-top:10px"><strong>Shipping</strong><span style="float: right;">$54</span></div> <hr> </div> <div> <div style="flex:2; text-align:center"><h6>Total: $387</h6></div> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Pay"> </div I believe these files contain the problem but from researching online I can't seem to pinpoint exactly what it is. The function based view of my website was working fine until I moved to class-based … -
image not uploading Django for loop and Bootstrap Card
I trying to upload image. I used Django for loop and inside it placed Bootstrap Card. Products {% for product in products %} {{product.name}} ${{product.price}} ORDER NOW {%endfor%} -
Show some readonly fields and a preview (not a field)
Django 3.1.6 class SvgFile( CreatedMixin, AltMixin, CommentMixin, models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Creation date")) file = models.FileField(upload_to=svg_upload_to, verbose_name=gettext_lazy("SVG file"),) def preview(self): return mark_safe('<img width="100" src="{}" />'.format(self.file.url)) preview.short_description = gettext_lazy('Preview') preview.allow_tags = True class Meta: verbose_name = gettext_lazy("SVG file") verbose_name_plural = gettext_lazy("SVG files") class SvgFileForm( ModelForm): class Meta: model = SvgFile exclude = [] Could you help me understand how to show id, created and preview in edit view of Django admin site? -
How to configure django-db-multitenant?
I am trying to use django-db-multitenant and I am doing something wrong. I am getting error ('%s does not subclass db_multitenant.mapper.TenantMapper', 'demo.mapper.TenantMapper'). It would be great help if anyone can help me regarding this. -
Django : matching query does not exist
I am getting error while creating an instance of ModelForm in DJango. I am not always facing the issue but sometimes it work fine and sometimes it gives me error. ModelFOrm code : class ClientinfoForm(ModelForm): Account_Name = forms.CharField(disabled=True) class Meta: model = AccountDescription fields = ['Account_Name','short_Name','group_Master_Project_Code','account_Logo','vertical','client_Website','client_Revenue','Employee_Count','client_Industry_Segment','delivery_Manager_Mail','project_Manager_Mail'] labels = {'client_Revenue':'Client Revenue(in USD Billion)','vertical':'Industry Vertical'} help_texts = {'client_revenue' : '(In Billion USD)' } views.py code def save_client_info(request): fm = ClientinfoForm(request.POST, instance = AccountDescription.objects.get(Account_Name = acc_name),files = request.FILES or None) save_form(request,fm) def clientinfo(request): if request.user.is_authenticated: if request.method == 'POST': print("inside form") save_client_info(request) global s4_option s4_option = AccountDescription.objects.filter(Account_Name = acc_name).values('s4_data') s4_option = s4_option[0]['s4_data'] accdata = AccountDescription.objects.filter(Account_Name = acc_name) clientdata = ClientinfoForm(instance = AccountDescription.objects.get(Account_Name = acc_name)) return render(request, 'AccountData/ClientInfo.html',{'name' : 'clientinfo','form':clientdata,'acntdata':accdata,'content':editoption}) Sometimes, when I save it works perfectly fine but sometimes it give matching query doesn't exist. Let me know if more information is required. -
'CreateView' object has no attribute 'render_to_response'
I have this create view and it throws the error 'CreateView' object has no attribute 'render_to_response' urls.py path( "p/<int:id>/food/create", views.FoodCreateView.as_view(), name="food-create", ), views.py class FoodCreateView(BaseCreateView): template_name = "food_form.html" form_class = forms.FoodForm success_message = "successfully created" def get_queryset(self): return Food.all(#####) def get_success_url(self): return reverse( "food_list" ) am I lacking anything with the code? -
Django AttributeError at /upload/
When I'm trying to run my view.py, I get this error: 'list' object has no attribute 'name' at the fourth line of view.py that I have attached below. My app basically allows users to upload photos and save them after they are edited automatically. This error happens right after I click upload. forms.py class PhotoForm(forms.ModelForm): image = MultiImageField(min_num=1, max_num=20) class Meta: model = Post fields = ['name'] widgets = {'name': forms.HiddenInput()} views.py def photoform(request, *args, **kwargs): if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): a = form.save() models.py class Post(models.Model): name = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) I don't know if this helps, but here is what the error shows. -
How to store filtered data in excel in Django?
Made a view that pulls data from the model. Based on this data, the table in the template is filled. For each field of the table (model) added filtering based on django-filters. Faced the following problem, I need to save filtered data to excel. The problem is precisely in getting the filtered data, saving in excel is not a problem. My class based view: class RequestList(FilterView): template_name = 'MQueryboard/Requests/RequestList.html' filterset_class = Filter_Adjustments_view model = Adjustments paginate_by = 3 def get_queryset(self): filterset_class = Adjustments.objects.order_by('-dateadjustment') return filterset_class def get_context_data(self, *args, **kwargs): _request_copy = self.request.GET.copy() parameters = _request_copy.pop('page', True) and _request_copy.urlencode() context = super().get_context_data(*args, **kwargs) context['parameters'] = parameters return context def post(self, request): if request.method == 'POST': response = adjustments_to_excel(Adjustments.objects.all()) return response else: return render(request, 'MQueryboard/Requests/RequestList.html', {}) The adjustments_to_excel function - in order not to load the view, data is sent to the script to generate an Excel file. Here I do not understand how I can get the filtered queryset in the post function. Now, as a "stub" is the selection for all fields of the model. Please tell me how you can do this. I've been struggling with this question for a week, nothing has been working out yet. Thanks in … -
Can't display images from models of django
Since I have faced this problem many times and couldn't find a solution, I need help Here's my settings file. I've configured media root from pathlib import Path import os import django_heroku import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testimage.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'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', ], }, }, ] WSGI_APPLICATION = 'testimage.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = … -
django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name
I am trying to create a url-shohrtener and it gives me this error: django.urls.exceptions.NoReverseMatch: Reverse for '' not found. '' is not a valid view function or pattern name. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('shorturl.urls')), ] here is my apps urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:id>/', views.redirect_url, name='redirect'), ] these are the views.py: from django.shortcuts import render, redirect from .models import Url import random import string def redirect_url(request, id): urls = Url.objects.filter(short=id) link = "" for i in urls: link = i.url return redirect(link) def index(request): if request.method == "POST": link = request.POST.get("link") short = "" if Url.objects.filter(url=link).exists(): urls = Url.objects.all() for i in urls: if i.url == link: short = i.short break else: short = get_short_code() url = Url(url=link, short=short) url.save() new_url = request.get_host() + "/" + short return render(request, 'shorturl/index.html', {"new_url":new_url}) return render(request, 'shorturl/index.html') def get_short_code(): length = 6 char = string.ascii_uppercase + string.digits + string.ascii_lowercase while True: short_id = ''.join(random.choice(char) for x in range(length)) if Url.objects.filter(short=short_id).exists(): continue else: return short_id just in case it is important this is the template: <!doctype html> <html lang="en"> <head> <!-- Required … -
Filter Django queryset using dropdown box and ajax
I have the following view and template. I would like to filter (current_state is the variable I'm using) the query set using the dropdown list and jquery or ajax to reload the data on the page. Views.py def dashboard(request): records = Employee.objects.filter(owner_id__profile__state=current_state) #my queryset return render(request, "dashboard.html", {"records" : records}) Template.html <form method="POST"> <select name="stateddl" id="stateddl"> <option value="AL" selected>Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> ... </select> </form> ... <table> <thead> <tr> <th>Name</th> <th>State</th> <th>Phone</th> </tr> </thead> <tbody> {% for r in records %} <tr> <td>{{ r.name }}</td> <td>{{ r.state }}</td> <td>{{ r.phone }}</td> </tr> {% endfor %} </tbody> </table> -
ImportError: cannot import name 'employees' from 'rest_framework'
from rest_framework import employees ImportError: cannot import name 'employees' from 'rest_framework' (C:\Users\SONY\AppData\Local\Programs\Python\Python39\lib\site-packages\rest_framework_init_.py) how to solve this error? -
Can I put custom settings in Django's settings.py
I have several custom settings I'd like to define in my Django app. Up to this point, I've put them in a constants.py file in each individual app. myapp/constants.py HOURS_PER_EVENT = 4 MAX_MEMBERS_PER_EVENTS = 150 MAX_EVENTS_PER_YEAR = 10 ... It just occurred to me I may be able to put these in settings.py and after a quick test everything seems to work fine. Is this allowed or is settings.py reserved for core django settings defined here? If it's not allowed, is there a better place to put these. -
Is there a way to create an endpoint (and subsequently view) for a choice field in a Django backend?
In my Django models.py file, I have a variable ColourChoices = ((0, "GREEN"), (1, "YELLOW"), (2, "RED"), (3, "GREY")) where in the same file, ColourChoices is used in class class Rainbow(models.Model): colour = models.IntegerField(choices=ColourChoices) I was wondering if there is a viable way to create a view for ColourChoices (i.e. some JSON endpoint), such that you can get all the existing values for it (GREEN, YELLOW, RED, GREY) without creating a new table in the underlying database and adding those values to it? That is, in such a way that if I were to add a new colour (e.g. BLUE), or remove one colour from the choices, that doing it once in the code would do the trick (i.e. change what you see in the view). -
what is the most optimal way of using location in django
If I am trying to create a location based recommender system in Django and where to start, Thanks in advance for answering this silly question -
django: prefetch with only() is causing many queries
If i am using only() in prefetch then its causing lot of sql queries queryset = SymbolList.objects.prefetch_related( Prefetch('stock_dailypricehistory_symbol',queryset = DailyPriceHistory.objects.filter(id__in= [1,....,200]).only('close','volume').order_by('datetime') ) for symbolObject in querset: querysetDaily = symbolObject.stock_dailypricehistory_symbol.all() for daily in querysetDaily: print(daily.volume,daily.close) this is causing sql query which is accpeted SELECT `daily_price_history`.`id`, `daily_price_history`.`volume`, `daily_price_history`.`close` FROM `daily_price_history` WHERE (`daily_price_history`.`id` IN (SELECT U0.`id` FROM `daily_price_history` U0 WHERE (U0.`datetime` >= 1604718922708 AND U0.`symbolId_id` = `daily_price_history`.`symbolId_id`)) AND `daily_price_history`.`symbolId_id` IN (1, 2, .. .. 200)) ORDER BY `daily_price_history`.`datetime` ASC but also many queries like which is not supposed to SELECT `daily_price_history`.`id`, `daily_price_history`.`symbolId_id` FROM `daily_price_history` WHERE `daily_price_history`.`id` = 11346597 LIMIT 21 I found the traceback causing the above sql to: File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1710, in prefetch_related_objects obj_list, additional_lookups = prefetch_one_level(obj_list, prefetcher, lookup, level) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1823, in prefetch_one_level prefetcher.get_prefetch_queryset(instances, lookup.get_current_queryset(level))) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 637, in get_prefetch_queryset instance = instances_dict[rel_obj_attr(rel_obj)] File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 647, in get_local_related_value return self.get_instance_value_for_fields(instance, self.local_related_fields) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related.py", line 667, in get_instance_value_for_fields ret.append(getattr(instance, field.attname)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\base.py", line 635, in refresh_from_db db_instance = db_instance_qs.get() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\dev\AppData\Roaming\Python\Python38\site-packages\django\db\models\query.py", line 53, in __iter__ … -
How to make a Python html implementation of Battleship(Flask or Django)?
Would it be easier for the program to get inputs from the terminal or from somewhere else? Why do you need flask/django and which one would be better? -
Exception Value: No module named 'PIL' - in Django
Django Version: 3.1.6 Python Version: 3.6.9 I'm trying to use the ImageField in my django admin page to upload an image. When I try to upload it from my NGinx/Gunicorn server I get this error. However when I run it from port 8000 using manage.py runserver 0:8000 from the SAME server, it works. I don't understand this error. I have Pillow installed. Environment: Request Method: POST Request URL: http://54.188.59.209/admin/core/employee/add/ Django Version: 3.1.6 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/contrib/admin/options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, … -
Scrapyd + Django in Docker: HTTPConnectionPool (host = '0.0.0.0', port = 6800) error
I am a young Italian boy looking for help.I'm building a web interface for my web scraper using django and scrapyd. It's my first experience with scrapy but i'm learning fast thanks to the good amount of documentation on the net. However, I find myself in quite a bit of difficulty starting my spider via scrapyd_api.ScrapydAPI. Despite starting the server at the correct port (curl and browser requests both work), django returns a requests.exceptions.ConnectionError: HTTPConnectionPool (host = '0.0.0.0', port = 6800) error. First of all, here is my folder structure: scraper ├── admin.py ├── apps.py ├── dbs │ └── default.db ├── __init__.py ├── items.py ├── logs │ └── default │ └── autoscout │ ├── 0b2585dc6f2011eba4d30242ac140002.log │ ├── 1fd803a66f2011eba4d30242ac140002.log │ └── 6fac4d646f2111eba4d30242ac140002.log ├── middlewares.py ├── migrations │ ├── 0001_initial.py │ ├── 0002_auto_20210214_2019.py │ ├── 0003_auto_search_token.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-38.pyc │ ├── [...] │ └── __init__.cpython-38.pyc ├── models.py ├── pipelines.py ├── __pycache__ │ ├── admin.cpython-38.pyc │ ├── [...] │ └── views.cpython-38.pyc ├── serializers.py ├── settings.py ├── spiders │ ├── AutoScout.py │ ├── __init__.py │ └── __pycache__ │ ├── AutoScout.cpython-38.pyc │ └── __init__.cpython-38.pyc ├── urls.py └── views.py and my docker compose: version: "3.9" services: django: build: . command: … -
Django video uploader is not playing videos?
I have this video uploader in django, but it is not working. Here is my model: #blog/models.py class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') And my views: #blog/views.py def display(request): videos = Videos.objects.all() context = { 'videos': videos, } return render(request, 'blog/videos.html', {'videos': videos}) My settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And my urls: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And my template: <h2>{{ video.title }}</h2> <div class="embed-responsive embed-responsive-16by9"> <video class="embed-responsive-item" src="{{ video.video.url }}" controls></video><br> </div> But it is not working, it is a play button with a cross on it. So what am I doing wrong? -
Gunicorn/Nginx/Django - 500 Error is not producing error logs
I have a django site in production running NGINX/Gunicorn/Supervisor. I have an imageupload Field which fails and returns a 500 error page from Gunicorn. Although my error logs don't tell me anything. How am I supposed to debug this problem? logs: ubuntu@ip-172-31-29-176:/logs$ cat gunicorn.err.log [2021-02-15 02:12:20 +0000] [11369] [INFO] Starting gunicorn 20.0.4 [2021-02-15 02:12:20 +0000] [11369] [INFO] Listening at: unix:/home/ubuntu/gsc/app.sock (11369) [2021-02-15 02:12:20 +0000] [11369] [INFO] Using worker: sync [2021-02-15 02:12:20 +0000] [11372] [INFO] Booting worker with pid: 11372 [2021-02-15 02:12:20 +0000] [11374] [INFO] Booting worker with pid: 11374 [2021-02-15 02:12:20 +0000] [11375] [INFO] Booting worker with pid: 11375 /etc/nginx/sites-enabled/django.conf server{ listen 80; server_name ec2-54-188-59-209.us-west-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/gsc/app.sock; } location /static { alias /home/ubuntu/gsc/assets/; } location /media { alias /home/ubuntu/gsc/media/; } } /etc/supervisor/conf.d/django.conf [program:gunicorn] directory=/home/ubuntu/gsc command=/usr/local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/gsc/app.sock gsc.wsgi:application autostart=true autorestart=true stderr_logfile=/logs/gunicorn.err.log stdout_logfile=/logs/gunicorn.out.log -
How include Recipients to django-postman
in django postmon, when sending a message, an empty recipient field, how to auto-detect the recipient by ID, if the message is sent from the recipient's profile page? thank -
How to make the django-filter issue a request and transform it into a geoJSON?
I want to display my data from the database on a web map, in the form of a geoison. Since I'm new to development, I am lacking in knowledge. The Djnago filter displays my geoDjango coordinates from the database on HTML as: SRID = 4326; POINT (78.407707 44.998262). Is there an option for integration with Django Rest Framework, which gives data in the form of JSON? Help me please. Thank you in advance. #------------------------------------------------------------------------------------------------------ #filters.py import django_filters from .models import SubstationTable, PowerLine10Table, TransformerTable class SubstationFilter(django_filters.FilterSet): class Meta: model = SubstationTable fields = [ 'owner_substation', 'section_substation', 'substation_number', ] class PowerLine10Filter(django_filters.FilterSet): class Meta: model = PowerLine10Table fields = [ 'owner_powerline10', 'section_powerline10', 'substation', 'powerline10_number', ] class TransformerFilter(django_filters.FilterSet): class Meta: model = TransformerTable fields = [ 'owner_transformer', 'section_transformer', 'powerline10', 'transformer_number', ] #------------------------------------------------------------------------------------------------------ #views.py def web_map(request): substation_filter = SubstationFilter(request.GET, queryset=SubstationTable.objects.all()) powerline_filter = PowerLine10Filter(request.GET, queryset=PowerLine10Table.objects.all()) transformer_filter = TransformerFilter(request.GET, queryset=TransformerTable.objects.all()) context = { 'title': 'WEB_MAP', 'substation_filter': substation_filter, 'powerline_filter': powerline_filter, 'transformer_filter': transformer_filter, } return render(request, 'app_webmap/app_webmap_page.html', context)``` #------------------------------------------------------------------------------------------------------ #models.py from django.db import models from django.contrib.gis.db import models class SubstationTable(models.Model): """Substation""" owner_substation = models.ForeignKey( OwnersTable, on_delete=models.CASCADE, verbose_name='Owner:') section_substation = models.ForeignKey( SectionsTable, on_delete=models.CASCADE, verbose_name='Section:') substation_number = models.CharField(max_length=25, unique=True, verbose_name='Substation number:') substation_name = models.CharField( max_length=25, unique=True, blank=True, null=True, verbose_name='Substation name:') visibility_on_map= … -
Django stuck on default splash page in production
I just set up a deployment server with NGINX/GUNICORN. I've uploaded my project and all I see is the "welcome to django" splash page. No matter what I do, I can't get rid of this. When I run: ./manage.py runserver 0:8000 I can access my website through port 8000, and it works! I don't understand why the production server (using the same code) won't do anything. I even changed debug=False, and the splash screen still thinks I'm in debug mode. I have even deleted my pycache folder. No change. -
Django Template: Add Variable Into URL As Parameter
What's the proper way to add {{gamestoday|lookup:i}} into the <a href={%url 'stats'%}>. Do I need to make changes to urls.py? {% load tags %} <center> <div class = "scoreboardbackground"> <div class="row"> {% for i in ngames %} <div class="col"> <a href={%url 'stats'%}> <div class="livegamebox"> {{teamnames|lookup:i|lookup:0}} vs {{teamnames|lookup:i|lookup:1}} - {{gamestoday|lookup:i}} <br> <div style="font-size:12px;"> {{datetimegames|lookup:i}} </div> <br> <div style = "font-size:30px"> <b>{{latestscore|lookup:i}}</b> </div> </div> </a>