Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I have Interprocess Communication with Django Channels?
I am building an architecture where I have several Services that runs in parallel, one of them serves the client application, which communicates through Websockets, call it Frontend. I choose Django with Channels for its implementation. I have another service (implemented in Python too) that needs to communicate with the Frontend, I need to do it through network sockets using a simple custom protocol. How can I integrate those services that way? I took a look at the Cross-Process Communication docs but I did not figured out how to do it. Can I push messages to a channel from any Python process? -
Use @propert based attr as Model slug, django's views?
I am trying to use an attribute created using the @property decorator im my model as a slug field for django DetailsView, as follow: class Province(models.Model): name = models.CharField(max_length=30) code = models.CharField(max_length=10) @property def slug(self): return slugify(self.name) My url: path("map/<slug:slug>", MyView.as_view()) My view: class MapTemplateView(DetailView): template_name="myapp/map.html" context_object_name = "province" model = Province But when accessing page I get the following exception: Cannot resolve keyword 'slug' into field. Choices are: code, id, name -
Post request to external Rest Service using Django - use returned json to update model
I require some advice on the best way to implement the following details using Camunda Rest API and Django: 1) User is presented with a form - Selects the details and then does a POST request to camunda using 'http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start' the details sent in this POST request consist of 3 variables in a JSON RAW : in the form of : {"variables": {"UserID" : {"value" : "user.", "type": "String"}, "OrganisationID" : {"value" : "some value", "type": "String"} }, "businessKey" : "SomeBusinessKey" } from views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import StartProject import requests class StartProcessView(TemplateView): template_name = 'startdeliveryphase.html' def get(self, request): form = StartProject() return render(request, self.template_name, {'form':form}) def post(self,request): form = StartProject() url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start" payload = "{\"variables\":\r\n {\"Username\" : {\"value\" : \"[form.Username]\", \"type\": \"String\"},\r\n \"OrganisationInitiating\" : {\"value\" : \"[form.OrganisationInitiator]\", \"type\": \"String\"}},\r\n \"businessKey\" : {form.businessKey}\r\n }" headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data = payload) return render(response, self.template_name, {'form':form}) The response is returned as a 200 along with a JSON payload in the form: { "links": [ { "method": "GET", "href": "http://localhost:8080/engine-rest/process-instance/fbff8359-84cd-11ea-a2e1-00155d891509", "rel": "self" } ], "id": "fbff8359-84cd-11ea-a2e1-00155d891509", "definitionId": "Process_B_PerProject:1:71921815-737c-11ea-91a6-00155d891509", "businessKey": "SomeBusinessKey", "caseInstanceId": null, "ended": false, "suspended": false, "tenantId": … -
django model and templates
I'm new to django, I'm trying to make a display for an e-commerce site enter image description here I would like to display only the sub-categories corresponding to the category -
Error accessing AWS elasticache redis in cluster mode) + TLS Enabled from django service
I'm trying to connect AWS elasticache(redis in cluster mode) with TLS enabled, the library versions and django cache settings as below ====Dependencies====== redis==3.0.0 redis-py-cluster==2.0.0 django-redis==4.11.0 ======settings======= CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com:6379/0", 'OPTIONS': { 'PASSWORD': '<password>', 'REDIS_CLIENT_CLASS': 'rediscluster.RedisCluster', 'CONNECTION_POOL_CLASS': 'rediscluster.connection.ClusterConnectionPool', 'CONNECTION_POOL_KWARGS': { 'skip_full_coverage_check': True, "ssl_cert_reqs": False, "ssl": True } } } } It doesn't seem to be a problem with client-class(provided by redis-py-cluster) since I'm able to access from rediscluster import RedisCluster startup_nodes = [{"host": "redis://xxxxxxx.mc-redis-cache-v2.zzzzz.usw2.cache.amazonaws.com", "port": "6379"}] rc = RedisCluster(startup_nodes=startup_nodes, ssl=True, ssl_cert_reqs=False, decode_responses=True, skip_full_coverage_check=True, password='<password>') rc.set("foo", "bar") rc.get('foo') 'bar' but I'm seeing this error when django service is trying to access the cache, is there any configuration detail that I might be missing? File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 32, in _decorator return method(self, *args, **kwargs) File "/usr/lib/python3.6/site-packages/django_redis/cache.py", line 81, in get client=client) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 194, in get client = self.get_client(write=False) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 90, in get_client self._clients[index] = self.connect(index) File "/usr/lib/python3.6/site-packages/django_redis/client/default.py", line 103, in connect return self.connection_factory.connect(self._server[index]) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 64, in connect connection = self.get_connection(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 75, in get_connection pool = self.get_or_create_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 94, in get_or_create_connection_pool self._pools[key] = self.get_connection_pool(params) File "/usr/lib/python3.6/site-packages/django_redis/pool.py", line 107, in get_connection_pool pool = self.pool_cls.from_url(**cp_params) File "/usr/lib/python3.6/site-packages/redis/connection.py", line 916, … -
How can I make chained multiple choice fields in Django with JQuery?
I want to make a chained multiple choice field. I have working code for chained dropdown boxes below. I want to be able to choose more than one option at each level and have the next level return all records for each of the selected values. How can I make this happen? (my code is not very DRY, so appreciate any notes on that as well, but that is secondary) models.py class Nace_Level_1(models.Model): code = models.CharField(max_length=1) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_2(models.Model): parent = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE) code = models.CharField(max_length=2) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_3(models.Model): parent = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE) code = models.CharField(max_length=4) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_4(models.Model): parent = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE) code = models.CharField(max_length=5) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name class Nace_Level_5(models.Model): parent = models.ForeignKey(Nace_Level_4, on_delete=models.CASCADE, blank=True, null=True) level_3 = models.ForeignKey(Nace_Level_3, on_delete=models.CASCADE, blank=True, null=True) level_2 = models.ForeignKey(Nace_Level_2, on_delete=models.CASCADE, blank=True, null=True) level_1 = models.ForeignKey(Nace_Level_1, on_delete=models.CASCADE, blank=True, null=True) code = models.CharField(max_length=6) name = models.CharField(max_length=200) short_name = models.CharField(max_length=100) notes = models.TextField() def __str__(self): return self.short_name forms.py class NaceForm(forms.ModelForm): … -
multivaluedictkeyerror post django
I have a views.py where i get a list of value from user checked checkbox now i want it to store in database views.py def ResultTest(request): var = request.POST.get('selectedTests') request.session['var'] = var def PostTest(request): if request.method == 'POST': test = UserTest() var = request.session['var'] test.TestSelected = request.POST['var'] i have 2 function in ResultTest function i am getting the user checked result and i want that result to get store in database from PostTest function as i have a form which get submitted along with the result of checked checkbox . Being more specific after user checked the checkbox page redirect to next form where user get to fill a form and there is the value present which is selected by the user in previous checkbox page so now with other form details i want to save the checked result. -
psycopg2 installing within docker
I am learning django,currently while installing psycopg2 with the following command docker-compose exec web pipenv install psycopg2 binary==2.8.3 I got this error and my python version within docker is Python 3.7.7 the error message I got is Warning: Python 3.6 was not found on your system… You can specify specific versions of Python with: $ pipenv --python path/to/python can someone help me to find out the solution or the command to specify the python version -
How to prevent Throttling issue with celery workers?
I want to build script to pull data from amazon api, interesting thing in amazon api that they have strict Throttling rules by different endpoints, e.g.: Maximum request: quota 30 requests Restore rate: One request every two seconds Hourly request quota: 1800 requests per hour So for one account we can do 30 requests at one time without throttling, but not more than 1800 per hour. Restore rate means - that after we did 30 requests at once we have to wait 60 seconds(2 seconds * 30 request) to make again 30 requests at once. First I wanted to implement that with celery, but in this case need to use global lockers, which seems isn't best solution, and hard to maintain. In nodejs worlds we can use something like https://www.npmjs.com/package/bottleneck. const limiter = new Bottleneck({ maxConcurrent: 1, minTime: 333 }); limiter.schedule(() => myFunction(arg1, arg2)) .then((result) => { /* handle result */ }); Any similar libs in python, or maybe just good suggestion how to implement that, with ability to monitor, and reschedule if fail. -
Why i am see server error 500 in my website when Debug = False in django
I am see Server Error 500 in my website [www.softdlr.com] after i make Debug = Flase in settings.py this problem appear when i do search in other language ( except English ) when i use contact form how to fix this error (My priorities is to fix the contact form that i using gmail ) forms.py # contact form class ContactForm(forms.Form): contact_name = forms.CharField(required=True,label='Your name ') contact_email = forms.EmailField(required=True,label='Your email ') title = forms.CharField(required=True,label='The Subject') content = forms.CharField(required=True,label='Full Deatils ',max_length=500,widget=forms.Textarea(attrs={"rows":5, "cols":30}) ) views.py from django.core.mail import send_mail from first_app import forms from django.shortcuts import render from .forms import ContactForm from django.core.mail import EmailMessage # Contact form view def contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') title = request.POST.get('title') template = loader.get_template('html_file/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'title' : title, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['myemail@gmail.com'], headers = { 'Reply To': contact_email } ) email.send() return redirect('Success') return render(request, 'html_file/contact_us.html', {'form':Contact_Form }) settings.py # email message contact EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'smtp.gmail.com' EMAIL_HOST_USER= 'myemail@gmail.com' EMAIL_HOST_PASSWORD= 'mypass' EMAIL_USE_TLS= True … -
I want to beat goggle search which framework should i use django or flask
I wanted to create a search engine better than google. I did some research and found that search engine uses machine learning and deep learning, python is best at it. So i have chosen python but now which framework to use django or flask -
I want to get data based on header menu from the same table
Here is my code: models.py class HeaderMenu(models.Model): header_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.header_menu class SubMenu(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.CASCADE) sub_menu = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.sub_menu class Category(models.Model): sub_menu = models.ForeignKey(SubMenu, on_delete=models.CASCADE) category = models.CharField(max_length=150, primary_key=True) def __str__(self): return self.category class Links(models.Model): header_menu = models.ForeignKey(HeaderMenu, on_delete=models.SET_NULL, null=True) sub_menu = models.ForeignKey(SubMenu, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) link_name = models.CharField(max_length=255) link_url = models.URLField() hits = models.IntegerField() def __str__(self): return self.link_name The table in my database: table whole data My requirement: let say there are 5 links in link_url under sports category under Home tab I want to render all the link name under the home(header_menu) > sports(category) > links like > home> home Submenu > Sports > and all the links name not whole table Help me out to write the view for this problem Thanks :) -
KeyError at /recommend/ in combined_features
why I am getting this error in combined features why this appears and show why df or local variables assigned def recommendation(Movie): Movie = Movie.lower() try: df.head() cosine_sim.shape except: cosine_sim = recommender_sim() if Movie not in df['title'].unique(): return('Search for another Movies') else: indices = pd.Series(df.index, index=df['title']) # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] sim_scores = [] for i in range(len(sim_scores)): movie_indices = sim_scores[i][0] sim_scores.append(df['title'][movie_indices]) return sim_scores def recommend(request): if request.method == 'GET': movie = request.GET['movie'] movies = recommendation(movie) movie = movie.upper() if type(movies) == type('string'): return HttpResponse('recommend.html', movie=movie, movies=movies, t='s') else: return HttpResponse('recommend.html', movie=movie, movies=movies, t='sim_scores') return render(request, 'recommend.html') -
How to convert geojson file into class model in django
I have geojson data in the URL. Here is the URL: https://publoccityhealthdata.s3.us-east-2.amazonaws.com/chi_boundries.geojson I need to generate model class for Django using ogrinspect from django.contrib.gis.db import models -
How to return custom sql query that goes through the serializer in django
I am running a custom query through a serializer in Django so that I can use the data on the frontend. The serializer however returns the full objects or records from the database. How can I have it return only the fields that I want it to return as indicated in my query? views.py from .models import Property from .serializers import PropertySerializer from rest_framework import generics from django.views.generic.list import ListView from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status # class PropertyListCreate(generics.GenericAPIView): @api_view(['GET', 'POST']) def propertyListCreate(request): if request.method == 'GET': properties = [] # properties = Property.objects.all() properties = Property.objects.raw("SELECT id as 'id', suburb, COUNT(*) FROM properties_property group by suburb") serializer = PropertySerializer(properties,context={'request': request} ,many=True, read_only=True) return Response({'data': serializer.data}) models.py from django.db import models class Property(models.Model): Title = models.CharField(max_length=255) Price = models.IntegerField() Area = models.FloatField() Bedrooms = models.FloatField() Bathrooms = models.FloatField() Parking = models.FloatField() Suburb = models.CharField(max_length=255) Address = models.CharField(max_length=255) Link = models.CharField(max_length=255) Date = models.CharField(max_length=255) serializers.py from rest_framework import serializers from .models import Property class PropertySerializer(serializers.ModelSerializer): class Meta: model = Property fields = ('id', 'Title', 'Price', 'Area', 'Bedrooms', 'Bathrooms', 'Parking', 'Suburb', 'Address', 'Link', 'Date') Output that I am receiving: The desired output would be the following: -
'User' object has no attribute 'is_staff' Django
i am getting an AttributeError while creating superuser for my model, that's showing AttributeError at /admin/login/ it would be great if anybody could help me out where i am doing thing wrong. thank you so much in advance. here below is my working code; models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50, blank=True) avatar =models.ImageField(upload_to='avatar' , blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('email must me set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Super User must have is_superuser=True') return self._create_user(email, password, **extra_fields) -
Using Ajax to receive total amount due before submitting to database
Trying to use Ajax to calculate and display the sum before I submit anything to the database. At the moment this is what I have, but I can't seem to get anything to display. I'm trying to start small and see if I'm even able to display the values in the fields.. Is my view for final_price wrong? Or did I mess up somewhere in the Jquery? I'm still new to Ajax, so I'm not sure where I went wrong (following tutorials) Book Price: $10 (input field) Delivery charge: $3 (input field) Delivery type: $5 (input field) [calculate] [submit] Final Result: $18 (result of adding the fields above when user clicks the calculate button) calculate button will display $18 submit button will finalize the results and send the values to the database. This is my model for the table class book(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) book_price = models.IntegerField() delivery_charge = models.IntegerField() delivery_type = models.IntegerField() final_result = models.IntegerField() def save(self, *args, **kwargs): self.final_result = self.book_price + self.delivery_charge + self.delivery_type print(self.final_result) super(book, self).save(*args, **kwargs) views.py for the form def final_price(request): response_data = {} if request.method == 'POST': form = RequestForm(request.POST) book_price = request.POST.get('book_price') delivery_charge = request.POST.get('delivery_charge') delivery_type = request.POST.get('delivery_type') response_data['book_price'] … -
Get profile from user's foreign key django
I am trying to get my customer's details but, having issues filtering it in the serial from the foreign key Customer. Here is what I have now: Serializers: class CustomerOrderSerializer(serializers.ModelSerializer): customer = OrderCustomerSerializer() class Meta: model = CustomerDetails fields = ('id', 'current_selfie', 'customer', 'phone') class OrderSerializer(serializers.ModelSerializer): customer= OrderCustomerSerializer() driver = OrderDriverSerializer() dispensary = OrderDispensarySerializer() order_details = OrderDetailSerializer(many=True) status = serializers.ReadOnlyField(source="get_status_display") customer_details = CustomerOrderSerializer.OneToOneField(customer, related_name='customer_details') class Meta: model = Order fields = ("id", "customer", "customer_details", "dispensary", 'delivery_signature', 'order_rated', "driver", "order_details", "total", "status", "address", "created_at") Model class Order(models.Model): a = 1 b = 2 c = 3 d = 4 e = 5 STATUS_CHOICES = ( (a, "ah"), (b, "bb"), (c, "cc"), (d, "dd"), (CANCELED, "Canceled/Refunded") ) address = models.CharField(max_length=500) created_at = models.DateTimeField(default=timezone.now) customer = models.ForeignKey(CustomerDetails, on_delete=models.CASCADE) delivery_signature = models.ImageField( upload_to='delivery_selfie/', blank=True, default='') delivered_at = models.DateTimeField(default=timezone.now) dispensary = models.ForeignKey(Dispensary, on_delete=models.CASCADE) driver = models.ForeignKey( Driver, blank=True, null=True, on_delete=models.CASCADE) picked_at = models.DateTimeField(default=timezone.now) order_rated = models.BooleanField(default=False) status = models.IntegerField(choices=STATUS_CHOICES) total = models.FloatField() def __str__(self): return str(self.id) class CustomerDetails(models.Model): age = models.IntegerField(default="21", blank=True) address = models.CharField( default='', max_length=254, null=True, blank=True) nick_name = models.CharField(max_length=500, blank=True) average_order = models.FloatField(default="0.0", blank=True) completed_orders = models.IntegerField(default="0", blank=True) customer = models.ForeignKey( Customer, on_delete=models.CASCADE, related_name='customer') customer_type = MultiSelectField( choices=CUSTYPE, default=CUSTYPE, max_length=100) current_selfie = … -
Django API Log to LogStash
I am working on an API in Django and when the API call is finished, we need to log that data using the ELK stack. Here the Setup is Done Properly as I can see new logs showing up in the Logstash but not in Filebeat using which we push the Data to Kibanna. I am uploading screenshots for the configuration file and other details here. Please be Patient Code Segment from Django logger = logging.getLogger(__name__) logging.config.dictConfig( { "version": 1, "disable_existing_loggers": False, "formatters": { "console": {"format": "%(name)-12s %(levelname)-8s %(message)s"}, "file": {"format": "%(asctime)s %(levelname)s-%(message)s"}, }, "handlers": { "console": {"class": "logging.StreamHandler", "formatter": "console"}, "file": { "level": "DEBUG", "class": "logging.FileHandler", "formatter": "file", "filename": "/home/dhruv/elk_log/debug.log", }, }, "loggers": {"": {"level": "DEBUG", "handlers": ["console", "file"]}}, } ) # Create your views here. class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_data = request.data["file"] decoded_file = file_data.read().decode("utf-8").splitlines() file_serializer = FileSerializer(data=request.data) print("File data is", request.data["file"]) read_data = csv.DictReader(decoded_file) # s = smtplib.SMTP("smtp.gmail.com", 587) # s.starttls() id, password = settings.GMAIL_ID, settings.GMAIL_PASSWORD print(f"The gmail id and password is {id} {password}") # s.login(id, password) # Reading the Data as for item in read_data: # print(item) print( item["Email ID"], item["To"], item["cc"], item["bcc"], item["subject "], item["body"], ) # msg … -
how to create a django project using pycharm terminal
I created a project in the pycharm called pyshop. After that I downloaded the django 2.1 in my pycharm terminal. Then i went to create a project using the terminal of the pycharm. But it is showing an error like: (venv) C:\Users\shan\PycharmProjects\PyShop>django-admin startproject pyshop. CommandError: 'pyshop.' is not a valid project name. Please make sure the name is a valid identifier. what should i give as a valid identifier ? -
Service makemigrations has neither an image nor a build context specified
Hello I am trying to make workable a project. But when I run the following instruction : docker-compose up I got the following error : ERROR: The Compose file is invalid because: Service makemigrations has neither an image nor a build context specified. At least one must be provided. Here is the yml file docker-compose.yml : version: '3' services: db: image: postgres expose: - "5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/myproject/ ports: - "8000:8000" - "3000:3000" depends_on: - db - makemigrations - migrations makemigrations: command: python manage.py makemigrations --noinput volumes: - .:/myproject/ depends_on: - db migrations: command: python manage.py migrate --noinput volumes: - .:/myproject/ depends_on: - db Could you help me please ? -
I want to group by the same date the errors (in django models)
I want to group together the errors that had been created on the same date class Error(models.Model): # Audit fields created_on = models.DateTimeField(auto_now_add=True) @classmethod def update_repeat_count(cls, app_error: 'Error'): # Sí el error es del mismo día que agrupe los errores sino nada if app_error.created_on.datetime.date[0] == app_error.created_on.datetime.date[1]:#I am not sure if the "if" is right because I can't try it in develop cls.objects.filter(pk=app_error.pk).update(repeat_count=F('repeat_count') + 1) app_error.repeat_count += 1 post_save.send(sender=cls, instance=app_error, created=False, update_fields=('repeat_count',)) Lots of thx for hellping me -
How can I use template blocks in django?
I'm trying to load a header template into my index with {% block %} but I can't get it to load index.html <body> <header> {% block header %}{% endblock %} </header> <h1>Hello</h1> </body> header.html {% extends "index.html" %} {% block header %} <div class="header"> <a href="/category/"><i class="fas fa-archive"></i></a> <a href="../"><i class="fas fa-home"></i></a> <h1>hey</h1> </div> {% endblock %} views.py def index(request): categories = Category.objects.all() context = {'categories': categories} return render(request, 'category/index.html', context) The app is installed in the settings. -
Django join models based on unique key
I have a situation where I can't join models based on foreign key. I want to join them based on common key that is basically foreign key to third table. Have a look at code: class Thread(models.Model): timestamp = models.DateTimeField(default=datetime.now) class Chat(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=2000) thread = models.ForeignKey(Thread, on_delete=models.CASCADE) read = models.BooleanField(default= 0) timestamp = models.DateTimeField(default=datetime.now) class User_Thread(models.Model): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE) reciever = models.ForeignKey(User, related_name='reciever', on_delete=models.CASCADE) I want to join Chat and User_Thread models based on same thread. How can I achieve this? Any thoughts? -
MultiValueDictKeyError - stripeToken Django error
the error message i am receiving in my template is --MultiValueDictKeyError at /checkout/ 'stripeToken'-- I can't seem to find a solution anywhere online. i have highlighted areas in the code where stripeToken occurs. Any suggestions would be appreciated as I am stuck on this for quite some time now! views.py import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator try: stripe_pub = settings.STRIPE_PUBLISHABLE_KEY stripe_secret = settings.STRIPE_SECRET_KEY except Exception as e: raise NotImplementedError(str(e)) # stripe_pub = "pk_test_AueCfYJ1QIxjLej496MIA43t00BNIWgUb6" stripe.api_key = stripe_secret def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: new_order = Order.objects.get(cart=cart) except Order.DoesNotExist: new_order = Order() new_order.cart=cart new_order.user = Profile.objects.get(user=request.user) # new_order.user = Profile.objects.get(user=request.user) new_order.order_id = id_generator() new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = UserAddress.objects.filter(user=request.user) billing_addresses = UserAddress.objects.get_billing_addresses(user=request.user) # if 'stripeToken' in request.POST: …