Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding SSL to nginx in docker container on AWS returns connection refused
seeking some help with adding SSL using certbot on Ubuntu 18.04 + nginx. The issue is I get a ERR_CONNECTION_REFUSED error after adding SSL using certbot, I was able access my website (on port 80) before adding SSL. My Django app runs on port 3000 which has been exposed in my Dockerfile and passed in my nginx.conf file as well. docker-compose.yml db: image: postgres uwsgi: restart: always build: . nginx: restart: always image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro - ./uwsgi_params.par:/etc/nginx/uwsgi_params.par:ro - /etc/ssl/certs:/etc/ssl/certs:ro - /etc/ssl/private:/etc/ssl/private:ro redis: restart: always image: redis:latest I have already copied the generated certificates to their respective directories as shown in volumes. nginx.conf server { listen *:80; server_name mydomain.com; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name mydomain.com; root html; client_max_body_size 8000M; client_body_buffer_size 8000M; ssl_certificate /etc/ssl/certs/chained.pem; ssl_certificate_key /etc/ssl/private/domain.key; ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA; ssl_session_cache shared:SSL:50m; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_prefer_server_ciphers on; location /static { alias /var/www/static; } location ~ (\.php|.aspx|.asp|myadmin) { deny all; } location / { include /etc/nginx/uwsgi_params.par; uwsgi_pass uwsgi:3000; uwsgi_max_temp_file_size 10024m; } } I’ve also updated mydomain.com with my actual domain. -
Saving image after manipulation
I have 2 models. One called Choice and the other called ChoiceImage. class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') ChoiceImage img takes an ImageField. If the user uploads one image field, then that image is cut in half shown by this function: def slice_image(img): reader = misc.imread(img) height, width, _ = reader.shape with_cutoff = width // 2 s1 = reader[:, :with_cutoff] s2 = reader[:, with_cutoff:] misc.imsave(settings.MEDIA_ROOT + "/" + img.name, s1) return ContentFile(np.ascontiguousarray(s2)) The first image half gets resaved and the second image half gets saved for the second choice. Here's how the logic looks like: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") if not image_uploaded["img"]: q = validated_data.get("question") if not q.choice_set.exists(): raise APIException("You must upload either an image or a cover.") else: img = q.choice_set.all()[0].choiceimage.img img2 = slice_image(img) validated_data["choiceimage"]["img"] = img2 image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) It seems everything works fine. The first image gets cut in half and resaved in the media folder, however, the second image does not get saved and has the … -
Django get modelformset_factory input field ID's in html template
I am trying to get the input ids for my forms in an HTML template in order to write a javascript code to trigger the input field from as you click on a div. I am trying to print the id of every input field in the template however right now my code is not showing anything on the page: in my **template I currently have:** {% for form in formset %} {% for field in form.fields %} {{ field.auto_id }} {% endfor %} {% endfor %} And this is my view: @login_required def post_create(request): data = dict() ImageFormset = modelformset_factory(Images,form=ImageForm,extra=4) if request.method == 'POST': form = PostForm(request.POST) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() for f in formset: try: i = Images(posts=post, image=f.cleaned_data['image']) i.save() except Exception as e: break data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm formset = ImageFormset(queryset=Images.objects.none()) context = { 'form':form, 'formset':formset, } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) I was wondering if this is the best way to do this, however, is there any way to get the ID of the … -
NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P<slug>[\\w-]+)/$']
I got this error using django 2.0.7. Here are my codes: urls.py: urlpatterns = [ url(r'^home/$', HomeView.as_view(), name='ACRMS-Home'), url(r'^cart/(?P<slug>[\w-]+)/$', carts_views.update_cart, name='update_cart'), url(r'^cart/$', carts_views.view, name="cart"), ] views.py in carts: def view(request): cart = Cart.objects.all()[0] context = {"cart": cart} template = "cart/view.html" return render(request, template, context) def update_cart(request, slug): cart = Cart.objects.all()[0] try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass if not product in cart.products.all(): cart.products.add(product) else: cart.products.remove(product) return HttpResponseRedirect(reverse("cart")) template: <div> <h1>{{ product.name }} <a href='{% url "update_cart" product.slug %}' class ='pull-right'>Add to Cart</a></h1> </div> I am trying to add an item to the cart, but keep getting that error. I cannot tell why it is not able to find a reverse pattern, since I am very new to django. Please help. Thank you! -
Django: Serializer VS CustomUserManager
I was wondering, being new to Django and trying different practices, I was wondering whats the difference between using methods with a CustomUserManager and using the similar methods in the serializer. For exemple, I'm creating a User, and to correctly save the password I've put a method using user.set_password() When I'm only using the serializer it looks like this: from rest_framework import serializers from django.contrib.auth import get_user_model from ..models.model_user import * class UserIndexSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', 'password', 'first_name', 'last_name', 'email', 'is_a', 'is_o' ] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( username=validated_data['username'], password=validated_data['password'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'], is_a=validated_data['is_a'], is_o=validated_data['is_o'] ) user.set_password(validated_data['password']) user.save() return user class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' And when I'm using the CustomUserManager it looks like this: from django.db import models from django.contrib.auth.base_user import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def … -
Python - ugly code, refactor code into something simpler and more readable
ugly code, refactor code into something simpler and more readable if a <= b and f <= g and c<=d and d<=f and b<=c: print('pass') else: print('fail') ugly code, refactor code into something simpler and more readable min_length = min(len(colours),len(fruits)) for i in range(min_length): print(colours[i],fruits[i]) ugly code, refactor code into something simpler and more readable for i in range(len(colours)): print(i,colours[i]) ugly code, refactor code into something simpler and more readable for i in range(len(colours)-1,-1,-1): print(colours[i]) -
Django/Python Stripe stripeToken doesn't seem to load/work properly
I am trying to charge a subscription on Stripe API in test-mode and my charge keeps getting declined. Everything seems to be working fine, except I cannot retrieve the "stripeToken" via POST. I tested this by printing the various variables I need and they all work fine... but when it comes to printing stripeToken, I get this error: MultiValueDictKeyError at /memberships/payment/ 'stripeToken' Request Method: POST Request URL: http://127.0.0.1:8000/memberships/payment/ Django Version: 2.2 Exception Type: MultiValueDictKeyError Exception Value: 'stripeToken' Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/utils/datastructures.py in __getitem__, line 80 Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 Python Version: 3.8.2 Python Path: ['/Users/fred/Documents/yonder/videoservice', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/fred/Library/Python/3.8/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages'] Server time: Wed, 1 Apr 2020 16:20:53 -0700 Here is my view code: def PaymentView(request): user_membership = get_user_membership(request) try: selected_membership = get_selected_membership(request) except: return redirect(reverse("memberships:select")) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == "POST": token = request.POST['stripeToken'] try: token = request.POST['stripeToken'] customer = stripe.Customer.retrieve(user_membership.stripe_customer_id) customer.source = token # 4242424242424242 customer.save() subscription = stripe.Subscription.create( customer=user_membership.stripe_customer_id, items=[ { "plan": selected_membership.stripe_plan_id }, ] ) return redirect(reverse('memberships:update-transactions', kwargs={ 'subscription_id': subscription.id })) except: messages.info(request, "An error has occurred, investigate it in the console") context = { 'publishKey': publishKey, 'selected_membership': selected_membership } return render(request, "memberships/membership_payment.html", context) And here is my HTML code {% extends 'courses/base.html' %} {% load static %} … -
Model property displays default value for a field instead of actual value
I am a Django beginner and I started working on my first project. I implemented a model "extendedUser" with a medic_code field, extending User. It appears to be a problem when displaying the medic_code in a template. It doesn't display the actual property of the user, but the default value: "". Template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }} </p> <p class="text-secondary">{{ user.medic_code }}</p> (empty string here) </div> </div> <!-- FORM HERE --> </div> {% endblock content %} models.py: from django.db import models from django.contrib.auth.models import User class extendedUser(User): medic_code = models.CharField(max_length=20, default='') users/forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from users.models import extendedUser class UserRegisterForm(UserCreationForm): email = forms.EmailField() medic_code = forms.CharField(max_length=20) class Meta: model = extendedUser fields = ['username', 'email', 'medic_code', 'password1', 'password2'] views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save() #user.refresh_from_db() user.medic_code = form.cleaned_data.get('medic_code') user.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now … -
Grouping Form Fields using Django Crispy Forms
I'm trying to group fields in Django Model Form like this. But it doesn't work in Model Form. Is it possible to group? How do I do? class RegisterForm(forms.ModelForm): class Meta: model = People; exclude = ['isverified',] def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset('Group 1', Field('field1'), Field('field2')), Fieldset('Data 2', Field('field3')) -
How can we speed this up without modifying the body of the get_resource_identifier function?
How can we speed this up without modifying the body of the get_resource_identifier function -
Python websockets: cannot use AsyncToSync in the same thread as an async event loop
I am trying to write a multiplayer game using python websockets, The async server code is as below from websockets import WebSocketClientProtocol from asgiref.sync import async_to_sync class Player: def __init(self, websocket): self.websocket = websocket @async_to_sync async def send(self, msg): await self.websocket.send(msg) @async_to_sync async def receive(self): msg = await self.websocket.recv() return msg class Server: players = list() async def register(self, websocket): self.players.append(websocket) # register layers and if number of player greater than 2 start the game if len(self.players) >= 2: Game(self.players[:2]).start_game() self.players=self.players[2:] asyncio.get_event_loop().run_until_complete( websockets.serve(Server().ws_handler, 'localhost', 6191)) asyncio.get_event_loop().run_forever() The sync Game code is as below class Game: def __init__(self, players): self.players = players def start_game(self): self.players[0].send('hello') msg = self.players[0].receive() The issue is whenever I run the server code I get an error RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Can someone point the issue in my code? -
how can use two types of queryset models override save method?
I have two types of queryset. one is featured=true second is featured=false. i want to ask you if i POST an article with featured=True then the old featured=true get transferred to featured=false queryset. i just want two [:2] values in featured=true queryset. here is the example there are two article in featured=true queryset which i want the second article automatically get updated to featured=false when i create new article. i also try this method that method get this output! models.py def save(self, *args, **kwargs): if self.featured == True: Article.objects.filter(pk__in=(Article.objects.filter(featured=True,).values_list('pk',flat=True)[:2])).update(featured=False) self.featured = True super(Article, self).save(*args, **kwargs) -
Django Postgres syntax error at or near "SEPARATOR"
I recently migrated from mysql to postgres, and now I'm trying to see the admin page for a model in my app. Django responds with ProgrammingError at /admin/app/model/ syntax error at or near "SEPARATOR" LINE 1: ..._CONCAT("app_model_relatedModel"."relatedModel_id" SEPARATOR ... Any clues as to why this is happening? I'm never directly executing sql in the app, it's all done through the ORM. -
Django Using multiple (two) user types extending AbstractUser
For our project, we have two user types: Donor and Hospital. So we use the User model, which extends the AbstractUser model. The Donor and Hospital models both have OneToOneField relationship with the User and it uses the default user authentication. Almost everything works fine. The Donor and Hospital creation works well, the instances are added to the database and we can log in. However, we need the Donor object and its fields in the view and in the template. We have the user contained in the request and the id of the user. donor = Donor.objects.get(pk=request.user.id) Or donor = Donor.objects.filter(donor=request.user).first() Should return the donor object, but it returns None. It works for Hospital. If we do Donor.objects.all() the newly created Donor is not in the list. However, created hospital is present in the list. We cannot figure out what is the problem, the ids for donor and user do not match. Thank you very much for your help! These are our models: class User(AbstractUser): is_donor = models.BooleanField(default=False) is_hospital = models.BooleanField(default=False) class Donor(models.Model): # username, pword, first+last name, email donor = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # donor_id = models.IntegerField(auto_created=True, unique=True, null=False, primary_key=True) nickname = models.CharField(max_length=40, unique=True) phone = models.CharField(max_length=10) address = … -
Django channels process not sending data
I'm trying to create a Django Channels consumer which receives some data in real time from a RabbitMQ queue and then sends this data to a frontend, in order to let users have real-time data. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.queue_declare(queue='Test') def callback(ch, method, properties, body): print(" [x] Received %r" % body) channel.basic_consume( queue='Test', on_message_callback=callback, auto_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') await self.send({ "type": "websocket.accept" }) await channel.start_consuming() async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) And here is my Javascript code: <script> // websocket scripts var loc = window.location var wsStart = 'ws://' + window.location.host + window.location.pathname var endpoint = wsStart + loc.host + loc.pathname var socket = new WebSocket(endpoint) if (loc.protocol == 'https:'){ wsStart = 'wss://' } socket.onmessage = function(e){ console.log("message", e) } socket.onopen = function(e){ console.log("message", e) } socket.onerror = function(e){ console.log("message", e) } socket.onclose = function(e){ console.log("message", e) } </script> The problem with this code is that, altough in my console i will see the queue waiting for data, on my HTML page i won't see any … -
Django: How can i validate the combination existance of two fields
I'm using Django Model Form Can you help me validate those fields to get field error using clean()? Name cannot repeat on the same office, can only repeat on different office. class CreateSalesRepForm(forms.ModelForm): class Meta: model = CreateSalesRep fields = ['name', 'office'] widgets = { 'office': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Enter Office'}), 'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Name'}) } -
Show TimeField value without seconds - Django
I'm displaying a selectbox with hours in it. This hours are fixed and coming from db. For this I used models.TimeField in models.py. Now in html page these hours are shown like 14:00:00. I want to remove seconds. Here are my codes: models.py: class MeetingHour(models.Model): hour = models.TimeField() def __str__(self): return str(self.hour) html: <select> {% for meetinghour in meetinghours %} <option value="{{meetinghour}}">{{meetinghour}}</option> {% endfor %} </select> -
Can't login to django admin account after creating super user
I created a project in django and the first thing I want to do is to create a superuser for admin account and then proceed with the django project but the problem is after creating a superuser account using pyhton manage.py createsuper and filling out the information the superuser gets created it says Superuser created successfully. But when I try to login with these credentials it says Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. I am not sure if there is some other setting that I need to check out or I am doing something wrong. Please suggest me solution for that. -
MoviePy in Django: Failed to read the duration of the file
I'm trying to pass the video data pulled from a ModelsForm into a moviepy method, however the VideoFileClip() function is unable to read the duration of the file. I've checked the data I'm pulling in and it is the correct namem, currently the issue may be that I'm passing it in as a string. However, without this is errors back as 'endswith' is not a valid attribute. Please see the error and my code below. Thanks for your help! Code Models.py Error Message OSError at /highlights/ MoviePy error: failed to read the duration of file <highlights.splitter.Splitter object at 0x000001A82CE553D0>. Here are the file infos returned by ffmpeg: ffmpeg version 4.1 Copyright (c) 2000-2018 the FFmpeg developers built with gcc 8.2.1 (GCC) 20181017 configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth libavutil 56. 22.100 / 56. 22.100 libavcodec 58. 35.100 / 58. 35.100 libavformat 58. 20.100 / 58. 20.100 libavdevice 58. 5.100 / 58. 5.100 libavfilter 7. 40.101 / 7. 40.101 libswscale 5. … -
Why serializing a QuerySet I iobtain a string?
I'm using a js function to obtain some data from my django models. Concretely, I want to obtain the last value from my sensors. I'm doing the following, from django.core import serializers def getData(request): ctx = {} if request.method == 'POST': select = int(request.POST['Select']) last_val = DevData.objects.order_by('dev_id','-data_timestamp').distinct('dev_id') data = serializers.serialize('json', last_val) print(data) print('****************') print(data[0]) # I just obtain a "[" then is a string not a list ctx = {'Select':data} return JsonResponse(ctx) My question is, why the output is a string? How can I convert it to a Json object and then pass it to my js function? Thank you very much!! -
Django Login POST hangs when i do HttpResponseRedirect (302)
I'm Juan Manuel and I have a problem with my Login page in Django 1.11 (Python 2.7). When I do "POST" of username/password Form (passes authenticate() and login() well) and have to redirect (HttpResponseRedirect) to my index page, the browser hangs waiting for a response (it stays in the login page). After POST it wants to redirect to to '/' with a HTTP 302 and stays like that. [01/Apr/2020 16:19:43] "POST /login/ HTTP/1.1" 302 0 I've noticed a few things: 1) It doesn't happend everytime. 2) On Chrome's developer mode with "Disable cache" mode on works fine. 3) On Firefox works fine. 4) With reverse() it's the same problem (internally calls HttpResponseRedirect()). 5) The problem exists on the Developing Server (Django) and in Production Server (Apache). When it's hanging like that, if I press F5 (reload), works fine and the redirection goes to the index. url.py: # -*- coding: utf-8 -*- from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from .views import * admin.autodiscover() urlpatterns = patterns('', url(r'^', include('tadese.urls')), url(r'^login/$', login), url(r'^login_cuota/$', login_cuota), url(r'^logout/$', logout), url(r'^admin/', include(admin.site.urls)), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG is False: #if DEBUG … -
How to add a share button in Django to share a post
I am relatively new to Django, I have a blog that I have been working on. However, I am having problem implementing a sharing button to share my posts on social media, with the title and thumbnail,specifically Facebook and WhatsApp.I have researched and googled all the possible solutions, but neither of them tends to solve my problem. Not many tutorials out here have covered this issue. I have used the social_share,django_addthis, and social_share_widgets but none of them seem to help. Here are my models and templates {% extends 'base.html' %} {% load static %} {% load social_share %} {% load blog_tags %} {% block content %} <p>{{post.content| safe}}</p> <div class="social-contact"> <a href="#" id="shown" style="background-color: red;"><i class="fa fa-share"></i> Share</a> <a id="hidden" href="https://facebook.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="facebook-link"><i class="fa fa-facebook"></i> Facebook</a> <a id="hidden" href="https://www.twitter.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="twitter-link"><i class="fa fa-twitter"></i> Twitter</a> <a id="hidden" href="https://www.instagram.com/share?url=http://devbrian.com{{ request.get_full_path|urlencode }}" class="instagram-link"><i class="fa fa-instagram"></i> Instagram</a> <a style="background-color: green;" href="https://api.whatsapp.com/send?+254799043853=+*YOURNUMBER*&text=%20*{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://devbrian.com*" class="youtube-link"><i class="fa fa-whatsapp"></i> Whatsapp</a> </div> {% endblock content %} class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200,blank=True,unique=True) thumbnail = models.ImageField() def get_absolute_url(self): return reverse('details', kwargs={'slug': self.slug}) I will appreciate your help -
Django-differnt models for specific group model choices Django
Could someone help me how to solve my question, What is an efficient and good way to write group model choices, I want multiple Django model values depends on choice field values! (Django rest framework)enter image description here For jobs it's giving different field and if you choose another option it displaying other options like below picture This is for cars..I would like to write code for this similar one -
HOW TO EDIT A RECORD BY USE DJANGO FORM INTO A TEMPLATE
I have two models that have relationship to each other which are a child and academy model which means that a child can have academic details,and then i pass a child ID into the template to edit academic details of child here is academy model #ACADEMY MODEL from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) here is child model #CHILD MODEL from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname I come to the scenario that i want to edit academic details of a child by use django form to the template that i pass child ID def edit(request,pk): child=get_object_or_404(Child_detail,pk=pk) form=AcademicForm(request.POST or None,instance=child) if form.is_valid(): form.instance.Student_name=child form.save() return redirect('more',pk=pk) context={ 'form':form } return render(request,'functionality/more/academy/edit.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And also this is my template that pass child id <form action="" method="post" autocomplete="on"> {% csrf_token %} … -
meke tests with django inside innerHTML method
I am new in django and I faced a problem in my project.The problem is I want to put some tests inside innerHTML method like this: var level = document.getElementById('level'); selectElementM.innerHTML = ` <option value="">--select--</option> {% for module in modules %} {% ifequal module.level|lower ${level} %} <option value="{{ module.name}}">{{ module.name}}</option> {% endifequal %} {% endfor %} // here are other tests... `; I know it's not possible for doing it like this so I need another proper way