Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - annotation produces duplicate joins
The following annotation produces duplicates .annotate( **{ f"{key}_bundle_id": F('item__child_link__parent_item__bundle__id'), f"{key}_bundle_name": F('item__child_link__parent_item__bundle__name') } ) Both of these annotations join across a many to many table to get the id and name of the joined table. I would expect this to produce a join, and select both the id and name from the join. Instead it duplicates the join and selects the id from 1 set and the name from the other. Is there a solution to work around this or do annotations always produce their own joins? Here's the sql it generates: SELECT T8.id as x_axis_bundle_id, T12.name as x_axis_bundle_name .... INNER JOIN "item" ON ("gmdts"."item_id" = "item"."id") INNER JOIN "link" ON ("item"."id" = "link"."child_id") INNER JOIN "item" T8 ON ("link"."parent_id" = T8."id") INNER JOIN "bundle" T9 ON (T8."id" = T9."item_id") INNER JOIN "link" T10 ON ("item"."id" = T10."child_id") INNER JOIN "item" T11 ON (T10."parent_id" = T11."id") INNER JOIN "bundle" T12 ON (T11."id" = T12."item_id") -
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter?
I need to filter Titles by genre field, I tried to use DjangoFilterBackend, but it didn't work, I don't know, how to create a CustomSearchFilter? Views: class GenreViewSet(ModelCVDViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('name', 'slug') search_fields = ('name', 'slug') lookup_field = 'slug' class TitleViewSet(viewsets.ModelViewSet): queryset = Title.objects.all() serializer_class = TitleSerializer permission_classes = (IsAdminOrReadOnly,) filter_backends = (DjangoFilterBackend, filters.SearchFilter) filterset_fields = ('genre__slug', 'category__slug', 'name', 'year') search_fields = ('=genre__slug', '=category__slug', 'name', 'year') -
Cascade delete of model with GenericForeignKey without using GenericRelation
I'm creating a reusable django app which includes a model with GenericForeignKey which I need to be cascade deleted. This model may be attached to any other. I have no control over target model class as it is outside of the app. This means I can not add GenericRelation field to it and can't force user to add it as target might be in another third-party app. Assuming we have such models (having NO control over Post and PostGroup): class Tag(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() object = GenericForeignKey() class PostGroup(models.Model): title = models.CharField(max_length=255) class Post(models.Model): title = models.CharField(max_length=255) group = models.ForeignKey(PostGroup, on_delete=models.CASCADE) Is there a way to delete Tag in case of PostGroup queryset is being deleted? E.g. not only post_group.delete() but also PostGroup.objects.delete(). -
how can I add a django array element into a js array using an if condition
I have a Django project with data being submitted by form , I am trying to use chart.js to display the data. I need to check whether an array exists() if so then add an item to 'labels' array in 'mycharts.js' . Heres what I have so far django views.py ing1 = request.POST.getlist('ingredients1') ing2 = request.POST.getlist('ingredients2') ing3 = request.POST.getlist('ingredients3') ( I've passed the above into my context ) mycharts.js var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: {chart.js labels: ['{{ing1.0}}', '{{ing2.0}}', {% if ing3|length > 1 %} '{{ing3.0}}', {% endif %}], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], (etc...) if I take out the if statement inside of 'labels' array , then it shows the 'ing1' and 'ing2' headings , but I can't get it to work with this if statement , whats the correct way of doing it. -
Django rest framework and react - CORS issue only on same URLs
I'm using react on the frontend side and Django on the backend. I using corsheaders.middleware.CorsMiddleware ALLOWED_HOSTS = ["127.0.0.1", "localhost"] and for some URLs I have no issue sending a request and for others, I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/actions' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. error. Working URL: http://localhost:8000/api/profiles/auth-data Not working URL: http://localhost:8000/api/actions method: GET settings.py: """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path from corsheaders.defaults import default_headers # 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 = os.environ["GH_BE_SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True PROD = False ALLOWED_HOSTS = ["127.0.0.1", "localhost"] CORS_ALLOW_HEADERS = list(default_headers) + [ "businessId", ] # Application definition # TODO need to check security in PROD ['corsheaders'] … -
How can I query data from two tables in Django, when some of the data is conditional
We have multiple data tables, the 'main' one is Player with the primary key Player Name, which is a foreign key to a few other tables, and a foreign key Team Name which is a foreign key to a table called Team, with Team Name being that primary key. We have this query in SQL: SELECT p.TeamName, AVG(b.G) as avg_games_for_team, AVG(b.OPS) FROM Players as p JOIN batter as b ON p.PlayerName = b.PlayerName GROUP BY p.TeamName ORDER BY avg_games_for_team LIMIT 15; And we can't translate this into Django ORM. I know you're supposed to give some of the code you've tried, but we really aren't able to put anything down into paper. The only thing we can get is something like Players.objects.select_related('Teams').get(TeamName).filter(...) using this as a start. We also know to use .annotate() but can't discover where or how. Thanks! -
django-js-routes resolver not finding url
using https://pypi.org/project/django-js-routes/ along with Vue2 and Inertia.js the resolver.js file is not finding the routes i have included in my JS_ROUTES_INCLUSION_LIST application urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.index, name='index'), path('article/<int:id>/', views.articleDetailsPage, name='article'), ] urlpatterns += staticfiles_urlpatterns() Vue template attempting to call route <template> <div> … <div class="sm:p-6 sm:flex sm:flex-col"> <div v-for="article in articles" :key="article.id" class="sm:text-xl"> <inertia-link :href="route('article', article.id)"> {{article.title}} </inertia-link> </div> </div> … </template> <script> export default { props: [ 'articles', 'num_articles' ], methods: { 'page_name': function() { return 'Articles Page' }, 'route': function(...args) { return window.reverseUrl(...args); }, }, } </script> project urls.py #add articles app urls urlpatterns += [ path('articles/', include('articles.urls')), ] project settings.py # Django JS Routes Inclusion List JS_ROUTES_INCLUSION_LIST = [ 'trends', 'articles:index', 'articles:article', ] I have also tried a settings.py where the list only included the app name, articles, whose urls are not being found error returned in console URL 'article' was not found. The error message is being returned by the django-js-routes resolver.js file -
Failed to connect to remote host when using Stripe webhooks
Created stripe webhook account in Test environmnet and then try "send test webhook"enter image description here -
Django Google log-in/sign up not working even though django-oauth
Following this guide to add google sign-in/sign-up to my django app. Added all the code and it all seemed to be working until the very end when I got this error. Error 400: redirect_uri_mismatch The redirect URI in the request, http://127.0.0.1:8000/accounts/google/login/callback/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/.... However, i visit my credential screen I do see the url correctly reported. What am i doing wrong? -
Gunicorn does not handles connections on Elastic Beanstalk AL2
My gunicorn does not accepts connexion. I'm currently launching gunicorn manually to test why it fails to accept connexion. $ gunicorn --bind :8080 --workers 1 config.wsgi:application --log-level=debug [2021-07-23 16:48:20 +0000] [7943] [INFO] Starting gunicorn 20.1.0 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] Arbiter booted [2021-07-23 16:48:20 +0000] [7943] [INFO] Listening at: http://0.0.0.0:8080 (7943) [2021-07-23 16:48:20 +0000] [7943] [INFO] Using worker: sync [2021-07-23 16:48:20 +0000] [7946] [INFO] Booting worker with pid: 7946 [2021-07-23 16:48:20 +0000] [7943] [DEBUG] 1 workers bash: /opt/python/current/env: No such file or directory This /opt/python/current/env stuff seems to come from old AL1 config but I don't know where it come from. Gunicorn continue to work but without accepting connexions. Here is the output from curl: * Empty reply from server * Connection #0 to host test.skippair.com left intact curl: (52) Empty reply from server * Closing connection 0 -
Database considerations when writing a Django app for personal use only in a local server
I am a Django developer for a startup. The project is about to finish and I will start looking for a new job soon. I would like to use my skills do write a simple app to keep my job search organised and I would like to keep my database running on my localhost. I don't want to spend money and effort hosting the website online as I can simply run it with a local database. The problem is that as I develop my apps I usually nuke my database when some migration didn't go as planned or sometimes when PostgreSQL acts out (as in updates). So I would like to know what are the best options for developing and app with a development database while I have an actual database with valuable data that I don't want to lose. If anybody ever faced this problem I would like to know possible solutions. Thanks! -
Why static files are served locally and not from AWS s3 in my Django project?
I have Django application and I want to serve static and media files from AWS s3 bucket but after configuration only media files are served from s3 and static files are served locally. When I collect static all static files are collected in local staticfiles folder. No files are send to AWS s3 bucket. I had to copy them manually to s3. I use Django==2.1.4, boto3==1.18.3, django-storages==1.11.1 Below I show the configuration in settings.py (some irrelevant parts are removed and I comment STATIC_URL and MEDIA_URL values that I have tried) I tried for example what was advised in this topic Django and S3 Bucket AWS Admin Static files. import os from decouple import config import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['yogahouse-ap.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'storages', ] 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 = 'yogahouse.urls' IMAGEKIT_URL = config('IMAGEKIT_URL') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_STATIC_LOCATION = 'static' DEFAULT_FILE_STORAGE = 'yogahouse.storages.MediaStorage' AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com" AWS_IS_GZIPPED = True STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL … -
How to keep a message within a string instead of showing it on CMD ? python
What does the channel.basic_consume' function return? how i can access to message using variable i want consumed message and show it in browser? i build django application send message to rabbitmq and consume messsage from it to show message in browser like chat import pika, sys global message def consume(room,username): credentials = pika.PlainCredentials('admin', 'admin') parameters = pika.ConnectionParameters('192.168.1.14',5672,'/', credentials) connection = pika.BlockingConnection(parameters) channel = connection.channel() channel.exchange_declare(exchange='topic_exchange', exchange_type='topic') result = channel.queue_declare('', exclusive=True) queue_name = result.method.queue arr= [room,username] binding_key ='.'.join([str(i) for i in arr]) channel.queue_bind(exchange='topic_exchange', queue=queue_name, routing_key=binding_key) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r:%r" % (method.routing_key, body)) channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True) global message #message = channel.start_consuming() return message -
Djngo Signals How to find duplicate in queryset and appoint theme for sender and receiver?
I am using django post_save signals in my BlogComment model and creating duplicate of each object. I want to appoint first duplicate for my sender and second duplicate for my receiver. How to do that in queryset? This queryset for my sender: notifications = Notifications.objects.all().filter(sender=user).order_by('-date') This queryset for my reciver: notifications = Notifications.objects.all().filter(receiver=user).order_by('-date') here is my BlogComment model which creating Notifications objects: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fileds #here signals stating def user_comment(sender, instance, *args, **kwargs): comment= instance blog = comment.blog sender = comment.user commnet_notes = comment.rejected_comment_notes comment_text = comment.comment if sender != blog.author and comment.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=comment.blog.author,text_preview=comment_text[:250], notification_type="New Comment") notify.save() #want appoint this object for receiver in queryset notify2 =Notifications.objects.create(blog=blog, sender=sender, receiver=comment.blog.author, text_preview=comment_text[:250], notification_type="New Comment") notify2.save() #want appoint this object for sender in queryset post_save.connect(BlogComment.user_comment, sender=BlogComment) here my notifications model: class Notifications(models.Model): blog = models.ForeignKey('blog.Blog',on_delete=models.CASCADE,blank=True,null=True) blogcomment = models.ForeignKey('blog.BlogComment',on_delete=models.CASCADE, blank=True,null=True) globalnotifications = models.ForeignKey('blog.GlobalNotifications',on_delete=models.CASCADE,blank=True,null=True) NOTIFICATION_TYPES = (('New Comment','New Comment'),('Comment Approved','Comment Approved'), ('Comment Rejected','Comment Rejected'),('pending post','pending post'),('post approved','post approved'),('post rejected','post rejected'),('global_noti','global_noti')) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.CharField(choices=NOTIFICATION_TYPES,max_length=250,default="New Comment") text_preview = models.CharField(max_length=500, blank=True) help_notes = models.TextField(max_length=1000,default="",blank=True,null=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) is_seen_author_noti = models.BooleanField(default=False) def __str__(self): return … -
Django Admin Selection by Related Tables
I have models named School, Class and Student List. When adding to the student list, there is a class selection. I want to filter these classes by choosing school name and only show classes belonging to that school. How can I do that? When I add on the admin page, only the class selection field comes up. My admin.py file is default for now. How can I filter during this insertion process? Example scenario -> When the add page opens School: "Empty" Class: "Empty because no school has been selected yet" Child: "List of children" -> When a school selected School: "Example School" Class: "Class list of selected school" Child: "List of children" School Model class School(AbstractSchoolBaseModel): city = models.ForeignKey( "country.City", on_delete=models.DO_NOTHING, related_name="city_schools", verbose_name=SchoolStrings.SchoolStrings.city_verbose_name) name = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.name_verbose_name) address = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.address_verbose_name) website = models.CharField( max_length=250, verbose_name=SchoolStrings.SchoolStrings.website_verbose_name) Class Model class Class(AbstractSchoolBaseModel): school = models.ForeignKey( "school.School", on_delete=models.CASCADE, related_name="classes_school", verbose_name=SchoolStrings.ClassStrings.school_verbose_name) instructor = models.ForeignKey( "account.InstructorProfile", on_delete=models.CASCADE, related_name="instructors_school", verbose_name=SchoolStrings.ClassStrings.instructor_verbose_name) name = models.CharField( max_length=50, verbose_name=SchoolStrings.ClassStrings.name_verbose_name) grade = models.IntegerField( verbose_name=SchoolStrings.ClassStrings.grade_verbose_name) Student List Model class StudentList(AbstractSchoolBaseModel): school_class = models.ForeignKey( "school.Class", on_delete=models.CASCADE, related_name="student_list_class", verbose_name=SchoolStrings.StudentListStrings.school_class_verbose_name ) child = models.ForeignKey( "account.ChildProfile", on_delete=models.CASCADE, related_name="children_class", verbose_name=SchoolStrings.StudentListStrings.child_verbose_name) -
Django couldn't display context in template when the conetxt contain path
Usually I can display any variable present in my context, it works. But here when i want to display in template a variable context containing a path it does not work. My path is in the context variable because i can print him in my console. I only encounter this problem with context variables with a path view.py def step0(request): context = {} if request.method == 'POST': context['GV.Levels_m0'] = GV.Levels_m[0] print(context['GV.Levels_m0']) else : None return render(request,"template.html",context) template: {% if export_process_done %} <div class="alert alert-success"><b>Done</b>.The files are exported to {{ GV.Levels16 }} </div> {% endif %} my console : C:\Users\exex\Documents\name\WebApp\Application\media\projectname\process rendering -
how to add a none existing language to django
i tried to add a my language (kurdish - (arabic character)) which is not in the list of languages in django ,i've read several questions and answers but still i get the same error ?: (translation.E004) You have provided a value for the LANGUAGE_CODE setting that is not in the LANGUAGES setting. i add ku folder extension into my /django/conf/locale/ but not worked , i also add this into my settings.py ..... from django.conf import global_settings gettext_noop = lambda s: s LANGUAGES = ( ('ku', gettext_noop('Kurdish')), ) EXTRA_LANG_INFO = { 'ku': { 'bidi': True, # right-to-left 'code': 'ku', 'name': 'Kurdish', 'name_local': u'\u0626\u06C7\u064A\u063A\u06C7\u0631 \u062A\u0649\u0644\u0649', }, } import django.conf.locale LANG_INFO = dict(django.conf.locale.LANG_INFO, **EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = LANG_INFO LANGUAGES_BIDI = global_settings.LANGUAGES_BIDI + ["ku"] -
Django images from s3 bucket result in NoSuchBucket error
All of my images were working, then after editing settings.py (not touching AWS variables), the images no longer show and I get this error. <Error> <Code>NoSuchBucket</Code> <Message>The specified bucket does not exist</Message> <BucketName>gym-workout-files</BucketName> <RequestId>ME2V5DFD368RT8XX</RequestId> <HostId>9VG9pz5/SJ9VryDCkA4FPU5KnTIcqDDT1NG2Blbc2j36A+IwYJcp6zIOR8Z0qUrn0lZcf5qHdRQ=</HostId> </Error> This is how I access the AWS bucket from settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I can clearly check that the bucket name DOES match, and is in all lower-case. I've also tried updating the region directly in settings.py, but that had no effect. Block public access with my bucket is set to OFF, so I'm very confused why the images cannot be accessed. When I try to click on a link from one of my images on AWS, like this one https://gym-workouts-files.s3.amazonaws.com/workout_pics/greatest.jpg, I get an error of AccessDenied. -
How to run cronjobs with dynamic timing
We have course creation platform, in that admin can assign a course to learner in future. So, on the particular time i need to trigger an mail and notification function. Django celery-beat, we can run cron periodically. But i don't want run periodically, i need to run the function based on admin specified time like Netbanking future payments. -
How to wrap every request in additional json object?
I want to separate json object by data and links for easy use. I searched through web but I am unable to find any tutorials or guidance. My current request is this: { 'fieldname': '<data>', 'another_fieldname': '<data>', 'field_with_relation': { 'child_field': '<data>', 'a_child_field': '<data>', }, 'link': '<data>', 'page' : '<data>' } I want this type of JSON Structure: { 'data':{ 'fieldname': '<data>', 'another_fieldname': '<data>', 'field_with_relation': { 'child_field': '<data>', 'a_child_field': '<data>', } }, 'links':{ 'link': '<data>', 'page': '<data>' } } I specifically asking for request it doesn't matter if it is a post, get, update or delete request. I want all my data to follow this specific structure. -
Django - best way to manage existing, auto increment fields with existing data?
This is still in dev, so I am relatively flexible in how to approach this. So I'm importing data (via fixtures, the import works fine) from an existing database into a django application. The source data is not uniformed in how it manages ID & primary keys. Some tables use what seems to be an auto-increment (similar to what django would produce by default). Others use some sort of integers. The relationships in the data dump are established based on those fields. Seems I can keep on using auto-increments in all cases. They are conveniently not named uniformly: id, pk, pk_sometablename, etc. The fixtures I use to import look like this (I generated them using a script based on the datadump, so this can be changed if needs be): { "model": "admin_account.client", "pk": "168", "fields": { "pk_client": "168", My django model: class Client(models.Model): pk_client = models.IntegerField(verbose_name='Pk_client', blank=True, null=True) I need to be able to import the data in such a way that this field, the pk_client field is used as the primary key (it can still remain as an auto-increment). So I tried to change to this: class Client(models.Model): pk_client = models.AutoField(primary_key=True, verbose_name="pk_client", default=-9999) However if I try this migration … -
How to annotate a QuerySet adding row numbers groupped by a field?
I have two models: Model books [id, title, author_id] Model authors [id, name] I need to query books ordered by author name and title: result = Books.order_by('author__name', 'title').value_list('author__name', 'title') But I also need to add a counter to each row which will reset with each new author. The results of the query should be: title name position ----------------------------------------- book1 Dan Brown 1 book2 Douglas Adams 1 book3 Douglas Adams 2 book4 Douglas Adams 3 book5 Douglas Adams 4 book6 Ernest Hemingway 1 book7 Ernest Hemingway 2 book8 Ernest Hemingway 3 book9 John Steinbeck 1 book10 John Steinbeck 2 Is it possible to implement this position field with Django ORM? -
How to POST multiple data in DRF and React with Axios
I have 2 models named Recipe and Step.. I have serialized both to make an API for GET request.. I want to know is there a way to create for POST request so that I can send both the data (steps and recipe) in the same request? models.py: from django.db import models class Recipe(models.Model): title = models.CharField( max_length=50) uuid = models.CharField( max_length=100) def __str__(self): return f'{self.uuid}' class Step(models.Model): step = models.CharField(max_length=300) uuid = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return f'{self.step} - {self.uuid}' serializers.py: from rest_framework import serializers from .models import * class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ['title', 'uuid'] class StepSerializer(serializers.ModelSerializer): class Meta: model = Step fields = ['step', 'uuid'] views.py: from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import * from .models import * @api_view(['GET']) def apiOverview(request): api_urls = { 'List':'/recipe-list/', 'Detail View':'/recipe-detail/<str:pk>/', 'Create':'/recipe-create/', 'Update':'/recipe-update/<str:pk>/', 'Delete':'/recipe-delete/<str:pk>/', 'Steps' : '/steps/<str:pk>' } return Response(api_urls) @api_view(['GET']) def recipeList(request): recipes = Recipe.objects.all() serializer = RecipeSerializer(recipes, many=True) return Response(serializer.data) @api_view(['GET']) def recipeDetail(request, pk): recipe = Recipe.objects.get(uuid=pk) recipe_serializer = RecipeSerializer(recipe, many=False) steps = Step.objects.filter(uuid=pk) steps_serializer = StepSerializer(steps, many=True) return Response({ 'recipe' : recipe_serializer.data, 'steps' : steps_serializer.data }) How can I create a view for POST and handle … -
How can i compare two strings in a template of django?
I am new to Django and i am trying to make a blog website where user first login to create their post. They can update their existing post later. but the problem is other logged in user can also interfere with the post of this user. so i was trying this logic, {% if post.author == user.username %} in my post_detail.html file. i.e. if person who has just logged (user.username) in is the same person who has written this post (post.author) then he is allowed to edit or remove this post. if not then option of edit & remove won't be visible to them on browser. Plz tell me if anything wrong in this if statement as its not working! below are my models.py and other files. #models.py from django.db import models from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.conf import settings from django.utils import timezone # Create your models here. class user_entry(models.Model): # models.Model means that the Post is a Django Model, so Django knows that it should be saved in the database. user = models.OneToOneField(User, on_delete=models.CASCADE) # name = models.CharField(max_length=30) # email = models.EmailField(max_length=254,unique=True) # … -
How to save form data from base.html in django?
In my app, I have created a context_proccessors.py to show the form to base.html file. I am able to show the form in the base.html file. But the problem I am facing is I have no idea how to save that form data from base.html since there is no view for the base.html. Below is my code: models.py class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_posts') post_pic = models.ImageField(upload_to='post_pic', verbose_name="Image") post_caption = models.TextField(max_length=264, verbose_name="Caption") created_date = models.DateTimeField(auto_now_add=True) edited_date = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username}" forms.py from django import forms from post_app.models import Posts class PostForm(forms.ModelForm): class Meta: model = Posts exclude = ('user',) context_proccessors.py from post_app.forms import PostForm def post_form(request): form = PostForm return { 'post_form': form, } I want the form to be displayed on every page so that the user can submit data from anywhere