Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest how to save current user when creating an new blog?
When I am creating an blog post I also want to automatically save the current user without selecting the user manually as a blog author. here is my code: models.py: class Blog(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) blog_title = models.CharField(max_length=200, unique=True) serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog views.py class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug' def get_permissions(self): if self.action == 'retrieve': permission_classes = [IsOwnerOrReadOnly] elif self.action == 'list': permission_classes = [IsOwnerOrReadOnly] else: permission_classes = [IsOwnerOrReadOnly & IsAuthorGroup] return [permission() for permission in permission_classes] -
Point of Sales System Using python
Point of Sales System Using python. Guys, I need your experience to develop my POS system. These are my question. Please share your opinion about this question. This is my basic idea about this POS system. I am trying to create a POS system for a shop with various items such as supermarkets and electronic items. It means that has multiple types of products in this shop. I need to add stock management also this software not only that it is necessary to add expiration dates to some categories of products as well (My idea is to send an alert to shop owners about expired that products). Among these features, I need to add a thermal printer and a barcode reader as well. And also I need to generate some sales reports as well with the net profit. These are my questions. I decided to use python to create my POS system. Is that language ok for that software? If it is ok, If I try to implement it as a stand-alone application, which is the most suitable GUI builder for that? (Ex: PyQt, Tkinter, Kivy). Is that ok to use Django for this ? Based on my basic idea … -
How to safely add an additional fee for additional services in an online store?
I have an online car rental store built on Python Flask. My problem is that: When choosing a car, the customer goes to the checkout page, where he can choose additional services, for example: GPS navigator, child seats and other services. The cost of some services depends on the number of rental days, for example, for a Gps navigator, the cost of 1 day is $ 5. The question is, how can I safely get the cost of these additional services from the FrontEnd and add to the cost of the car received from the BackEnd side I am trying to safely connect the cost of renting a car with the cost of additional services, some of which depend on the number of rental days.My task is to implement this system as safely as possible, but I do not know how it can be done -
ValueError: The view **** didn't return an HttpResponse object. It returned None instead
I'm using Django forms to handle user input for some point on my Django app .. but it keeps showing this error whenever the user tries to submit the form ValueError: The view *my view name goes here* didn't return an HttpResponse object. It returned None instead here is my code : Forms.py class sendBreachForm(forms.Form): """ Form for sending messages to users. """ text = forms.CharField(max_length=100) image = forms.FileField() cords = forms.CharField(widget=forms.TextInput( attrs={"type":"hidden"} )) views.py @login_required def web_app(request): if request.user.is_staff or request.user.is_superuser: return redirect('/ar/system/') else: if request.method == "POST": form = sendBreachForm(request.POST) print("AAAAAAAAa in a post request") if form.is_valid(): print("AAAAAAAAa form is valid") text = form.cleaned_data['text'] image = form.cleaned_data['image'] cords = form.cleaned_data['cords'] try: new_breach = Breach.object.create(text=text,image=image) add_form_cords_to_breach(request,new_breach,cords) print("AAAAAAAA added breach") return render(request,"web_app.html",context) except : print("AAAAAAAA error ") return render(request,"web_app.html",context) # raise Http404('wrong data') else: form = sendBreachForm() context = {} context['form']=form context['all_elements'] = WaterElement.objects.all() current_site = Site.objects.get_current() the_domain = current_site.domain context['domain'] = the_domain all_layers = MapLayers.objects.all() context['all_layers']=all_layers return render(request,"web_app.html",context) HTML <form method ='post'> {% csrf_token %} {{form.text}} <label for="text">وصف المعاينة</label> {{form.image}} <label for="image">صورة المعاينة</label> {{form.cords}} <input type="submit" value = "إرسال المعاينة"> </form> -
JSONDecodeError - request.body returns empty string Django
I am trying to access some JSON data from my views.py page but it seems i'm sending empty strings? My JS code document.querySelector('#compose-form').onsubmit = () => { const recipients = document.querySelector('#compose-recipients').value const subject = document.querySelector('#compose-subject').value const body = document.querySelector('#compose-body').value fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: String(recipients), subject: String(subject), body: String(body) }) }) .then(response => response.json()) .then(result => { load_mailbox('sent'); console.log(result); }); return false; }; What i was trying to replicate: fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: 'baz@example.com', subject: 'Meeting time', body: 'How about we meet tomorrow at 3pm?' }) }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); recipient, subject, and body are expected to be strings, given that i am grabbing mine from a form and have them in a variable i thought to convert them to strings **Template ** <form id="compose-form" action="{% url 'compose' %}" method="POST"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject"> </div> <textarea class="form-control" id="compose-body" placeholder="Body"></textarea> <input type="submit" class="btn btn-primary" id="compose-submit"/> </form> URL path("emails/", views.compose, name="compose"), Views.py data_unicode = request.body.decode('utf-8') data = json.loads(data_unicode) when i debug this is what i get: (return) body: b' ' … -
Vue3 frontend, Django back end. Key error for validated data in serializer
I have a Vue front end that collects data (and files) from a user and POST it to a Django Rest Framework end point using Axios. Here is the code for that function: import { ref } from "vue"; import axios from "axios"; const fields = ref({ audience: "", cancomment: "", category: "", body: "", errors: [], previews: [], images: [], video: [], user: user, }); function submitPost() { const formData = { 'category': fields.value.category.index, 'body': fields.value.body, 'can_view': fields.value.audience, 'can_comment': fields.value.cancomment, 'video': fields.value.video, 'uploaded_images': fields.value.images, 'user': store.userId }; console.log(formData['uploaded_images']) axios .post('api/v1/posts/create/', formData, { headers: { "Content-Type": "multipart/form-data", "X-CSRFToken": "{{csrf-token}}" } }) .then((response) => { if(response.status == 201){ store.messages.push("Post created successfully") } }) .catch((error) => { messages.value.items.push(error.message) }) } When I post data the response I see on the server side is: uploaded_data = validated_data.pop('uploaded_images') KeyError: 'uploaded_images' that comes from this serializer: class PostImageSerializer(serializers.ModelSerializer): class Meta: model = PostImage fields = ['image', 'post'] class PostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) uploaded_images = serializers.ListField(required=False, child=serializers.FileField(max_length=1000000, allow_empty_file=False, use_url=False),write_only=True) class Meta: model = Post fields = [ "category", "body", "images", "uploaded_images", "video", "can_view", "can_comment", "user", "published", "pinned", "created_at", "updated_at", ] def create(self, validated_data): uploaded_data = validated_data.pop('uploaded_images') new_post = Post.objects.create(**validated_data) try: for uploaded_item in uploaded_data: … -
Problem : Can't parse 'center'. Sequence item with index 0 has a wrong type
TypeError at /mark_your_attendance Can't parse 'center'. Sequence item with index 0 has a wrong type Hello guys! i am working related with attendance system using Face Recognition, i have trained the captured images once want to mark the attendance it gives me following error, i have used django at backend. def mark_your_attendance(request): detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor( 'face_recognition_data/shape_predictor_68_face_landmarks.dat') # Add path to the shape predictor ######CHANGE TO RELATIVE PATH LATER svc_save_path = "face_recognition_data/svc.sav" with open(svc_save_path, 'rb') as f: svc = pickle.load(f) fa = FaceAligner(predictor, desiredFaceWidth=96) encoder = LabelEncoder() encoder.classes_ = np.load('face_recognition_data/classes.npy') faces_encodings = np.zeros((1, 128)) no_of_faces = len(svc.predict_proba(faces_encodings)[0]) count = dict() present = dict() log_time = dict() start = dict() for i in range(no_of_faces): count[encoder.inverse_transform([i])[0]] = 0 present[encoder.inverse_transform([i])[0]] = False vs = VideoStream(src=0).start() sampleNum = 0 while(True): frame = vs.read() frame = imutils.resize(frame, width=800) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = detector(gray_frame, 0) for face in faces: print("INFO : inside for loop") (x, y, w, h) = face_utils.rect_to_bb(face) face_aligned = fa.align(frame, gray_frame, face) cv2.rectangle(frame, (int(x, y)), (int(x+w, y+h)), (0, 255, 0), 1) (pred, prob) = predict(face_aligned, svc) if(pred != [-1]): person_name = encoder.inverse_transform(np.ravel([pred]))[0] pred = person_name if count[pred] == 0: start[pred] = time.time() count[pred] = count.get(pred, 0) + 1 if … -
Django, how to display separate html blocks, which can then be edited in one place
I need to display the navbar, footer, main, base, title - in separate blocks, which can then be edited in one place, and the changes will occur everywhere Сan you give me an idea how to do it, I have no idea just I thought to do it with this function {% extends "..{directory}/{the name of html page}.html" %} But I think this won't work -
Send a welcome email after the user has confirmed his account in django
I'm trying to figure out how I can send welcome emails in Django after the user confirms their account. The welcome email should be sent only to users who have their emails confirmed (active users after signing up) and should be sent after the confirmation email. Any help in solving this will be highly appreciated models from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views from django.contrib.auth import login from django.contrib.auth.models import User from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from core.tokens import account_activation_token # Sign Up View class SignUpView(View): form_class = SignUpForm template_name = 'commons/signup.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return redirect('login') return render(request, self.template_name, {'form': … -
django rest framework what is login as the definition
Let me say in advance that thank you for reading my question. The problem I'm facing is related to login and permission from frontend. For example, log in as a user from the browser(like hit localhost:8080/admin in the search engine), and then you can see the user name on the right upper side of the screen which indicates the user is logged in. How Django identify the user login is that when you log in csrftoken is created and set in the cookies, so if you delete csrftoken, the username is disappeared, so you need to log in to access admin if you need. This login system is related to permission.IsAutenticated, so if 'DEFAULT_PERMISSION_CLASSES' : ['rest_framework.permissions.IsAuthenticated'], you cannot access any data if you are not logged in. Then I implemented social google login which receives google access_token to log in as a Django user(I will omit to describe how to get a google access token process), which works fine in the browser. I can see the username on the screen, and permission is working ok. But when I hit google social login endpoint from the front end, I can't log in, also csrftoken is not created in the cookies.(no error … -
PERFORMANCE Calling multiple times a posgres db to get filtered queries vs querying all objects and filtering in my django view
I'm working in a Django project and it has a postgreSQL db. I'm calling multiple times the model to filter the results: latest = Product.objects.all().order_by('-update_date')[:4] best_rate = Product.objects.all().order_by('rating')[:2] expensive = Product.objects.all().order_by('-price)[:3] But I wonder if it's better for performance and resources consumption to just do 1 query and get all the objects from the database and do the filtering inside my Django view. all = Product.objects.all() # Do some filtering here iterating over variable all Which of these do you think would be the best approximation? Or do you have a better option? -
Trying to embed a form within a form of foreign keys
I'm trying to create a form where a logged in user (PrincipalGuest) can update themselves but also multiple guests (AccompanyingGuest). I want an entire form with the attending and dietary_restrictions field embedded within a form, not just the ModelMultipleChoiceField. models.py class Guest(models.Model): """ """ attending = models.ManyToManyField("itinerary.Event", blank=True) dietary_restrictions = models.ManyToManyField(DietaryRestrictions, blank=True) last_modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class PrincipalGuest(Guest, AbstractUser): """ """ USERNAME_FIELD = "email" REQUIRED_FIELDS = [] username = None email = models.EmailField(_("email address"), unique=True) phone_number = PhoneNumberField(null=True) address = AddressField(on_delete=models.CASCADE, null=True) objects = PrincipalGuestManager() @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name class AccompanyingGuest(Guest): """ """ principal = models.ForeignKey( PrincipalGuest, related_name="accompanying_guests", on_delete=models.CASCADE ) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) is_under_ten = models.BooleanField(default=False) @property def name(self): return self.first_name + " " + self.last_name def __str__(self): return self.name views.py class RendezvousFormView(SuccessMessageMixin, UpdateView): template_name = "rsvp.html" form_class = RendezvousForm success_url = "/rsvp" success_message = "Thank you for your RSVP" def get_object(self): return self.request.user forms.py class RendezvousForm(ModelForm): """ """ first_name = CharField( label="", widget=TextInput(attrs={"placeholder": "First Name"}) ) last_name = CharField( label="", widget=TextInput(attrs={"placeholder": "Last Name"}) ) email = CharField(label="", widget=TextInput(attrs={"placeholder": "Email"})) phone_number = CharField( label="", widget=TextInput(attrs={"placeholder": "Phone Number"}) ) address = AddressField( label="", widget=AddressWidget(attrs={"placeholder": … -
NOT NULL constraint failed: ial_profile.user_id
I am new to Django and was trying to follow a tutorial. But i came across this problem and is not able to solve it myself. When i try to access 127.0.0.1:8000/profile/id(1,2,3...) then it is throwing 'IntegrityError'. Can anyone please help me to overcome it? Code example : views.py from django.shortcuts import render from .models import Profile # Create your views here. def dashboard(request): return render(request, "base.html") def profile_list(request): profiles = Profile.objects.exclude(user=request.user.id) return render(request, "ial/profile_list.html", {"profiles": profiles}) def profile(request, pk): if not hasattr(request.user, 'profile'): missing_profile = Profile(user=request.user.id) missing_profile.save() profile = Profile.objects.get(pk=pk) # edit 1 if request.method == "POST": current_user_profile = request.user.profile data = request.POST action = data.get("follow") if action == "follow": current_user_profile.follows.add(profile) elif action == "unfollow": current_user_profile.follows.remove(profile) current_user_profile.save() return render(request, 'ial/profile.html', {'profile': profile}) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField( "self", related_name = "followed_by", symmetrical=False, blank=True ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: user_profile = Profile(user=instance) user_profile.save() user_profile.follows.set([instance.profile.id]) user_profile.save() profile.html {% extends 'base.html' %} {% block content %} <div class="column"> <div class="block"> <h1 class="title is-1"> {{profile.user.username|upper}}'s djail </h1> </div> … -
Django DecimalField fails to save even though I give it a floating number
class WithdrawRequests(models.Model): withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True) timestamp = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=255, unique=False, db_index=True) currency = models.CharField(max_length=255, unique=False, db_index=True) user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150) withdraw_address = models.CharField(max_length=255, unique=False, db_index=True) withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15) This is my models.py file. currency = request.data['currency'] payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) timestamp = datetime.datetime.now() timestamp = timestamp.timestamp() withdraw_hash = hashlib.sha256() withdraw_hash.update(str(timestamp).encode("utf-8")) withdraw_hash = withdraw_hash.hexdigest() username = user.username currency_balance = GAME_CURRENCIES[request.data['currency']] user_balance = getattr(user, currency_balance) withdraw_address = request.data['withdraw_address'] withdraw_amount = request.data['withdraw_amount'] if user_balance < withdraw_amount: return Response({ "message": "Not enough funds." }) else: # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount withdraw = WithdrawRequests() withdraw.withdraw_hash = withdraw_hash, withdraw.timestamp = datetime.datetime.now(), withdraw.username = username, withdraw.currency = currency, withdraw.user_balance = user_balance, withdraw.withdraw_address = withdraw_address, withdraw.withdraw_amount = withdraw_amount withdraw.save() And here is the views.py file. Whatever I do the error is the following. ... File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.'] As you can see with user_balance everything is fine and it's floating number. -
how to upload multipe images in django rest framework(drf)
I want to upload multiple images,Is there a way to do it without using foreign keys. The images is just a attribute in my model. model.py class sellGoods(models.Model): img = models.ImageField(max_length=100, upload_to=get_file_path, default='sell.png', verbose_name='图片', null=True, blank=True) # 与用户绑定 # user = models.ForeignKey(UserInfo, on_delete=models.CASCADE) goods_name = models.CharField(verbose_name=_('物品名称'), max_length=90) # Many attributes are omitted here serializers.py ` class sellSerializer(serializers.ModelSerializer): class Meta: model = sellGoods fields = '__all__' ` view.py class sellGoodsList(APIView): def post(self, request, format=None): serializer = sellSerializer(data=request.data) qdata = request.data print('1: ',qdata) print('2: ',qdata['img']) print('3: ',qdata.get('img')) print('------------') if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in postman Realize uploading multiple image -
Getting values from django database
I'm just learning python and django. I am writing a thing that reads the values in the xlsx file, and if the values are similar to those in the database, then the value in the adjacent column in the xlsx file changes to the one I specify models.py class imgUpload(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to='img') def __str__(self): return self.title views.py def upload_xlsx(request): if request.method == 'POST': form = xlsxForm(request.POST, request.FILES) if form.is_valid(): form.save() fileName = xlsxUpload.objects.last() fileNameStr = str(fileName.file) book = load_workbook(fileNameStr) sheet: worksheet = book.worksheets[0] for row in range(2, sheet.max_row + 1): a = sheet[row][0].value fileNameImg = imgUpload.objects.all() fileNameImgStr = fileNameImg.filter(title=a) if a == fileNameImgStr: sheet[row][1].value = str(fileNameImgStr) book.save(fileNameStr) book.close() return redirect('xlsx_list') else: form = xlsxForm() return render(request, 'img/upload_xlsx.html', { 'form': form }) I have achieved that it takes all the values, but does not compare them -
How do I get rid of labels in django Form?
I have dealt with only ModelForm previously, so it is my first time using Form. I'd like to get rid of labels from my form, however, how I get rid of labels in ModelForm does not seem to work with Form. Here is my code: forms.py class UserLoginForm(forms.Form): email = forms.CharField(max_length=255) password = forms.CharField(max_length=255) labels = { 'email': '', 'password': '' } widgets = { 'email': forms.TextInput(attrs={'class': 'login_input', 'placeholder': 'Email'}), 'password': forms.PasswordInput(attrs={'class': 'login_input', 'placeholder': 'Password'}) } It seemed like a simple problem but it turned out I could not get what I wanted from the official django document or Google. I'd be really appreciated if you could help me solving it. Thank you. -
Django Unit Test login
I am trying to do a Unit-Test to check that an authenticated user accesses the url /downloads on my Django site but I get the following error: django.db.utils.ProgrammingError: (1146, "1146 (42S02): Table 'test_my_db_dev.filminfo' doesn't exist", '42S02') My Unit-Test looks like this: from django.test import TestCase class TestLoginView(TestCase): def test_authenticated_user_can_see_page(self): user = User.objects.create_user("SomeUser," "some_user@mymail.net", "my_testP@ss!") self.client.force_login(user=user) response = self.client.get("/downloads") self.assertEqual(response.status_code, 200) I would appreciate any help/comments. Thanks :) -
style.css not loading in django html template
I created a login page and calling a static css sheet for styling but its not working. I load static in my login.html and use <html> <head> <title>PWC Login</title> <link rel="stylesheet" href="{% static 'css/style.css'%}"> </head> <body> <div class="loginbox"> <img src="{% static 'images/avatar.png' %}" class="avatar"> <h1 class="h1">Login Here</h1> <form> <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="Login"> <a href="#">Forgot your password?</a><br> <a href="#">Don't have an account?</a> </form> </div> </body> </html> css: body { margin: 0; padding: 0; background: url('static/images/pic1.jpeg'); background-size: cover; background-position: center; font-family: sans-serif; } .loginbox{ width:320px; height:420px; background: #000; color: #fff; top:50%; left:50%; position: absolute; transform: translate(-50%,-50%); box-sizing: border-box; padding: 70px 30px; } .avatar{ width: 100px; height: 100px; border-radius: 50%; position: absolute; top: -50px; left: calc(50% - 50px); } i tried the html and css file separately and it works fine. the background is the jpeg file and the login box is centered. it has to be something in django but not sure what it is. -
How do I target a ForeignKey attribute inside a loop?
I've a cart view and when a user is authenticated and has products in the cart view, I wanna check against product availability and if one product is found with availability set to False I wanna render Out of stock, the code for not authenticated users works, but for authenticated users Traceback Error is 'OrderItem' object has no attribute 'availability' Models class Product(models.Model): availability = models.BooleanField() class OrderItem(models.Model): product = models.ForeignKey(Product) order = models.ForeignKey(Order) Views def cart(request): data = cartData(request) items = data['items'] orderitemlist = OrderItem.objects.all() if not request.user.is_authenticated: available = all(x['product']['availability'] for x in items) else: available = all(x.availability for x in orderitemlist) context = {"items": items, 'available': available} Template {% if available %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} -
Hi everyone, I just started learning DJango and I am stuck with Jinja
In my folder Templates I created 2 html files: main.html projects.html The structure of the main.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DJANGO</title> </head> <body> {% block userinfo %} {% endblock userinfo %} </body> </html> The structure of the user.html is: {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock userinfo %} I don't understand why <h2>John Doe</h2> <p>Explorer of life.</p> doesn't appear in the browser when I call main.html I have tried writing in this way too {% extends "main.html" %} {% block userinfo %} <h2>John Doe</h2> <p>Explorer of life.</p> {% endblock %} without user in the endblock but it does not work. In settings.py file in Templates list and DIR list I added: os.path.join(BASE_DIR,'templates'), and I importend os too. In views.py file that I've created I have written from django.shortcuts import render from django.http import HttpResponse def main(request): return render(request,'main.html') In urls.py file that I've created I have written from django.urls import path from . import views urlpatterns = [ path('main/',views.main,name='') ] When I call the page with http://localhost:8000/main/ I don't have any error. The only problem is that the page is blank. … -
How can i Access primary key in template tag
I am trying to create an update view that allows users to update their data. I am trying to access the data by using primary keys. My problem is that i do not know the syntax to implement it. views.py def updatedetails(request, pk): detail = Detail.objects.get(id=pk) form = Details(instance=detail) if request.method == "POST": form = Details(request.POST, instance=detail) if form.is_valid(): form.save() return redirect(success) return render(request, "details.html", {"form":form}) urls.py from django.urls import path from . import views urlpatterns = [ path("details/", views.details, name="details"), path("success/", views.success, name="success"), path("edit/<str:pk>/", views.updatedetails, name="updatedetails"), ] my html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Success</title> </head> <body> <h1>Thank You for Filling Out the Form</h1> <p><a href="/edit/{{request.detail.id}}/">Click Here To Edit</a></p> </body> </html> So what i am trying to figure out is how to call the primary key in my template -
Django - use multiple fields proprieties
class Event(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) guests = models.IntegerField() description = models.CharField(max_length=300) venue = models.BooleanField(default=False) garden = models.BooleanField(default=False) candybar = models.BooleanField(default=False) games = models.BooleanField(default=False) wine = models.BooleanField(default=False) premiumphoto = models.BooleanField(default=False) premiumvideo = models.BooleanField(default=False) limo = models.BooleanField(default=False) stuff = models.BooleanField(default=False) totalprice = models.IntegerField() This is my event model, i want the user to be able to select if they want, for example games, if they do i want the total price to be updated with the price of games wich could be 500$, how can i set games to be a bool and to have a value that can be changed by the admins. I think an interesint idea could be to have some kind of model that is default and the other models to take the price from the Price model -
DRF method GET not allowed on @action based function
I have the two models: Article and Comment. I have the ArticleAPI viewset, which have methods decorated with @action to handle requests to comments model, but when I am trying to test this endpoint via Postman I get an error: { "detail": "Method \"GET\" not allowed." } ArticleAPI.py class ArticleAPI(viewsets.ModelViewSet): serializer_class = ArticleSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly ] queryset = Article.objects.order_by('number') lookup_field = 'pk' ... @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-list') def get_comments_queryset(self, request): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.all(), many=True) return Response(serializer.data) @action(methods=['GET'], detail=True, url_path='comments', url_name='article-comments-object') def get_comment_object(self, request, pk=None): instance = self.get_object() serializer = CommentSerializer(queryset=instance.comment_set.get(pk=pk)) return Response(serializer.data) urls.py router = DefaultRouter() router.register('articles', articleAPI.ArticleAPI, basename='articles') -
Python Django session expire on redirect url is called
I have made an medium size website and am trying to implement payment gateway(paytm). In order to process the payment token is needed to start the payment, i could able to generate the token from the api request and the JS payment page is being invoked successfully. The main problem am encountering is after selecting the payment and start the payment pop up page appears to getting an error Session expired due to inactivity with in a seconds the page load. I tried contacting the payment gateway dev team but the could able to generated the payment successfully. However they are doing it in flask or through postman. when i try to run the code i have no problem processing the payment but when i use the same code in the Django am unable to process the payment.Even they are unable to understand the problem am getting(i.e session expired due to inactivity.) I am wondering this has to do something with the sessions and when i have stored the token in the session and call the payment page at then i do not get the error but am getting another issue is that the values are not being passed to …