Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create in Django objects linked list followed each to other
I'm trying to build in Django a kind of linked list of objects that will create objects by the user request. The main purpose is to build some kind of flowchart ob objects that will run some action. How to write the architecture by Django model/s? Thanks in advance. Daniel. -
Django logs not going to the expected log files
I have this LOGGING settings for my Django app. What I was expecting is that the views logs would go into their own separate folder when I have three different loggers in my views file. Logger in my view file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'views_error_file': { 'class': 'logging.FileHandler', 'filename': 'logs/errors/views.debug.log', }, 'views_info_file': { 'class': 'logging.FileHandler', 'filename': 'logs/infos/views.debug.log', }, 'views_debug_file': { 'class': 'logging.FileHandler', 'filename': 'logs/debugs/views.debug.log', } }, 'loggers': { 'py_folder.views': { 'handlers': ['views_error_file'], 'level': 'ERROR', }, 'py_folder.views': { 'handlers': ['views_info_file'], 'level': 'INFO', }, 'py_folder.views': { 'handlers': ['views_debug_file'], 'level': 'DEBUG', } } } The views.py file: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def sample_function(request): params_choices = ['param_1', 'param_2'] sample_param = request.POST.get('sample_param') # logger.debug should be logged at logs/debugs/views.debug.log logger.debug(sample_param) if sample_param in params_choices: if sample_param == 'param_1': # logger.info should be logged at logs/infos/views.debug.log logger.info("param_1 okay") return redirect("/param_1-req") else: # logger.error should be logged at logs/error/views.debug.log logger.error("param_2 okay") return redirect("/param_2-req") else: logger.error("param does not exist") return redirect("/param-invalid") But its only going in to the logs/debugs/views.debug.log. The logs/debugs/views.debug.log file: param_3 param does not exist I tried changing the logs/infos/views.debug.log to logs/infos/views.info.log and logs/error/views.error.log to logs/error/views.error.log but nothing changed. I don't know why … -
Check who is logged in Django admin panel
how to check whether the user is logged in or not from admin panel what are the changes i need to make in models.py and admin.py to achieve this from django.contrib.auth.models import User -
How to retrieve data from a model "function" with model.objects.values()?
this is my model class ArtWork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.CharField(max_length=40) desc = models.TextField(max_length=100) image = models.ImageField(upload_to=get_post_filename, null=True, blank=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) album = models.OneToOneField('PostImages', related_name='model', blank=True, null=True, on_delete=models.PROTECT) # identifier private_unique_id = models.CharField(max_length=200, blank=True, unique=True, default=uuid.uuid4) public_unique_id = models.CharField(max_length=200, blank=True, unique=True, default=uuid.uuid4) def __str__(self): return self.title def get_ratings(self): like = Vote.objects.filter(artwork=self, like=True, nope=False).count() nope = Vote.objects.filter(artwork=self, nope=True, like=False).count() return like, nope I'd like to get the ArtWork model function "get_ratings" in views with "values" filter posts = ArtWork.objects.filter(active=True).values('image', 'title', 'desc',) any help is appreciated, thanks in advance. -
How to allow users to select groups when register in django rest framework?
I am trying to create a custom registration in my rest framework API, in which users can make a POST request with the following data ['email', 'username', 'password', 'password2', 'groups'] ** my problem** : when I make a post request like this one in the photo I got an error {"groups":["Incorrect type. Expected pk value, received str."]} my goal : I need the user to be able to select the name of the group in the group field my files : # serializers.py class RegisterSerializer(serializers.ModelSerializer): password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'password2', 'groups'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError( {'password': 'Passwords must match.'}) user.set_password(password) user.save() return user # views.py @api_view(['POST', ]) def Registration_view(request): if request.method == 'POST': serializer = RegisterSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['email'] = account.email data['username'] = account.username data['groups'] = account.groups else: data = serializer.errors # new_user = User.objects.all().get(username=data['username']) return Response(data) # return JsonResponse(serlize("json",modles.User.objects.get(username=data['username']))) -
what is the best way for updating (git pull) django app on ubuntu server with gunicorn and nginx?
last time when i git pull from github remote to ubuntu server(digital ocean) , server is down and gunicorn not working what is the safe way for update and git pull safely ? -
How can we set a model is as default=0 or defoult=null in django
Two month back I had created two models and it was working well, and now these models have lot of query which is filled by users. It is clear that both models are independent to each other. My previous models.py class State(models.Model): state_name = models.CharField(max_length=300, blank=False) state_code = models.CharField(max_length=100, blank=False,unique=True) @classmethod def get_all_states(self): return State.objects.all() def __str__(self): return self.state_name class College(models.Model): college_name = models.CharField(max_length=300, blank=False) college_code = models.CharField(max_length=100, blank=False,unique=True) university_name = models.CharField(max_length=300, blank=True) def __str__(self): return self.college_name Today I want to design College model according to state wise. If users have selected some state than related college list will come. For this condition I have created below models.py class State(models.Model): state_name = models.CharField(max_length=300, blank=False) state_code = models.CharField(max_length=100, blank=False,unique=True) @classmethod def get_all_states(self): return State.objects.all() def __str__(self): return self.state_name class College(models.Model): college_name = models.CharField(max_length=300, blank=False) college_code = models.CharField(max_length=100, blank=False,unique=True) university_name = models.CharField(max_length=300, blank=True) state_id = models.ForeignKey(State, on_delete=models.CASCADE) @classmethod def get_all_colleges(self): return self.College.objects.all() def __str__(self): return self.college_name In code you can see state_id (in College models) is a foreign key. When I did migration then It's showing the error You are trying to add a non-nullable field 'state_id' without a default; we can't do that (the database needs something to populate existing rows). … -
Serialize Nested Django models with Many to Many fields
I am trying to serialize a nested django model which is structured as below: class Ingredients(models.Model): ingredient=models.CharField(max_length=264) def __str__(self): return self.ingredient class Step(models.Model): Steps=models.CharField(max_length=264) Ingredient=models.ManyToManyField(Ingredients) def __str__(self): return self.Steps class Recipe(models.Model): user=models.ForeignKey(Users,on_delete=models.CASCADE) recipie_name=models.CharField(max_length=2640) Steps=models.ManyToManyField(Step) def __str__(self): return self.recipie_name I have a main Recipe model which consists of a "number of Steps" and the Steps have "different ingredients" to them. All linked using Many to Many field relation. So far, I have been able to serialize using the below code class IngredientSerializer(serializers.ModelSerializer): class Meta: model=Ingredients fields='__all__' class StepSerializer(serializers.ModelSerializer): ingredient=IngredientSerializer(many=True,read_only=True) class Meta: model=Step fields='__all__' class recipe_serialized(serializers.ModelSerializer): Step=StepSerializer(many=True,read_only=True) Steps = serializers.StringRelatedField(many=True) depth = 2 class Meta: model = Recipe fields = '__all__' Which gives me an output like: { "id": 1, "Steps": [ "Add two bananas together", "Then mix them with apples" ], "recipie_name": "strudel", "user": 1 }, My problem is, I am having a hard time trying to "expand" the Steps as well. As the Steps have ingredients linked to them using a Many to Many relations. So the ideal serializer will have the Step portion further broken down too. Would appreciate any guidance in this regard Thank you -
I have a problem with Django Admin. The screen is splitted
It maybe a very silly question but my Admin site splits the screen for the detail instead of opening a new page and it becomes very hard to interact with it. In this example, I select the Sequences option and the records are shown below on the bottom half of the screen. Any help would be appreciated. -
Unable to login in website when user is created django
I am not able to login in website i created from django.contrib import messages from django.shortcuts import HttpResponse, render, redirect from home.models import Contact from blog.models import Post from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'home/home.html') def about(request): return render(request, 'home/about.html') def contact(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] description = request.POST['description'] if len(name)<3 or len(email)<5 or len(phone)<10 or len(description)<2: messages.error(request, 'Please fill the form correctly!') else: contact = Contact(name=name, email=email, phone=phone, description=description) contact.save() messages.success(request, 'Your message has been succesfully sent!') return render(request, 'home/home.html') return render(request, 'home/contact.html') def search(request): query = request.GET['query'] if len(query)>50: allposts = Post.objects.none() else: allposts_title = Post.objects.filter(title__icontains=query) allposts_content = Post.objects.filter(content__icontains=query) allposts = allposts_title.union(allposts_content) if allposts.count() == 0: messages.warning(request, 'No search results found!') params = {'allposts':allposts, 'query':query} return render(request, 'home/search.html', params) @csrf_exempt def signup(request): if request.method == 'POST': username = request.POST.get('username') fname = request.POST.get('firstname') lname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') # validation if len(username) < 2: messages.error(request, 'Username must be more than 2 characters') return redirect('home') if len(username) >15: messages.error(request, 'Username must be under 15 characters') return redirect('home') if … -
(actual errors: ['Select a valid choice. That choice is not one of the available choices.']) when trying to test a form
I am trying to test that a form will redirect when it is successfully posted, but I am getting this error: (actual errors: ['Select a valid choice. That choice is not one of the available choices.']) Model.py class BookInstance(models.Model): """Model representing a specific copy of a book (i.e that can be borrowed from the library).""" id = models.UUIDField( primary_key = True, default = uuid.uuid4, help_text = 'Unique ID for this particular book across whole library' ) book = models.ForeignKey('Book', on_delete = models.RESTRICT, null = False, blank = False) imprint = models.CharField(max_length=200) due_back = models.DateField(null = True, blank = True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank='True', default='m', help_text = 'Book availability' ) borrower = models.ForeignKey( User, on_delete = models.SET_NULL, null = True, blank = True) @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False class Meta: """order queries according to due back dates""" ordering = ['due_back'] permissions = ( ("can_mark_returned", "set book as returned"), ) def __str__(self): """String for representing the Model object.""" """ representes it as 'id.title-status'""" return f"{self.id}({self.book.title})-{self.status}" view.py def renew_book_librarian(request, pk): book_instance = get_object_or_404(BookInstance, pk = pk) if request.method == 'POST': … -
Angular or React Frontend with Django Backend
I would like to switch to a custom frontend for my Django project instead of the classic Django template engine. The question is whether I should use the Angular Framework or React. I want to connect frontend and backend via Django REST API. -
Django admin permission, admin can login to account another user (button in admin panel)
i have a question, how to create/add permission for admin to login account another user? In django admin panel i should have a button by user to login to his account. -
Django channels creating two instances instead of one
I am using Django channels for real-time app purposes, more specifically to make real-time comments. And then I will explain my situation ... When someone sends a comment, they are supposed to create one and only one object in the database. The problem here is that when two or more users are connected to the same layer, the database creates two objects instead of just one. I have already reviewed and revised my code and I cannot find where I messed up. I hope I was able to explain my problem well so that you can help me! Here is my database model: class Comentarios(models.Model): sender = models.ForeignKey(User, on_delete = models.CASCADE, null = False, blank = False) tarefa = models.ManyToManyField(Tarefa) content = models.TextField(max_length = 255, null = False, blank = False) time_created = models.TimeField(auto_now_add = True) And here is my consumers.py: from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async from app.models import Comentarios, Tarefa from django.contrib.auth.models import User from django.core import serializers class WSConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['id'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope['url_route']['kwargs']['user_id'] print("Connected!") print(self.scope['user'].__dict__) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() @database_sync_to_async def db_comentario(self, message): user_sender = User.objects.get(id = self.user) tarefa = … -
DRF Invalid DateTimeField value
I want to set DateTimeField value via POST request in Django Rest Framework by receive current time instead of mine in "active_date_from" and "active_date_to" fields I sent POST request with body { "title": "myTitle", "tag": 7, "created_at": "2021-05-09 17:32:18", "active_date_from": "2020-01-01 00:00:11", "active_date_to": "2020-01-01 11:11:11" } But receive { "result": { "id": 32, "title": "myTitle", "image": null, "description": "", "tag": 7, "tag_name": "124", "created_at": "2021-05-09 17:55:45", "active_date_from": "2021-05-09 17:55:45", "active_date_to": "2021-05-09 17:55:45" }, } My code. In Model I am setting default value auto_now_add=True, but I expect that I can set these fields in the post method models.py class News(models.Model): title = models.CharField(max_length=255) image = models.ImageField( upload_to=image_directory_path, blank=True, null=True ) short_description = models.CharField(max_length=255) description = models.TextField() tag = models.ForeignKey( NewsTag, related_name="product_tag", on_delete=models.SET_NULL, null=True, ) created_at = models.DateTimeField(auto_now_add=True) active_date_from = models.DateTimeField(auto_now_add=True) active_date_to = models.DateTimeField(auto_now_add=True) serializers.py class DashboardNewsSerializer(serializers.ModelSerializer): title = serializers.CharField(required=False) image = serializers.ImageField(required=False) description = serializers.CharField(required=False) created_at = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) active_date_from = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) active_date_to = serializers.DateTimeField(format=settings.DATETIME_FORMAT[0]) tag = PrimaryKeyRelatedField(queryset=NewsTag.objects.all(), many=False) tag_name = serializers.SerializerMethodField() class Meta: model = News fields = ( "id", "title", "image", "description", "tag", "tag_name", "created_at", "active_date_from", "active_date_to", ) views.py class DashboardNewsViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticatedManager,) serializer_class = DashboardNewsSerializer queryset = News.objects.all() search_fields = ("title",) filter_backends = [ drf_filters.SearchFilter, drf_filters.OrderingFilter, ] … -
Jquery returns an error where it cannot find the property of an objects (Django)
When I changed the import method I got an error on a live search. This is the JQUERY code I'm using. The error I'm gettin is the blogpost['title'] is empty. I've read that it might be due to the name blogpost being the overall container, so it's not actually a single blogpost but all the blogpost, but I don't know how to fix this. I think the most helpful would be someone taking a look at the rdata and the json error. Thanks! <script> var data = '{{qs_json}}' data = data.replace(/&quot;/g, '"'); data = data.replace(/(?:\r\n|\r|\n)/g, ''); console.log(data) rdata = JSON.parse(data) console.log(rdata) const input = document.getElementById('search_form') let filteredArr = [] input.addEventListener('keyup', (e) => { jsbox.innerHTML = "" filteredArr = rdata.filter(blogpost => blogpost['title'].toLowerCase().includes(e.target.value.toLowerCase())) if (filteredArr.length > 0) { filteredArr.map(blogpost => { jsbox.innerHTML += ` <div class="col mt-5 ml-1"> <a href="blog/${blogpost.slug}" style="text-decoration: none"> <div class= "card"> <div class='blogpost_image_container'> <img src="${blogpost.image}" class="card-img-top" alt="blogpost image"> </div> <div class="card-body"> <h5 class="card-title">${blogpost.title} </h5> <p class="card-text"> ${blogpost.subtitle} </p> <span id="category_badge" class="badge rounded-pill bg-warning text-dark"> ${blogpost.category} </div> </div> </div > </a> ` }) } else { jsbox.innerHTML = `<div class= "col mt-5 ml-1"> <h5 class="card-title"> No Matches Found! </h5></div >` } }) </script> However the console logged Rdata shows … -
load audios from django server
Here is my problem: I stored my audio files on my django server, and can successfully retrieve them on my vue application. However I only retrieve the 'url' ("/files/audios/2021/05/09/audio22.wav") of the audios and I do not know how to play them in my vue application. I tried integrating them as the source in an audio tag but it did not work. Here is my audiosView.py : class AudiosView(APIView): def get(self, request): all_audios = Audio.objects.all().order_by("timestamp") ser = AudioSerializer(all_audios, many = True) return JsonResponse(ser.data, safe = False) def post(self, request): ser = AudioSerializer(data = request.data) if ser.is_valid(): ser.save() return JsonResponse(ser.data) return JsonResponse(ser.errors, status = status.HTTP_400_BAD_REQUEST) Here is my serializers.py: class AudioSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Audio fields = ("user", "rooms","audiofile","timestamp") Urls.py: urlpatterns = [ path("audios/", AudiosView.as_view()), path("audios/<slug:pk>", AudioView.as_view()),] models.py class Audio(models.Model): id = models.SlugField(max_length = 6, primary_key = True, unique = True) user = models.TextField( blank = True ,help_text="user who sent the audio") rooms = models.TextField( blank = True ,help_text="room where the audio was sent") audiofile = models.FileField(upload_to="audios/%Y/%m/%d") timestamp = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return f"{self.id} ({self.user})" -
'QueryDict' object is not callable django pytjon
home.html {% extends 'base.html'%} {%block content%} <h1>hello word{{name}}</h1> <form action="add" method="POST"> <label>fname</label><input type="text" name="fn"> <label>lname</label><input type="text"name="ln"> <input type="submit" > </form> {%endblock%} views.py def index(request): return render(request,'home.html',{'name':'dhiraj'}) def add (request): val1=int(request.POST("fn")) val2=int(request.POST("ln")) res=val1+val2 return render(request,'result.html',{'result':res}) getting error is PS C:\Users\Dhiraj Subedi\fpro\fproject> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 09, 2021 - 20:18:42 Django version 3.2.2, using settings 'fproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /add Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dhiraj Subedi\fpro\ero\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dhiraj Subedi\fpro\fproject\fapp\views.py", line 11, in add val1=int(request.POST("fn")) TypeError: 'QueryDict' object is not callable [09/May/2021 20:19:00] "GET /add?fn=5&ln=4 HTTP/1.1" 500 65820 Due to the above mentioned error, my form is not getting displayed. Please help me in identifying and resolving the issue. i am relly trouble on this issue please help me I am really trouble on this issue thank … -
How to fix error context={'request':request} in serializers.HyperlinkedModelSerializer (DRF - Django)
When I'm using serializers.ModelSerializer, I see all Book records without problem in web interface. But I want to have serializers.HyperlinkedModelSerializer feature. Where is the problem !?. How to fix error below !?. When I changed the serializer class to HyperlinkedModelSerializer, I saw error below: AssertionError at /books/rest/ `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. Request Method: GET Request URL: http://127.0.0.1:8000/books/rest/ Django Version: 3.1.7 Exception Type: AssertionError Exception Value: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer. books/serial.py: from .models import Book from rest_framework import serializers from rest_framework.request import Request class BookSerializer (serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField (view_name="book_update") class Meta: model = Book #fields = '__all__' fields = ['url', 'id', 'title', 'category', 'author'] #lookup_field = "id" books/models.py: from django.db import models class Book (models.Model): title = models.CharField (max_length=250, null=False) category = models.CharField (max_length=50, null=True) publisher = models.CharField (max_length=100, null=True) published_at = models.DateField (auto_now=True, null=True) author = models.CharField (max_length=100, null=False) isbn = models.CharField (max_length=15, null=True) def __str__ (self): return self.title books/urls.py: from django.urls import path, re_path from . import views urlpatterns = [ path ('rest/list/', views.book_list_create.as_view(), name='book_list'), path ('rest/update/<int:id>/', views.book_update_create_fetch.as_view(), name='book_update'), ] books/views.py: from django.views.generic import ListView from … -
call a python script from the django admin panel through a Linux
Is it possible to call a python script from the django admin panel through a Linux script with an interval of 2 minutes without using celery and redis? If you have the opportunity, show an example of this script, or just tell me is it possible? -
eb deploy not able to resolve django application dependencies in requirements.txt
Here is the summary and order of events that happen when I deploy my code on AWS using eb deploy. The ec2 instance is unable to resolve the dependencies for the package "flake-logging-format 0.6.0" and the deployment fails with the error log shown below. I deploy after removing the dependency "flake-logging-format 0.6.0" from requirements.txt and it gets deployed successfully and the server starts running. I deploy again after re-adding the dependency "flake-logging-format 0.6.0" and this time it also gets deployed successfully and the server starts running. My question is: Why does the deployment fail in the first step, and why does it work after executing steps 2 and step 3, overall there is no difference in requirements.txt at step 1 and step 3. Here is the error log that I get after step 1: Collecting flake8-logging-format==0.6.0 Using cached flake8-logging-format-0.6.0.tar.gz (5.1 kB) ERROR: Command errored out with exit status 1: command: /opt/python/run/venv/bin/python3.6 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2g6pboop/flake8-logging-format/setup.py'"'"'; file='"'"'/tmp/pip-install-2g6pboop/flake8-logging-format/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-2g6pboop/flake8-logging-format/pip-egg-info cwd: /tmp/pip-install-2g6pboop/flake8-logging-format/ Complete output (23 lines): Couldn't find index page for 'nose' (maybe misspelled?) No local packages or working download links found for nose>=1.3.7 Traceback (most recent call last): File "", line … -
The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead
i have this code for verify payment , when user buy some course he will redirect to other page called mycourse but when i try to buy course it show error The view courses.views.checkout.verifypayment didn't return an HttpResponse object. It returned None instead. View.py : @csrf_exempt def verifypayment(request): if request.method == 'POST': data = request.POST context = {} try: client.utility.verify_payment_signature(data) razorpay_order_id = data['razorpay_order_id'] razorpay_payment_id = data['razorpay_payment_id'] payment = Payment.objects.get(order_id = razorpay_order_id) payment.payment_id = razorpay_payment_id payment.status = True userCourse = UserCourse(user = payment.user , course = payment.course) userCourse.save() payment.user_course = userCourse payment.save() return redirect('mycourse') except: return HttpResponse("Invalid Payment Details") -
How can i combine sub_category in same list only if parent title is same?
Any idea to check that list is already created or not? Or any filter method that i can get mentioned response? i am getting this type of response. [ { "Politics": [ "Government" ] }, { "Politics": [ "Court" ] }, { "State News": [ "State 1" ] }, { "State News": [ "State 2" ] } ] here is my views.py class getCategoriesAPIView(APIView): def get(self, request): queryset = SubCategory.objects.filter() toList = [] for items in queryset: toDict = {} toDict1 = {} toDict[items.category.title] = [] toDict1['sub_category'] = items.sub_title toDict[items.category.title].append(toDict1['sub_category']) toList.append(toDict) return JsonResponse(toList, safe=False) I need response like this: [ { "Politics": [ "Government", "Court" ] } { "State News": [ "State 1" "State 2" ] } ] -
Form not being saved in Database Django
I have created a form for a Post. The form loads and when I enter all the value and try to submit the form, it gets refreshed but the database is not updated. Here is my Post Model: class Post(models.Model): no_people = models.IntegerField() no_days = models.IntegerField() tour_date = models.CharField(max_length=200, blank=True) Gender_types = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Others'), ) Gender_prefer = models.CharField(max_length=1, choices=Gender_types) location = models.CharField(max_length=200, blank=True) pic_location = models.ImageField(blank=True, upload_to="posts/") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) detail = models.TextField() liked = models.ManyToManyField(Yatru, blank=True, related_name= 'likes') author = models.ForeignKey(Yatru, on_delete=models.CASCADE, related_name = 'posts',null=True) def __str__(self): return str(self.location) def no_likes(self): return self.liked.all().count() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): self.location = self.location.upper() return super(Post, self).save(*args, **kwargs) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) Here is the form: from django import forms from .models import Post class PostModelForm(forms.ModelForm): class Meta: model = Post fields = ('no_people','no_days','tour_date', 'Gender_prefer','location','detail') Here is the views: def post_add(request): user = request.user profile = Yatru.objects.get(user=user) form = PostModelForm(request.POST or None, request.FILES or None, instance=profile) if request.method == 'POST': if form.is_valid(): newpost=form.save(commit=False) newpost.user=request.user newpost.save() return render(request, 'posts/my_post.html',{'form': form}) This is the HTML file: <form method="POST"> {% csrf_token %} {{form.as_p}} <button type='submit'>Submit </button> </form> -
Запуск Django приложения на Heroku
Не получается выложить Django приложение на Heroku. Пользовался этими инструкциями https://python-scripts.com/django-simple-site-heroku но приложение не отображается. Кто может скать что в них не так?