Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show details of Products acording to thier IDs in django
I'm making one basic ecommerce application in Django.I have 'Item' model. In home page I'm showing only images and names of the products of Item model. when user will select any product, I want to show all the details of that particular product in item-detail.html template. My view.py def detail(request,I_id): try: item_detail = Item.objects.get(pk=I_id) except Item.DoesNotExist: raise Http404("Item not found") return render(request, "item-detail.html",{"item_detail":item_detail} ) When I'm running the server, CSS not supportingenter image description here, but same template working with different function(css working with other function). -
I'm using if else statement in my django and I want print INR price only if value is more than 100 else it should not print anything
but i'm getting error: The view mysite.views.index didn't return an HttpResponse object. It returned None instead. def index(request): A = "https://free.currconv.com/api/v7/convert?q=USD_INR&compact=ultra&apiKey=251f970c1a091e9d0378" responce1 = requests.get(A) INR_INTER0 = (responce1.json()["USD_INR"]) price ={'inr': INR_INTER0} if INR_INTER0>100: return render(request, 'index.html', price) This is my index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>{{index(request)}}</h1> </body> </html> ` -
Dynamically Changing the Amount of Extra Forms Displayed in a Formset
If a user is creating a new form or editing a form that has no formsets, I want a single extra form to be displayed. If the user is editing a form that does have formsets with data then the user should only see the forms that have data and no extra forms should be displayed. I have a way of achieving this (and it works exactly as I need) but I'm wondering if there's a better way that doesn't involve creating two slightly different instances of the same formset: forms.py: Formset = inlineformset_factory(MainModel, OtherModel, formset= ModelFormSet, extra= 1, can_delete= True, fields= '__all__') FormsetALT = inlineformset_factory(MainModel, OtherModel, formset= ModelFormSet, extra= 0, can_delete= True, fields= '__all__') views.py: new_formset = Formset((request.POST or None), instance = current_project) if len(Risk.objects.filter(project_id=project_id)) == 0 else FormsetALT((request.POST or None), instance = current_project) -
'pip' is not recognized as an internal or external command, operable program or batch file on docker web application
I am undergoing a web project using django and docker. The tutorial references how to set up an email service. I registered with AWS and followed a guide of how to link it to docker. The first step is to run "pip install --upgrade boto3". This is followed by the error in the title. How do I install boto3 through docker? -
Jsonresponse in Django working in browser but not in PostMan or Angular
I am trying to send a JSON response from Django back-end to my angular front-end. When I make the request I receive nothing in Postman or Angular but,opening the link in browser seems to be returning the correct result My View is : @api_view(['GET']) def my_view(request): print(request.user.username) return JsonResponse({'username': request.user.username}) When I open http://127.0.0.1:8000/accounts/get_username/ in browser I receive {"username": "aditya8010"} on the web page. But when i do a get request using POSTMAN I recieve { "username": "" } Same with Angular this.http.get("http://127.0.0.1:8000/accounts/get_username/").subscribe((res) => { this.username = JSON.stringify(res["username"]) console.log(this.username," ", res) }) this code also prints an empty username string. Another thing I have noticed is that my print statement in the view does print anything random I put in there when called from POSTMAN or Browser but when I use request.user.username it doesnt print anything when called by POSTMAN. And each time the response code is 200 What am I doing wrong. -
How to add comma separator to integer value in django
In my Django model table, I have a field for salaries. I how do i add comma separator to my entries. e.g 100000 --> 100,000 My model table looks like this class employeeDetails(models.Model): name = models.OneToOneField(CustomUser, on_delete=models.CASCADE, related_name="employee_name") phone_no = models.CharField(max_length=10, blank=True, unique=True) email = models.EmailField(max_length=255, unique=True) description = models.TextField(blank=True, null=True) department = models.CharField(max_length=50, choices=Department_Choices) job_title = models.CharField(max_length=50, choices=Title_Choices) salary = models.IntegerField(max_length=10) <--- FIELD date_employed = models.DateField(default=datetime.now) is_manager = models.BooleanField(default=False) def __str__(self): return self.name.name -
Django get the value of a field between 3 models
I have 3 models in my Django project, then I want to get the related product model's field from Order model and Order_item model. May I know how to get it on the views.py Models.py: class Product(models.Model): product_name = models.CharField(max_length=200) price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) storage = models.PositiveIntegerField() out_of_storage_or_not = models.BooleanField(default=False) description = models.TextField(blank=True, null=True) slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.product_name class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey('Payment', on_delete=models.SET_NULL, blank=True, null=True) order_ref = models.TextField(max_length=20, blank=True, null=True) On the views.py, I can get the related order_item of order, but I also want to get the related products of order_item, and make products.storage - orderitem.quantity while payment completed def payment_process(request): order = Order.objects.get(user=request.user, ordered=False) order_items = order.items.all() context ={ 'order':order } if request.method == 'POST': try: ..... return redirect('payment_success') except ObjectDoesNotExist: return redirect('/') else: return render(request, 'payment.html', context) -
Issue with django URLconfig not finding URL patterns that I've set
I've been testing the waters with Django and getting myself more familiar with web development and I ran into an issue that I need some outside help for. My localhost is showing: Request Method: GET Request URL: http://localhost:8000/blog/about Using the URLconf defined in movie_log.urls, Django tried these URL patterns, in this order: admin/ The current path, blog/about, didn't match any of these. my project urls.py file reads as from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] my urls.py file from the blog folder reads is from . import views urlpatterns = [ path('', views.home, name="blog-home"), path('about/', views.about, name="blog-about"), ] and finally the views.py file in the same "blog" folder is from django.http import HttpResponse def home(request): return HttpResponse('<h1>Blog Home</h1>') def about(request): return HttpResponse('<h1>Blog About</h1>') is there something im missing? -
Gunicorn + Django. ModuleNotFoundError: module named diasmart (my project) not found
My project thread: Where diasmart is the project folder with settings.py, wsgi.py, etc.. (root folder at the screenshot is "src") I have bash file for starting the gunicorn server (start_gunicorn.sh) #!/bin/bash source /root/DiaStore/env/bin/activate exec gunicorn -c "/root/DiaStore/src/gunicorn_config.py" diasmart.wsgi After that, I have a supervisor config that starting gunicorn with start_gunicorn.sh But I got an error start_gunicorn.py: self.callable = self.load() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/root/DiaStore/env/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'diasmart' [2020-07-30 16:50:09 +0000] [109587] [INFO] Worker exiting (pid: 109587) [2020-07-30 16:50:09 +0000] [109585] [INFO] Shutting down: Master [2020-07-30 16:50:09 +0000] [109585] [INFO] Reason: Worker failed to boot. All other things work correctly, I think the error reason is the wrong path in "exec" from start_gunicorn.sh (.. diasmart.wsgi) -
Django, Heroku running migrate raises KeyError
I'm deploying a Django project to Heroku, I've made some local migrations, migrating locally worked. But when pushing the changes to Heroku I'm getting a weird error: Operations to perform: Apply all migrations: admin, agsenze_api, auth, authtoken, contenttypes, farm_api, rest_framework_api_key, sessions, users Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 189, in handle pre_migrate_state = executor._create_project_state(with_applied_migrations=True) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/executor.py", line 79, in _create_project_state migration.mutate_state(state, preserve=False) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 98, in state_forwards state.models[app_label, self.model_name_lower].fields.append((self.name, field)) KeyError: ('agsenze_api', 'coweventsdata') I don't understand where this is originating from but I can see the migrations of this model and app are. But, I don't do delete all migrations and reset the database. How can I fix this migrations and avoid dropping the Database and migrations files completely? -
Django Parler "The 'language_code' attribute cannot be changed directly
I am currently extending a plugin to play well with Django translations and languages. Here is the method in question. Prior to getting translations involved, it worked as needed. I extended the query to pull data from a couple of translation tables. However, I am getting an error, which I am unsure how to deal with. def get_authors_and_article_counts(self, authors): """method returning authors and their article counts""" # first, we collect ids of authors for which we need to get data author_ids = [author.id for author in self.authors.all()] author_ids_tuple_str = '(' + str(author_ids).strip('[]') + ')' #limit subquery to published articles published_clause = """ AND is_published %s AND publishing_date <= %s """ % (SQL_IS_TRUE, SQL_NOW_FUNC, ) query = """ with article_count as ( select author_id, count(*) as article_count from aldryn_newsblog_article where app_config_id = 1 %s group by author_id ) select distinct prof.*, coalesce(ac.article_count, 0) as article_count, author_trans.*, aldryn_people_trans.slug from common_authorprofile prof left join article_count ac on ac.author_id = prof.profile_id left join common_authorprofile_translation author_trans on prof.id = author_trans.master_id left join aldryn_people_person_translation aldryn_people_trans on prof.profile_id = aldryn_people_trans.master_id WHERE prof.id IN %s AND author_trans.language_code = 'ru'; """ % (published_clause, author_ids_tuple_str) print(query) #print(author_ids) raw_authors = list(AuthorProfile.objects.raw(query)) #print(raw_authors) authors = [author for author in raw_authors if author.article_count] … -
How can I redirect a user to Django auth from a webpage not a part of the Django app?
We have a R shiny app server to whose links will be present on our Django website. However we want the user to be taken to login(and check if they have the permission to access) before they are able to access the R shiny app page. We could embed the Shiny app using an iframe on our site, but then anybody can copy the src link and use it to access shiny app without login, later. -
installing latest version of linux and venv
from many days i'm getting errors while installing various libraries like NLP, Django etc ..After investigating about the errors on stackoverflow , i found the reason is uncompatible python version of myvenv can anyone help me in creating a venv with latest version of python installed ? i'm using linux mint -
bad request(400) django-postgresql page error in gcp
my application was successfully deployed to google cloud platform. when i run command glcoud app browse it shows a blank page with bad request(400). this is the details of the error. my app runs well locally. where is the problem coming from? is there any command for checking if everything is perfectly setup in my google platform account? Traceback (most recent call last): File "/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/env/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/env/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/env/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused setting.py from decouple import config BASE_DIR = os.path.dirname(os.path.dirname (os.path.dirname(os.path.abspath(__file__)))) try: SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False except KeyError: SECRET_KEY = config('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'projects', 'crispy_forms', ] CRISPY_TEMPLATE_PACK= 'bootstrap4' 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 = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], … -
Return results according to ForeignKey
I've had a problem with my code for days. I claim to be inexperienced with Django. I would like to get the results according to a specific "CalendarGroups", for example all calendars only of a specific CalendarGroups. The id of the group on which to filter the calendars I would like to pass it through url whit "goup_id". In Url.py: urlpatterns = [ url(r'^$', views.hello, name='hello'), #Prova url(r'^home/$', views.GroupCalendarView.as_view(), name='home'), #Prova url(r'^home/(?P<group_id>\d+)/$', views.CalendarsOfGroupView.as_view(), name='calendar_view'), ] In models.py: class CalendarGroups(models.Model): GRP = ( ('Amazon', 'Amazon'), ('VICHY', 'VICHY'), ) name = models.CharField(max_length = 155, blank=True, null=True) @property def get_html_url(self): url = reverse('', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' class Calendar(models.Model): name = models.CharField(max_length=200) #created_by group = models.ForeignKey(CalendarGroups, on_delete = models.CASCADE, default='') @property def get_html_url(self): url = reverse('cal:calendar_view', args=(self.id,)) return f'<a href="{url}"> {self.name} </a>' In views.py: class GroupCalendarView(generic.ListView): model = CalendarGroups template_name = 'cal/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) #print (context) return context class CalendarsOfGroupView(generic.ListView): model = Calendar template_name = 'cal/calendarOfGroup.html' def get_queryset(self, **kwargs): context = super().get_context_data(**kwargs) return context This is my current code, I don't know how I can use what I pass through "group_id" in views.py. -
Why my Django exception middleware does not log stack trace
I am trying to set up a custom exception handler. # settings.py LOGGING = { // ... 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', }, }, 'loggers': { 'django': { 'handlers': ['applogfile', 'mail_admins'], 'level': 'ERROR', 'propagate': True, } } } When I use the Django default exception handler and there is a Django error, I get an email containing the debug page, including the stack trace. However, I want to have my own exception middleware, so I added the following: # middleware.py from django.utils.deprecation import MiddlewareMixin class MyExceptionMiddleware(MiddlewareMixin): def process_exception(self, request, exception): return render(request, template_name='error_message.html', context={ 'title':'Error', 'message':'Sorry, we encountered an unexpected error' }) # settings.py MIDDLEWARE = [ # other middlewares ... 'middleware.MyExceptionMiddleware', ] After I added this, the debug email that I get is missing the stack trace. It tells me that there is an "Internal server error" at the url, but it doesn't give any details of the errors. I know I can override error handlers (https://docs.djangoproject.com/en/3.0/topics/http/views/#customizing-error-views) which would give me the full stack trace, but I am wondering why when I use a middleware to catch exceptions I don't get the stack trace. -
Relative path to django static file
I am trying to find a way to read a JSON file from static files without hardcoding the path to the file. def value_setup(): with open('path/to/static/config/species.json') as f: data = json.loads(f.read()) values = data["value"] return values Is there a way to open this file with just a relative path from the static folder? -
How can I open a page with only one django model object's info after clicking it's ImageField on another page?
I am displaying django models on one of my website's pages. When I press one's ImageField on the page, I want it to open another page including only that one object. How do I do that ? I thought about using the filter method in my views.py for filtering through my objects and finding that exact one, but I don't know what arguments to use. Any ideas? VIEWS.PY from django.shortcuts import render import requests from . import models def index(request): return render(request, 'base.html') def new_search(request): ********NOT IMPORTANT (I THINK)******** search = request.POST.get('search') models.Search.objects.create(search=search) objects = models.Object.objects.all() results = objects.filter(name__contains=search).all() args = { 'results': results } return render(request, "my_app/new_search.html", args) def individual_page(request): link = request.POST.get('object-link') objects = models.Object.objects.all() return render(request, "my_app/individual_page.html") MY TEMPLATE {% extends "base.html" %} {% block content %} {% load static %} <h2 style="text-align: center">{{ search | title }}</h2> <div class="row"> {% for result in results %} <div class="col s4"> <div class="card medium"> <div class="card-image"> <a name="object-link" href="{% url 'individual_page' %}"><img src="{{ result.image.url }}" alt=""></a> </div> <div class="card-content"> <p>{{result.name}}</p> </div> <div class="card-action"> <a href="/">View listing: Price TEST</a> </div> </div> </div> {% endfor %} </div> {% endblock %} So, the thing I want to do is: when I press … -
Django Rest Framework get_queryset() does not send full result to TestCase
I am running into a strange issue where my get_queryset() method for my ViewSet is grabbing the correct results but one of the objects in the query gets dropped as it's being returned to my test case. I can't really post any code but I can display parts of the test that fail and some logs. Has anyone ever encountered this problem? Here is the print out of my model field names just before the return statement in get_queryset(self): QUERYSET len: 3 QUERYSET should return: <QuerySet ['Test', 'Test', 'Test']> The assertion in my TestCase after calling the viewset and storing the response in res self.assertEqual(len(res.data), 3) AssertionError: 2 != 3 I don't understand how the ViewSet's get_queryset() clearly shows that the length is 3, yet the response returned from the ViewSet only has 2 objects out of the 3 in it. I've also tested serializing the response.data and testing that length also shows up as 2 but should be 3. So confused. I hope this is enough info for someone to go off of. -
Graphql Mutation Error: "Number of args exceeds number of fields",
I'm trying to build an API using graphql in django. I have a set of drivers here. Whenever I want to create a new driver sample I face to the following error: "message": "Number of args exceeds number of fields" I don't really know what this error actually means! Here is Mutation Definition in schema: class CreateDriver(Mutation): class Arguments: first_name = graphene.String() last_name = graphene.String() email = graphene.String() username = graphene.String() phone_no = graphene.String() national_id = graphene.String() driver = graphene.Field(DriverType) def mutate(self, info, first_name, last_name, email, username, phone_no, national_id): return CreateDriver( first_name, last_name, email, username, phone_no, national_id ) class Mutations(ObjectType): create_driver = CreateDriver.Field() and this is Driver model: class Usermodel(User, models.Model): phone_no = models.CharField( max_length=11, blank=True, verbose_name="Phone Number" ) def __str__(self): return self.username class Driver(Usermodel, models.Model): national_id = models.CharField( max_length=10, blank=True, verbose_name="National ID" ) profile_picture = models.ImageField( blank=True, null=True ) STATUS_CHOICES = [ ('1', 'Free'), ('2', 'Busy') ] status = models.CharField( max_length=1, choices=STATUS_CHOICES ) rating = models.FloatField( default=-1 ) ranking = models.IntegerField( default=-1 ) class Meta: verbose_name = 'Driver' verbose_name_plural = 'Drivers' -
How do I create automatically inherited url paths for views?
I am trying to create a blog app in Django. I am new to Django so I am still figuring things out. One thing I am trying to do is to have pages inherit their path from the previous views. For example I have a page: "all_blogs" which lists all of the different blog series available and has the path of: "localhost:8000/blog/". When I select a series, the path inherits the name of the selected series: "localhost:8000/blog/series_name". This page will then display all the articles that exist under that series(still figuring this out. Will probably ask another question separately regarding this topic). When the article is selected, I want the path to inherit the previous paths:(e.g. localhost:8000/blog/series_name/episode). If I make the path for articles in urls.py :"path(int:episode, views.blogArticles, name='blogArticles')" I get a path of: "localhost:8000/blog/series_name/blog/episode" instead of"localhost:8000/blog/series_name/episode". If I set the urls.py path to "path('str:series_name/<int:episode', views.blogArticles, nane='blogArticles')" I get the error "NoReverseMatch at /blog/concert_series Reverse for 'blogArticles' with arguments '(1,)' not found. 1 pattern(s) tried: ['blog/(?P<series_name>[^/]+)/(?P[0-9]+)$']" any assistance is appreciated. models.py from django.db import models class BlogSeries(models.Model): series_name = models.CharField(max_length=200) series_title = models.CharField(max_length=200) series_image = models.ImageField(upload_to='blog/series/images/', null=True) series_date = models.DateTimeField(null=True) series_desc = models.CharField(max_length=400, null=True) class Meta: verbose_name = "Series" verbose_name_plural … -
my user_id profile database is null, how i insert the value in user_id?
Why does my data look like this? can i make the value in user_id? this is my models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) nama = models.CharField(max_length=30, blank=True) nik = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=75, blank=True) nomor_hp = models.TextField(max_length=15, blank=True) def __str__(self): return self.user @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): try: instance.profile.save() except ObjectDoesNotExist: Profile.objects.create(user=instance) -
How to get data from another class with ForeignKey relationship
I have two class in my Model.py one is Blog class and another is comment class. i want to get comment of related blog class i mean if comment_1 has ForeignKey of blog_1 then while retrieving blog_1 i want to get comment also at the same time models.py class Blog(models.Model): title = models.CharField(max_length=200) content = models.TextField() image = models.CharField(max_length=200) created_at = models.DateTimeField(timezone.now()) views = models.IntegerField(null=True, blank=True) def __str__(self): return self.title class comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.EmailField(max_length=100) comment = models.TextField() image = models.CharField(max_length=200, null=True, blank=True) commented_at = models.DateTimeField(timezone.now()) def __str__(self): return self.blog.title Serializers.py class CommentSerializer(serializers.ModelSerializer): # blog = BlogSerializer() class Meta: model = comment fields = '__all__' class BlogSerializer(serializers.ModelSerializer): comment = CommentSerializer(many=True) class Meta: model = Blog fields = ['id', 'title', 'content', 'image', 'created_at', 'comment'] views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all() serializer_class = BlogSerializer pagination_class = MyLimitOffSetPaginations filter_backends = [SearchFilter] search_fields = ['title', 'content'] I have try in this way but i am getting error the error is saying that Blog object has no attribute comment but i want to get comment of related blog please any one can help me to get blog with comment that has ForeignKey of blog -
Javascript multiple elements toggle got unexpected results
I'm working on a project in Django, where on each page I have comments, generated automatically from the database. For each of them I want to have a form in which someone can reply to those comments. I do not want the form to be visible all the time, but only when the reply button is pressed. I tried to use getElementsByClassName, but when I pressed the button, the visible forms disappeared and the hidden ones appeared. I then tried to use getElementById, and called the function with the comment id. The result was that, whatever button I pressed, only the last comment's form appeared and disappeared, the others remaining unchanged. The variable only keeps the last element's id. When using this code, I inspected the result and the ids are the right ones. I would like to see only the form for which the button is pressed. This is my code: function myFunction() { var x = document.getElementById({{ comment.id }}); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } {% for comment in comments %} <button class="btn btn-warning" onclick="myFunction({{ comment.id }})">Reply</button> <div id="{{ comment.id }}"> <form method="post"> {{ comment_form.as_p }} {% csrf_token … -
Django auto redirect to home page if model matching query does not exist
I have a site with payment function and redirected to success html when payment succeed, so I want to redirect homepage if user click browser's 'go back' button from success html as it will show: order matching query does not exist. Any way to make this happen? Views.py for payment: def payment_process(request): stripe.api_key = settings.STRIPE_SECRET_KEY token = request.POST.get('stripeToken') order = Order.objects.get(user=request.user, ordered=False) context ={ 'order':order } amount = int(order.get_total() * 100) if request.method == 'POST': try: charge = stripe.Charge.create( amount=amount, currency="usd", source=token, ) # create the Payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order_items = order.items.all() product_items = order_items.item.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.save() messages.success(request, "Sucess") return redirect('payment_success') except ObjectDoesNotExist: messages.warning(request, 'Fialed') return redirect('/') else: return render(request, 'payment.html', context)