Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Really weird behaviour when running a function, coding it in shell works, importing the function doesn't
I have no idea what's happening here. ​ I have a class that looks something like, ​ class Scrape: def __init__(self, session, headers, proxies): self.session = session self.headers = headers self.proxies = proxies self.response = None def post(self, url): self.response = self.session.post(url, headers=self.headers, proxies=self.proxies, verify=False) def get(self, url): self.response = self.session.get(url, headers=self.headers, proxies=self.proxies, verify=False) Then I have this function in another file, import requests from .config import * from .scraper import Scrape from .serializer import * import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def run(): scrape = Scrape(requests.session(), headers, PROXIES) scrape.post(url) save = [] for obj in scrape.parse_response(): ....... Now this works perfectly in my development environment, but when I deploy it, I get this. urllib3.connection.HTTPConnection object at 0x7f69ccf34710>: Failed to establish a new connection: [Errno 110] Connection timed out',))) Now at first I thought my server had whitelists and stuff, BUT if I do this, In [10]: from bots.roku.config import * In [11]: import requests In [12]: r = requests.session().post(url, headers, PROXIES) In [13]: r Out[13]: <Response [200]> IT WORKS? This doesn't though, In [5]: import requests In [6]: scrape = Scrape(requests.Session(), headers, PROXIES) In [7]: scrape Out[7]: <bots.roku.scraper.Scrape at 0x7f69ccfaff60> In [8]: scrape.get("http:\\www.google.com") ProxyError: HTTPConnectionPool(host='170.130.63.178', port=8800): Max retries exceeded with url: http://www.google.com/ … -
Best way to render HTML to PDF in Django site
I have pretty complicated css in my HTML and I tried to render it to PDF using xhtml2pdf but it does not support my css. So I tried to use reportLab but then it might take times because I have to do the design all over again (also I'm not sure how can I insert my fetch data from db into the pdf using it). So in my case what is the best way to render HTML to PDF in Django ? -
Django foreign key form
I have two models Order and a date model. Order model has a foreign key attribute of date model. I have made a form in which I can update the date fields of order, but when I click submit it creates a new date object in date model not in the order date field. I want my form to save values in the date field in order. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) order.date = date_instance order.save() context = { 'order':order,'form':form } else: … -
Preventing users writing foul language in the comment section
I don't want users to be able publish offensive comments on my posts. I know a way of censoring out s***, f***, c*** etc. But if you apply a blanket ban to offensive words then you may unintentionally end up banning a word such as Scunthorpe (a place in the UK) because it contains an offensive substring. In forms.py I want to set the comment active property to false if the comment potentially contains an offensive word. Therefore I could manually check any potentially controversial posts. models.py class Comment(models.Model): #The foreign key is linked to the ID field in the Post model #id = models.IntegerField(primary_key=True, blank=False) post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') nameid = models.ForeignKey(User,on_delete=models.CASCADE,related_name='commentsid') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on= models.DateTimeField(default = timezone.now()) active = models.BooleanField(default=True) forms.py I have tried setting active to false in at least 4 different ways but have so far had no luck. Does anyone have any suggestions? def clean_body(self): body = self.cleaned_data.get("body") if "f***" in body or "s***" in body : self.data['active'] = False self.fields['active'].initial = False self.cleaned_data.get("active")=False form.fields['active'].initial = False return body -
Django Does Not Detect Tests Ran 0 tests in 0.000s
I run the python manage.py test and also tried app specific tests for my app blog but it is not detected. Is there an error in my test.py? I don't know why the tests are not being detected. from django.contrib.auth import get_user_model from django.test import Client, TestCase from django.urls import reverse from .models import Post class BlogTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='testuser', email='test@email.com', password='secret' ) self.post = Post.objects.create( title='A good title', body='Nice body content', author=self.user, ) def test_string_representation(self): post = Post(title='A sample title') self.assertEqual(str(post), post.title) def test_post_content(self): self.assertEqual(f'{self.post.title}', 'A good title') self.assertEqual(f'{self.post.author}', 'testuser') self.assertEqual(f'{self.post.body}', 'Nice body content') def test_post_list_view(self): response = self.client.get(reverse('home')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Nice body content') self.assertTemplateUsed(response, 'home.html') def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000/') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') -
Saleor production deploy
Im trying to deploy a saleor instance on my local network, but im having trouble accesing it if im not in the localhost, storefront shows no pictures, but Network Error: failed to fetch, i cant log in either, dasboard shows unespected error and don't log in My common.env file is in the attached photo -
im having trouble Django materialize css form when a render the form i get the variable does not exist from field.html from django-materializecss-form
I'm new to Django. whenever I render the form I get "Exception has occurred: VariableDoesNotExist Failed lookup for key [required_css_class] in " . I don't understand this error if anybody explain or tell me what I'm doing wrong will be much appreciated thank you in advance this is my view def considerations(request): if request.method == "POST": form = B2bConsideration(request.POST) v = form.is_valid() if form.is_valid(): instance = form.save(commit=True) #adding date to instance from request not in table but a good idea #instance.date = request.date instance.save() return HttpResponseRedirect(reverse('b2b:TypeOfTitle')) else: return HttpResponse(form.errors) else: form = B2bConsideration() return render(request, 'b2b/B2B_notes.html',{'form':form} ) this is my modelform class B2bConsideration(ModelForm): CHOICES = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),] under_name_title = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect()) class Meta: model = Consideration fields = ['under_name_title','salvage_title','is_title_paidoff'] this is my model under_Name_choices = [('yes_title_under_name', 'yes'),('No_title_under_name','no'),] salvage_title_choices =[('yes_salvage_title','yes'),('no_salvage_title','no'),] is_title_paidoff_choices = [('yes_title_paidoff', 'yes'),('no_title_paidoff','no'),] class Consideration (models.Model): under_name_title = models.CharField(max_length=21, choices=under_Name_choices) salvage_title = models.CharField(max_length=18, choices=salvage_title_choices) is_title_paidoff = models.CharField(max_length=21, choices=is_title_paidoff_choices) here is where the error points to. this is what it said "Exception has occurred: VariableDoesNotExist Failed lookup for key [required_css_class] in " <label class="control-label {{ classes.label }} {% if field.field.required %}{{ form.required_css_class }}{% endif %}">{{ field.label }}</label> this is my HTML {% load static %} {% load materializecss %} <!DOCTYPE HTML> … -
how to include html file in another to avoid repeating code?
I code with django and when I am working with django template, I do the below to avoide repeating code. I illustrate it with an example: Suppose I have two pages in my website: 1) home 2) about In django I code as below: I first build a base.html : <!DOCTYPE html> <html> <head> </head> <body> <h1>this is my site</h1> {% block body %}{% endblock body %} </body> </html> I then build home.html: {% extends 'base.html' %} {% block body %} <h2>This is home</h2> {% endblock body %} I talso build about.html: {% extends 'base.html' %} {% block body %} <h2>This is about</h2> {% endblock body %} I now want to do the same without having a backend. I have a static website. How can I do the same without having a backend like django or php, etc. -
AttributeError: module 'pages.views' has no attribute 'home_view'
I was following a beginner's Django tutorial word-for-word creating a project called 'Pages' when all of a sudden my computer gave me an error (AttributeError) when I tried to access the localhost page (http://127.0.0.1:8000/) that was supposed to say 'Hello World.' Instead of seeing the statement, a 'This site can’t be reached' page was there. I am completely confused as to why this happened because I was following the instructor word-for-word yet got a different result. If anyone can help that would be very much appreciated! Here are my files views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home_view(*args, **kwargs): # args, kwargs return HttpResponse("<h1>Hello World</h1>") # string of HTML code urls.py """trydjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin … -
Cross origin ajax requests with iframe resulting in 403 error
I'm attempting to run my webapp on another domain via an iframe. I'm using jquery ajax POST requests to my server with this webapp. I'm getting the following error: Forbidden (403) CSRF verification failed. Request aborted. So far, I've taken the following steps: 1) I'm including the csrf_token on the data I'm sending to my backend via ajax. 'csrfmiddlewaretoken': '{{ csrf_token }}', 2) I've installed django-cors-headers and: - added the middleware to the top of my list of middleware ('corsheaders.middleware.CorsMiddleware',), - added 'corsheaders' to the list of installed apps - set the following variable in my settings: CORS_ORIGIN_ALLOW_ALL = True 3) I've got the following code running to support ajax requests $(document).ready(function(){ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) … -
Button not sending POST request to update object django
I have a scheduling app with Event objects and I'm trying to create a form that will allow the user to update an Event that already exists by the press of the button. However, when the user presses the button it doesn't seem to do anything. It just refreshes the page. {% for a in availability %} <form method='POST'> <li><a class="btn btn-primary" href="{% url 'updateevent' a.id %}" type="submit" role="button">{{a.day}}: {{a.start_time}} - {{a.end_time}}</a></li> </form> {% endfor %} view.py: def updateevent(request, pk): if request.method == 'POST': try: form = EventForm(data=request.POST, instance=post) updatedEvent = form.save(commit=False) updatedEvent.requester_user = request.user updatedEvent.notes = None updatedEvent.save() return redirect('/') except ValueError: print(form.errors) return render(request, 'events/createevent.html', {'form':EventForm(), 'error':'There was an error. Please make sure you entered everything correctly!'}) else: return redirect('/') I want the user that presses the button to become the "requester_user", a blank field in my Event object. How can I make this happen? -
Can I receive Django channels group messages in other part of my project
I am able to send to channels group from separate scripts using something like this from channels.layers import get_channel_layer async def somefunction(): await channel_layer.group_send( group_name, {"type": "system_message", "text": "demo text"}, ) What I want to know is, how can I also read updates from channel groups. Any help with be appreciated. -
Django Crispy forms helper throwing Failed lookup for key [helper] error
I cannot get crispy form helper to work with forms or formsets. If I simply user the {% crispy form %} or {% crispy formset %} tags, depending on implementation, the forms appear and function normally. Of course, this is a problem when I'm trying to use layouts with crispy helpers. When I user {% crispy form form.helper %} or {% crispy formset helper %}, my app throws errors that: Failed lookup for key [%s] in %r / Failed lookup for key [helper] error This is very strange as it only applies to helpers and I have tried passing in helpers, different attributes, and queryset data. I have tried using inlineformset_factory as well as modelformset_factory, and the outcomes are the same. I am trying to use inline formset factory with the parent as the logged in user. My user pk is a UUID (which gets another error related to these formsets: UUID object does not contain variable 'pk'). Here is my view: @login_required(login_url=reverse_lazy('login')) def real_property_req(request): # Import RealPropertyFormSet from forms.py current_user = CustomUser.objects.get(id=request.user.id) submitted = False if request.method == "POST": formset = RealPropertyFormSet(request.POST, instance=current_user) if formset.is_valid(): formset.save() return HttpResponseRedirect('?submitted=True') formset = RealPropertyFormSet(instance=current_user) context = {'formset': formset, 'submitted': submitted} return render(request, … -
Django {% for loop - showing 1 out of 3 values
I added for loop to my html, after I added more data to the Queryset. For some reason it's showing 1 out of 3 values I passed. - I could print them, it's just not showing up on the html. The result page - client_name (in blue), missing product_name + waiting_time (in red) Any ideas? thank you URLs.py ... path('orders/', views.orders_filter_view, name='orders'), ... Views.py def orders_filter_view(request): qs = models.Orders.objects.all() ... for order in qs: client = models.Clients.objects.get(pk=order.client_id) client_name = client.first_name qs.client_name = client_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<< product = models.Products.objects.get(pk=order.product_id) product_name = product.product_name qs.product_name = product_name <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< tz_info = order.created_date.tzinfo qs.waiting_time = order.created_date - datetime.datetime.now(tz_info) <<<<<<<<<<<<<<<<<<<<<<< total_matches = qs.count() context = { 'orders': qs, <<<<<<<<<<<<<<<<<<<<<<<<<<<<< 'view': 'הזמנות', 'total_matches': total_matches, 'titles': orders_titles } return render(request, 'adolim/orders.html', context) Orders.html {% for order in orders %} <tr> <td class="center">{{ order.client_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<< <td class="center">{{ order.product_name }}</td> <<<<<<<<<<<<<<<<<<<<<<<< ... <td class="center">{{ order.delivery_person_name }}</td> {% if order.delivery_status == 'סופק' %} <td class="center green-text">{{ order.delivery_status }}</td> {% else %} <td class="center">{{ order.delivery_status }}</td> {% endif %} <td class="center yellow-text">{{ order.waiting_time }}</td> <<<<<<<<<<<<<<<<< The result page - client_name (in blue), missing product_name + waiting_time (in red) -
how to setup prometheus in django rest framework and docker
I want to monitoring my database using prometheus, django rest framework and docker, all is my local machine, the error is below: well the error is the url http://127.0.0.1:9000/metrics, the http://127.0.0.1:9000 is the begging the my API, and I don't know what's the problem, my configuration is below my requirements.txt django-prometheus my file docker: docker-compose-monitoring.yml version: '2' services: prometheus: image: prom/prometheus:v2.14.0 volumes: - ./prometheus/:/etc/prometheus/ command: - '--config.file=/etc/prometheus/prometheus.yml' ports: - 9090:9090 grafana: image: grafana/grafana:6.5.2 ports: - 3060:3060 my folder and file prometheus/prometheus.yml global: scrape_interval: 15s rule_files: scrape_configs: - job_name: prometheus static_configs: - targets: - 127.0.0.1:9090 - job_name: monitoring_api static_configs: - targets: - 127.0.0.1:9000 my file settings.py INSTALLED_APPS=[ ........... 'django_prometheus',] MIDDLEWARE:[ 'django_prometheus.middleware.PrometheusBeforeMiddleware', ...... 'django_prometheus.middleware.PrometheusAfterMiddleware'] my model.py from django_promethues.models import ExportMOdelOperationMixin class MyModel(ExportMOdelOperationMixin('mymodel'), models.Model): """all my fields in here""" my urls.py url('', include('django_prometheus.urls')), well the application is running well, when in the 127.0.0.1:9090/metrics, but just monitoring the same url, and I need monitoring different url, I think the problem is not the configuration except in the file prometheus.yml, because I don't know how to call my table or my api, please help me. bye. -
Heroku is rolling back my django app back to state when I deployed it. Every File and Data is being reset tot state when I deployed app
Heroku is rolling back. The staticfiles, mediafiles and database which i had deployed are always there but all those files and data added after deployment gets deleted after certain period. This is my Setttings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'rest_framework', 'news', 'Userprofile', 'search', 'bs4', ] SITE_ID = 1 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', ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] ROOT_URLCONF = 'project.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', 'django.template.context_processors.request', 'news.context_processors.provider', 'news.context_processors.promotions', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } 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', }, ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I have tried pushing with several changes but the heroku apps just resets again. PS all those database, static files, media files remains normal as I … -
jQuery DataTables is not a function error randomly occurring in Safari
I've been trying to use DataTables and other jQuery JS libraries in a Django-based web application. I call the .DataTable function in the document ready function. I have had no issues with Firefox and Chrome, but in Safari, some of the times I load the page, I get a .dataTable is not a function error, and the table does not render as a DataTables formatted table. However, other times I load the page, it seems to be working fine. Additionally, it seems that when there are issues with DataTables loading, other libraries also seem to have errors loading as well. I have ensured that jQuery is being imported only once, and prior to DataTables in the code. Even when the errors occur, it seems that DataTables is still being loaded by the browser. As I mentioned, the error only seems to happen in Safari and only seems to occur part of the time. Any insights? -
Set Model Field as Required in Django
Django doesn't enforce NOT NULL at the model/database level. device_serial is neither supposed to have blank '' nor null class Device(models.Model): device_serial = models.CharField(max_length=36, unique=True, null=False, blank=False) ....etc The statement below works totally fine! I expect it to fail because device_serial is required. It shouldn't accept empty string '' Device.objects.create(device_serial='') How can I make a field required at the model / database level? What could I possibly be doing wrong here? I don't see where did I go wrong. I tried ''.strp() to convert empty string to None but it didn't work -
Custom model permission in django-admin to edit a particular field
Normally, after migrating the models located in models.py, in django-admin you get a set of default permissions for your models. For example: models.py class Appointment(models.Model): time = models.TimeField(auto_now_add=False, auto_now=False, null=True, blank=True) notes = models.TextField(blank=True, null=True) In django-admin I can assign these permissions to a group: appname|appointment|Can add appointment appname|appointment|Can change appointment appname|appointment|Can delete appointment appname|appointment|Can view appointment However, I want to add a new permission to this list that will be able to allow a staff user to change the notes field only, such as: appname|appointment|Can change appointment notes I know I can add it like this: class Meta: permissions = [ ("change_notes", "Can change appointment notes"), ] However, the lines above will only add the permission to the list, and after assigning it to a group nothing happens (the notes field cannot be changed). How can I solve this? Is there any Django extension that can help me add a custom model permission in to edit a particular field? -
how to create a dynamic url in python (apiview,django)?
I want to dynamically add an id to an urlpattern and print that id to my server. for example on http://127.0.0.1:8000/experience/3 I want to print 3 to my server. from django.contrib import admin from django.urls import path,include from core.views import TestView from core.views import ExperienceView from core.views import ProjectView from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('experience/<str:id>', ExperienceView.as_view(),name='experience'), ] class ExperienceView(APIView): ... def delete(self,request,*args,**kwargs,id): connection = sqlite3.connect('/Users/lambda_school_loaner_182/Documents/job-search-be/jobsearchbe/db.sqlite3') cursor = connection.cursor() req = request.data print(id) return Response(data) -
Using DJANGO_SETTINGS_MODULE in a script in subfolder
In order to populate the database of my Django application, I created a small script that reads a CSV (a list of filenames) and creates objects accordingly: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') import django django.setup() import csv import sys from myapp.models import Campaign, Annotation campaign_name = "a_great_name" path_to_csv = "filenames.csv" with open(path_to_csv) as f: reader = csv.reader(f) filenames = [i[0] for i in reader] new_campaign = Campaign.objects.create(name=campaign_name) for i in filenames: new_annotation = Annotation( campaign=new_campaign, asset_loc = i) new_annotation.save() I saved this script at the root of my project: myrepo/populator.py and it worked fine. … until I decided to move it into a subfolder of my project (it’s a bit like an admin tool that should rarely be used): myrepo/useful_tools/import_filenames/populator.py Now, when I try to run it, I get this error: ModuleNotFoundError: No module named 'myproject' Sorry for the rookie question, but I’m having a hard time understanding why this happens exactly and as a consequence, how to fix it. Can anybody help me? -
Invalid urls structure in Django
I have a simple structure Shop_list --> Product_list --> Product_detail I hava an error. When I click to the shop I see products for ALL shops. The reason of the error is invalid urls.py logic I tried to use slug but did not receive result. I need to see products only for clicked shop I want to achieve it by this : start_url/ Click to the shop --> start_url/shop1_url Click to the product --> start_url/shop1_url/product1_url models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE) title = models.CharField(max_length=200) price = models.CharField(max_length=200) urls.py from .views import HomePageView, ProductListView, produt_detail urlpatterns = [ path('', HomePageView.as_view(), name='shop_list'), path('<int:pk>/', ProductListView.as_view(), name='product_list'), #path('tags/<slug>/', ProductListView.as_view(), name='product_list'), path('product/<int:pk>/', views.produt_detail, name='product_detail'), ] views.py class HomePageView(ListView): model = Shop template_name = 'blog/shop_list.html' page_kwarg = 'shop' context_object_name = 'shops' class ProductListView(ListView): model = Product template_name = 'blog/product_list.html' page_kwarg = 'product' context_object_name = 'products' def produt_detail(request, pk): print(request) product = get_object_or_404(Product, pk=pk) return render(request, 'blog/product_detail.html', {'product': product}) shop_list.html {% for shop in shops %} <div class="col-md-4"> <div class="card mb-4 box-shadow"> <a href="{% url 'product_list' pk=shop.pk %}"> <img class="card-img-top" src="{{shop.image.url}}" alt="Card image cap" style="width:120px;height:120px;margin:auto;"> </a> ... {% endfor %} -
Creating choices in model based on other models
So what I want to do, is how can I create a choice (CUSTOMER_ADDRESS_CHOICE) to take customer_address field from Customers model or just typical string like "personal collection"? What i mean by that is for example: When my client want to collect his order from shop, it will outputs string but when he want to send it, it will shows up his address. class Customers(models.Model): textcustomer_id = models.AutoField(primary_key=True, null=False) customer_name = models.CharField(max_length=100, null=True) phone_number = models.CharField(max_length=9, null=True) customer_adrress = models.CharField(max_length=10, null=True) def __str__(self): return f'{self.customer_id}' class Meta: verbose_name_plural = "Customers" class Orders(models.Model): CUSTOMER_ADDRESS_CHOICE = ( ('ADRES KLIENTA', 'ADRES KLIENTA'), ('ODBIÓR OSOBISTY', 'ODBIÓR OSOBISTY'), ) STATUS_CHOICES = ( ('W TRAKCIE', 'W TRAKCIE'), ('ZAKOŃCZONE', 'ZAKOŃCZONE'), ) PAYMENT_STATUS_CHOICES = ( ('NIEZAPŁACONE', 'NIEZAPŁACONE'), ('ZAPŁACONE', 'ZAPŁACONE'), ) order_id = models.AutoField(primary_key=True, null=False) order_date = models.DateField(auto_now_add=True, null=True) customer_id = models.ForeignKey(Customers, on_delete=models.SET_NULL, null=True) customer_address = models.CharField(max_length=20, choices=CUSTOMER_ADDRESS_CHOICE, null=True) cost = MoneyField( decimal_places=2, default=0, default_currency='PLN', max_digits=11, ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, null=True) payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, null=True) def __str__(self): return f'{self.order_id}' class Meta: verbose_name_plural = "Orders" -
django.template.exceptions.TemplateDoesNotExist: index.html
Internal Server Error: / Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/amandeepsinghsaini/Django_projects/First_projects/first_app/views.py", line 6, in index return render (request,'index.html', context=my_dict) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html -
static files not found 404 django on development server
i couldn't find a solution after trying alot of solutions here, my problem is i'm running an ASGI app on a devlopement server and i can't get static files nor urls,it's working perfectly on local but not in server this server is running ubuntu and using apache2, i couldn't deploy because apache don't support asgi so i wanted just to run it as local , this is the apache conf on server ProxyPass /checkAuth2 http://localhost:8000 ProxyPassReverse /checkAuth2 http://localhost:8000 ProxyPreserveHost On so to run the app i should go to http://server/checkAuth2 settings.py BASE_DIR = os.path.abspath(os.path.dirname(file)) INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'checkurl', ] STATIC_URL = '/static/' print(BASE_DIR) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), index.html <link rel="stylesheet" href="{% static 'checkurl/css/bootstrap.min.css' %} "> <script src="{% static 'checkurl/js/jquery.min.js' %}"></script> <script src="{% static 'checkurl/js/bootstrap.min.js' %}"></script> path of static folder: project --checkurl --static --checkurl **--static** --css --js when i run server : i get this url http://server/checkAuth2/checkurl and for the files i get : http://server/checkurl/static/css.. which's not found i appreciate your help about this as i'm stuck here for 3 days, thank you!