Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you initialize hardware when a Django server starts up?
I am working on a project where a raspberry pi receives some data from a radio module and then sends it to a localhost django server to present it on a web interface. Right now, I do this by generating a JSON object with the data and sending a POST request to the server, but I found out that the response time is very slow and it often misses packets because of this. Since everything is written in python, I figure it should be possible to just embed the reception script into the django project and just have the on_receive() function write directly to the database, but I have no idea where in my django project could I write the initialization script so it sets up the GPIO and SPI and the reception function and executes it on launch. Also, as icing on the cake, if it were possible to run a script on closing the server to free up the hardware resources it would be great. -
Getting Localtime using timezone.now()
I m performing a quary where I want to get list of item added today. listOfMatches=Matches.objects.filter(match_starting_time__date=timezone.localdate(timezone.now())) Also tried this listOfMatches=Matches.objects.filter(match_starting_time__date=timezone.now()) All i m getting is Utc time print(timezone.now()) I need Local time. I have set Time_zone to TIME_ZONE = 'Pacific/Fiji' -
What should be the mentioned in the host in django if I'm running redis in a docker container?
'host': 'localhost', 'port': 6379, This is a part of the redis configuration that I am using. I have created a DockerFile for my app. I want to eventually test it with running a separate redis docker container without using docker-compose. What should I mention in the 'host' part of the configuration? Is it enough if I mention the following in Django settings.py? 'host': <Name_of_redis_container>, 'port': 6379, -
I am getting a no attribute error in my django rest api
models.py from django.db import models # Create your models here. class Question(models.Model): title = models.CharField(max_length=120) date_created = models.DateTimeField(auto_now_add=True) content = models.TextField() # answers = models.ForeignKey(Answer, on_delete=models.CASCADE) def __str__(self): return self.title class Answer(models.Model): question = models.ForeignKey(Question, related_name="comment_post", on_delete=models.CASCADE) answer = models.CharField(max_length=750) date_answered = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question.title serializers.py from rest_framework import serializers from . import models class AnswerSerializer(serializers.ModelSerializer): class Meta: model = models.Answer fields = ('id', 'question', 'answer', ) class QuestionSerializer(serializers.ModelSerializer): post_comment = AnswerSerializer(many=True) class Meta: model = models.Question fields = ('id', 'title', 'post_comment', 'content', ) depth = 1 I wanna view questions with all the answers they got but get the error : AttributeError at /v1/question/ Got AttributeError when attempting to get a value for field post_comment on serializer QuestionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Question instance. Original exception text was: 'Question' object has no attribute 'post_comment'. -
Problem pagination for category posts in Django
I used the following code for pagination and got the error I left here. please help. Note that for categories whose number of posts is less than 2 (_paginator), there is no problem, but the same posts are more than two and pagination is done. urls.py: from django.urls import path from . views import home, detail_article, category_list app_name = "blog" urlpatterns = [ path('', home, name="home"), path('page/<int:page>', home, name="home"), path('post/<slug:slug>', detail_article, name="detail_article"), path('category/<slug:slug>', category_list, name="category_list"), path('category/<slug:slug>/page/<int:page>', category_list, name="category_list") ] views.py: def category_list(request, slug, page=1): category = get_object_or_404(Category, slug=slug, status=True) article_list = category.articles.published() _paginator = Paginator(article_list, 2) articles = _paginator.get_page(page) context = { 'category':category, 'articles':articles } return render(request, 'blog/category.html', context) template.html: <!-- Paginator --> {% if articles.has_other_pages %} <div class="col-12 pagging"> <ul> {% if articles.has_previous %} <li> <a href="{% url 'blog:category_list' category.slug articles.previous_page_number %}"> <i class="fa fa-arrow-right" aria-hidden="true"></i></a> </li> {% else %} <li><i class="fa fa-arrow-right a-active" aria-hidden="true"></i></li> {% endif %} <!-- {% for i in articles.paginator.page_range %} {% if articles.number == i %} <li><span class="a-active">{{ i }}</span></li> {% else %} <li><a href="{% url 'blog:category' %} page/{{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} --> {% if articles.has_next %} <li> <a href="{% url 'blog:category_list' category.slug articles.next_page_number %}"> <i class="fa … -
How i could take id articles from Ajax for django
i take id product and try to go view django, and always took error how i could take data in view? help pls i don't understand what data i get from request and how can i look inside $(function () { $(".js-take-id").click(function () { alert("вы нажали на кнопку скрипта Poka! с номером товара id="+ $(this).data("id")); const csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); $.ajax({ url: '/articles/', type: 'post', dataType: 'json', data: { 'id': $(this).data("id"), } }); }); }); class MainArticles(ListView): template_name = 'dishes/articles.html' model = Articles def post(self, request): name = request.POST.get('/articles/') #data = json.loads(request.POST.get('data')) data = json.dumps(request.POST.get('/articles/')) return HttpResponse('HelloWorld') -
Django rest Framework problem otp expires without checking please help anyone
def validate_token_age(mobile_otp): """ Returns True if a given token is within the age expiration limit. """ try: token = MobileOTP.objects.get(otp=mobile_otp, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = PASSWORDLESS_TOKEN_EXPIRE_TIME print("token_expiry_time" ,token_expiry_time) if seconds > token_expiry_time: return True else: # Invalidate our token. token.is_active = False token.forced_expired = True token.save() return False except MobileOTP.DoesNotExist: # No valid token. return False class UserConfirmAPIView(APIView): def post(self,request,*args,**kwargs): otp_code = request.data['otp_code'] phone_number = request.data["phone_number"] #first make sure that the user is registered try: user = User.objects.get( phone_number=phone_number ) #if the user exists make sure the verification_code is valid too and also active try: the_code = MobileOTP.objects.get(otp=otp_code ,is_active=True) #make sure the one using the code is the owner if the_code.user != user: logger.warning("drfpasswordless: User passed a code that does not belong to them.") verify_sms_response = { "status":"error", "token":None, "message":"Please try again ,Wrong Velification." } return Response(verify_sms_response ,status=status.HTTP_400_BAD_REQUEST) #make sure the code is not expired is_valid = validate_token_age(the_code) if is_valid: #mark the code as used the_code.is_active = False the_code.is_used = True the_code.date_used = timezone.now() the_code.save() #get the user auth token try: token = Token.objects.get(user_id=user.id) verify_sms_response = { "status":"success", "token":token.key, "message":"Success user Authentication", "phone_number":user.phone_number, # "email":user.email, # "first_name":user.first_name, # "last_name":user.last_name, } return Response(verify_sms_response , status=status.HTTP_202_ACCEPTED) except Token.DoesNotExist: logger.debug(" … -
AttributeError: 'NoneType' object has no attribute 'get'(MongoDB and Django)
We use MongoDB and Django in our project, some columns have some_col element, and some columns don't have some_col element, maybe that's why we will get the error of AttributeError: 'NoneType' object has no attribute 'get', is there any solution to solve this errors? def get_col(self, name, **kwargs): where = {'name': name} if 'where' in kwargs and isinstance(kwargs['where'], dict): where.update(kwargs['where']) find_data = self.find_one(where) return find_data def get_test_col(self): colmuns = Test(self.name) cls = colmuns.get_col('some_col') if not cls: self.some_col = {} self.some_col = cls.get('data', {}) # error line -
can my seperate index.html file and my django app run on the same server? same domain?
I am new to deploying and hosting website and applications. so i have my index.html file and some others( which have Ajax communications with my app) quite outside my Django App directory. now i am wondering whether i can deploy and run them on the same server, same as they are structured on my local server(but each running on different local server ports). and whether they work well on single domain? this question came to my mind when i tried to render a server-side page where after the submission of that page, a JsonResponse should be sent back to the client-side. but whereas they run on different local server ports, all i get is the JSON data. and my index page fails to retrieve JSON data. -
Export css file to Django template language
I was working on a Django project on my PC and i have a Bootstrap template for my site , is there any simple way to convert my CSS files to Django Template Language. is there a tool that convert it to Django Static files?! -
Django-rest-framework performance issues
Hi all this is my view class class ModuleViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = models.Module.objects.all() permission_classes = [ModuleViewPermission] serializer_class = serializers.ModuleSerializer I have turned the django.db logger to INFO level to see the actual database queries being executed. Following are my findings: Get list of modules: 2020-07-26 19:22:18,062 DEBUG utils:110 e70f16f5c7494c8783ca9f5a6bea22c4 (0.013) SELECT "courses_module"."id", "courses_module"."course_id", "courses_module"."name", "courses_module"."number" FROM "courses_module"; args=() django.db.backends 2020-07-26 19:22:18,090 INFO basehttp:154 e70f16f5c7494c8783ca9f5a6bea22c4 "GET /api/courses/modules/ HTTP/1.1" 200 99 django.server Get single object: 2020-07-26 19:23:26,143 DEBUG utils:110 f1332e4a5e2247709dc784dc2f8b6d19 (0.005) SELECT "courses_module"."id", "courses_module"."course_id", "courses_module"."name", "courses_module"."number" FROM "courses_module"; args=() django.db.backends 2020-07-26 19:23:27,331 DEBUG utils:110 f1332e4a5e2247709dc784dc2f8b6d19 (0.003) SELECT "courses_module"."id", "courses_module"."course_id", "courses_module"."name", "courses_module"."number" FROM "courses_module" WHERE "courses_module"."id" = 1; args=(1,) django.db.backends 2020-07-26 19:23:27,342 DEBUG utils:110 f1332e4a5e2247709dc784dc2f8b6d19 (0.006) SELECT "courses_course"."id", "courses_course"."name", "courses_course"."description", "courses_course"."price_group_id" FROM "courses_course" WHERE "courses_course"."id" = 1; args=(1,) django.db.backends 2020-07-26 19:23:27,359 DEBUG utils:110 f1332e4a5e2247709dc784dc2f8b6d19 (0.015) SELECT "user_user"."id", "user_user"."password", "user_user"."last_login", "user_user"."is_superuser", "user_user"."username", "user_user"."is_staff", "user_user"."is_active", "user_user"."date_joined", "user_user"."email", "user_user"."first_name", "user_user"."last_name" FROM "user_user" INNER JOIN "courses_course_authors" ON ("user_user"."id" = "courses_course_authors"."user_id") WHERE "courses_course_authors"."course_id" = 1; args=(1,) django.db.backends 2020-07-26 19:23:27,375 INFO basehttp:154 f1332e4a5e2247709dc784dc2f8b6d19 "GET /api/courses/modules/1/ HTTP/1.1" 200 45 django.server For 1 it may be correct to select all but according to documentation queryset is cached for the upcoming requests. But in get_queryset() method we can see … -
I am getting an attribute error while trying to build a user registration form using Django
So I have been trying to create an authentication form using Django but I am getting an attribute error which I'm not able to resolve. The code is given below. models.py file: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) # additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username forms.py file: from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site', 'profile_pic') app urls.py file: from django.contrib import admin from django.conf.urls import url from django.urls import path, include from . import views app_name = 'basic_app' urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), ] views.py file: from django.shortcuts import render from basic_app.forms import UserForm, UserProfileInfoForm from . import forms # Create your views here. def index(request): return render(request, 'basic_app/index.html') def reqister(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) #this one user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() … -
plese help in resolving reverse match error
I'm new in Django and i cannot understand why this error is popping up: django.urls.exceptions.NoReverseMatch: Reverse for 'updater' with no arguments not found. 1 pattern(s) tried: ['update/(?P[0-9]+)$'] [26/Jul/2020 19:05:05] "GET /update/2 HTTP/1.1" 500 127513 my urls: urlpatterns=[ path('update/<int:updating>',views.update,name='updater'), ] the html page <!DOCTYPE html> <html lang="en"> <head> {% load static %} <title>NEW PRODUCT</title> </head> <body> <div class="bg-contact2" style="background-image: url('images/bg-01.jpg');"> <div class="container-contact2"> <div class="wrap-contact2"> <form class="contact2-form validate-form" method="post" action="{%url 'updater' %}" enctype="multipart/form-data"> {% csrf_token %} <span class="contact2-form-title"> Provide Product details Below </span> <div class="wrap-input2 validate-input" data-validate="type is required"> <input class="input2" type="text" name="type" value="{{details.product_type}}"> <span class="focus-input2" data-placeholder="PRODUCT-TYPE"></span> </div> <div class="wrap-input2 validate-input" data-validate = "Name is required"> <input class="input2" type="text" name="name" value="{{details.product_name}}"> <span class="focus-input2" data-placeholder="PRODUCT NAME"></span> </div> <div class="wrap-input2 validate-input" data-validate = "description is required"> <textarea class="input2" name="description">{{details.product_description}}</textarea> <span class="focus-input2" data-placeholder="PRODUCT DESCRIPTION"></span> </div> <div class="wrap-input2 validate-input" data-validate = "Price is required"> <input class="input2" type="number" name="price" value="{{details.product_price}}"> <span class="focus-input2" data-placeholder="PRICE"></span> </div> <div class="wrap-input2 validate-input" data-validate = "Picture is required"> <label >product sample picture</label> <input class="input2" type="file" name="picture"> <span class="focus-input2" data-placeholder=""></span> </div> <div class="container-contact2-form-btn"> <div class="wrap-contact2-form-btn"> <div class="contact2-form-bgbtn"></div> <button class="contact2-form-btn"> Update Product Listing </button> </div> </div> </form> </div> </div> </div> </body> </html> my views: def update (request,updating) : if request.method=='POST' : product_details=product_info.objects.get(id=updating) product_details.product_type=request.POST.get('type') product_details.product_name=request.POST.get('name') product_details.product_description=request.POST.get('description') … -
Docker- Containers Multiple copies of a deployed app in multiple containers, saleor
i have deployed saleor by cloning it from < https://github.com/AirnFire/saleor-platform >. i want to create multiple images of this app and deploy them on different containers, can anybody guide me how to do that. -
How i can use images in models
Django can't find the path to the image settings.py import os, sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '!h869$36+^-is$a06!4==th9&npp6ksu*^uyp(36w!+a%w21#p' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) # Application definition INSTALLED_APPS = [ 'homepage.apps.HomepageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'testsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_ROOT, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'testsite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT … -
How to apply Kubernetes on a dockerized Saleor container
I want to build a mall. I have used saleor as the ecommerce solution. Now I want to replicate the same container and apply kubernetes on it but i'm fairly new to to dockers and kubernetes. I have successfully containerized the app https://github.com/mirumee/saleor. But how to apply kubernetes to it? Any lead will be appreciated. -
django: How to modify class variables
My question is rather simple, how can i modify a class variable i defined in the class itself Class Based View class Depth_Edit(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Single form_class = EditSingle # Default form class template_name = 'creator/ViewSingles/depth_edit.html' PartOfAlbum = 'override me' def get(self, request, *args, **kwargs): song_id = kwargs.get('song').split('-')[-1] track = Single.objects.get(id=song_id) # Check if the track is part of an album if track.PartOfAlbum: print('Part of album') # Part of album form = EditAlbumSingle(initial={ 'musicName': track.musicName, 'description': track.description, 'genre': track.genre, }) self.PartOfAlbum = True else: print('Not part of album') # Not part of album form = self.form_class(initial={ 'musicName': track.musicName, 'coverImageLink': track.coverImageLink, 'description': track.description, 'genre': track.genre, }) self.PartOfAlbum = False The problem is on self.PartOfAlbum = True and self.PartOfAlbum = False the variable is simply not changing. -
How can i pass data from one view to another?
I am trying to use login function,it is enough for standard web use but i have to create separate GET function for JSON to be able to get data. Standard login function class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = User.objects.get() response = { 'message': 'User logged in successfully', 'token' : serializer.data['token'], 'email' : 'user.email', } status_code = status.HTTP_200_OK return Response(response, status=status_code) def get(self, request, format=None): queryset = User.objects.all() serializer = UserLoginSerializer() return Response(serializer.data) The View Function that i want to pass data onto class UserHomeView(APIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer = UserHomeSerializer() def post(self, request): return User.objects.get(user=self.request.user) response = { 'email' : user.email, } status_code = status.HTTP_200_OK return Response(response, status=status_code) def get(self, request, format=None): queryset = User.objects.all() serializer = UserHomeSerializer() return Response(serializer.data) There is no data that i want to receive,just to give the user details (just the GET function),but i don't know how to do it. Can anyone help? -
model = Sell NameError: name 'Sell' is not defined
I am getting the error NameError: name 'Sell' is not defined But I have defined this Model in Models.py Plz, tell what is the error I have posted my relevant code. Thanks in advance. Models.py of buy app from django.db import models from django.contrib.auth.models import User # Create your models here. class Sell(models.Model): Cats =( ('Course book','Course book'), ('Fiction','Fiction'), ) Lang =( ('Hindi','Hindi'), ('English','English'), ('Tamil','Tamil') ) Cond = ( ('New','New'), ('Old','old') ) Title = models.CharField(max_length=400) Author = models.CharField(max_length=100) Price = models.DecimalField() Category = models.CharField(choices=Cats) Language = models.CharField(choices=Lang) Condition = models.CharField(choices=Cond) user = models.ForeignKey(User, on_delete=models.CASCADE) Views.py of buy app class sell(TemplateView): template_name = 'buy/sell.html' def get(self,request): form = sellForm() return render(request,self.template_name,{'form':form}) def post(self,request): text = None form = sellForm(request.POST) if form.is_valid(): print("all good") text = form.cleaned_data['Title'] form = sellForm() args = {'form':form,'text':text} return render(request,self.template_name,args) Forms.py of accounts app from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class EditProfileForm(UserChangeForm): class Meta: model = User fields =( 'first_name', 'last_name', 'email', 'password' ) class sellForm(forms.ModelForm): Cats =( ('Course book','Course book'), ('Fiction','Fiction'), ) Lang =( ('Hindi','Hindi'), ('English','English'), ('Tamil','Tamil') ) Cond = ( ('New','New'), ('Old','old') ) Title = forms.CharField() Author = forms.CharField() Price = forms.DecimalField() Category = forms.ChoiceField(required=False,choices=Cats) Language = forms.ChoiceField(choices=Lang) Condition … -
External API Request with Proxy within Django
I have a local proxy service up at 127.0.0.1:8080 I can make api calls with it but not within django, for some reason it works in regular python code (i.e. python test.py) but not in django. import requests proxies = { 'http': 'http://127.0.0.1:8080', 'https': 'https://127.0.0.1:8080', } response = requests.get('https://api.ipify.org?format=json', proxies=proxies) django v3.0.8 and requests v2.24.0 I have an assumption that WSGI somehow override's my proxy settings -
How to get the first field from TextField?
I am using the django-background-tasks package. I have a TextField which saves data like this for some purposes. [[61], {}] What I am trying to achieve is to get the only 61 in a int format. Task model (code pasted from here) @python_2_unicode_compatible class Task(models.Model): # the "name" of the task/function to be run task_name = models.CharField(max_length=190, db_index=True) # the json encoded parameters to pass to the task task_params = models.TextField() Is it possible or I have to think in another way ? -
Why do we use authenticate and not login directly in Django login system
Why do we use authenticate and not login directly, this is the code from my views.py: def loginpage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect(r'/') else: messages.info(request, "Username or Password is incorrect") return render(request, 'blogs/login.html') -
Django Channel installation error, required Microsoft Visual C++ 14.0
Before One month I ran the Django channels successfully in my environment,But now I can't install and asks to install MSV C++ 14. The MSV C++ 14. package seems to be more than 14 GB. Does Python packages depend on C++ ? Why does this error occur ? -
How can I in django rest framework select a foreign key from dropdown?
models.py from django.db import models # Create your models here. class Question(models.Model): title = models.CharField(max_length=120) date_created = models.DateTimeField(auto_now_add=True) content = models.TextField() # answers = models.ForeignKey(Answer, on_delete=models.CASCADE) class Answer(models.Model): content = models.CharField(max_length=750) date_answered = models.DateTimeField(auto_now_add=True) question = models.ForeignKey(Question, on_delete=models.CASCADE) serializers.py from rest_framework import serializers from . import models class AnswerSerializer(serializers.ModelSerializer): class Meta: model = models.Answer fields = ('id', 'question', 'content', ) depth = 1 class QuestionSerializer(serializers.ModelSerializer): class Meta: model = models.Question fields = ('id', 'title', 'content', ) depth = 1 views.py from django.shortcuts import render from rest_framework import viewsets from . import serializers from . import models # Create your views here. class QuestionViewset(viewsets.ModelViewSet): serializer_class = serializers.QuestionSerializer queryset = models.Question.objects.all() def perform_create(self, serializer): if serializer.is_valid(): serializer.save() class AnswerViewset(viewsets.ModelViewSet): serializer_class = serializers.AnswerSerializer queryset = models.Answer.objects.all() def perform_create(self, serializer): if serializer.is_valid(): serializer.save() I JUST WANNA KNOW HOW DO I MAKE MY REST API SO USER CAN SELECT A QUESTION POST TO ANSWER TOWARDS AND THEN THE QUESTION HAS ANSWERS SHOWING UNDERNEATH! SOMEONE HELP ME WITH THIS! I AM STUCK! thanks! -
Reverse for 'update_laptop' with arguments '('',)' not found. 1 pattern(s) tried: ['update_laptop/(?P<laptop_id>[^/]+)/$']
I am building Inventry system and wants to add update functionality. but unfortunately it is not working. Please help me in this code error. views.py: def update_laptop(request, laptop_id): # function for updation of laptops. update = Laptop.objects.get(pk=laptop_id) if request.method == 'POST': form = LaptopForm(request.POST, instance=update) if form.is_valid(): form.save() return redirect('laptop') form = LaptopForm(request.POST) context = { 'forms': form, 'header': 'Laptop' } return render(request, 'device/update_laptop.html', context) update_laptop.html: {% extends 'device/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <form action="" method="POST"> {% csrf_token %} <h3>Add {{ header }}:</h3> {{ forms|crispy }} <a href="{% url 'update_laptop' forms.id %}" class="btn btn-outline-info"type="submit">Update</a> </form> </div> {% endblock %} urls.py: path('update_laptop/<str:laptop_id>/', views.update_laptop, name='update_laptop')