Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SignatureDoesNotMatch DigitalOcean Spaces Boto3 Django-Storages Django
You got the following error while using your digital ocean spaces for static files: <Error> <Code>SignatureDoesNotMatch</Code> <RequestId>xxxxx-716fe6ea-xxxx</RequestId> <HostId>xxx-nyc3c-xxx-xxxx</HostId> </Error> GET 403 Forbidden -
For looping in Django not worked
Hi I am newbie in django, I have problem with for looping in django, to make a navbar/menu, I use for looping in html like this: <div class="menu"> <a href="/"> <div class="menu-link klik"> <i class="bx bx-home"></i> <div class="contentMenu hidden">HOME</div> </div> </a> for key,value in menu.items %} <a href="{% url 'app_'|add:key|add:':'|add:key %}"> <div class="menu-link klik"> <i class="{{value}}"></i> <div class="contentMenu hidden">{{key|upper}}</div> </div> </a> endfor %} </div> and the views: from django.shortcuts import render from .forms import ProjectForm def index(request): projectForm = ProjectForm() context = { 'title': 'Achmad Irfan Afandi', 'tile': 'Home', 'subtitle': 'Data Analyst', 'social_media': {'linkedin':'https://www.linkedin.com/in/achmad-irfan-afandi-9661131a6/', 'github':'https://www.github.com/achmadirfana', 'facebook':'https://www.facebook.com/achmad.irfan.754', 'twitter':'https://www.facebook.com/achmad.irfan.754', 'instagram':'https://www.facebook.com/achmad.irfan.754'}, 'menu': {'about': 'bi bi-file-earmark-person', 'education': 'bx bxs-graduation', 'skill': 'bx bx-wrench', 'projects': 'bx bx-building', 'services': 'bx bx-support', 'contact': 'bx bxs-contact'}, 'projectForm': projectForm } return render(request, 'index.html', context) that code above is in main app projec, all the menus are displayed properly like picture above: enter image description here But in another app (btw I use extends tag for all app) , the for looping is not displayed , it just show 'HOME' menu that not include in for looping like picture below: enter image description here Do you know why? or I have to write the menu one by one not use foor … -
Checking if there are security issues with my django form
I hope you can help me clarify some things regarding my django form, which is used for a chat app. Honestly, I don't know a lot about security against hackers, so my concern is mainly related to form security. My questions are simply put... Did I do django form backend validation correctly? I read that backend validation prevents hackers from injecting malicious codes into the database. Are there any other security issues in my code? I hope you can point out even very basic things I might be missing out. Here is my template <form id="post-form"> {% csrf_token %} <input type="hidden" name="user_id" id="user_id" value="{{user_id}}"/> <input type="text" name="var1" id="var1" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/submit/', data:{ user_id:$('#user_id').val(), var1:$('#var1').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ alert(data) } }); document.getElementById('var1').value = '' }); </script> </html> Here is my views.py for the ajax: @login_required def submit(request): if request.method == 'POST': user_id = int(request.POST['user_id']) form = ChatForm(request.POST) if isinstance(user_id, int) and form.is_valid(): chat_instance = form.save(commit=False) user = User.objects.get(id=user_id) chat_instance.var2 = form.cleaned_data['var1']+"edited" chat_instance.user = user if request.user.is_admin: chat_instance.admin = True else: chat_instance.admin= False chat_instance.save() return HttpResponse('Message sent successfully') else: return HttpResponse('Error') return HttpResponse('Not a valid request method') Here is … -
Got an error while running a django project in docker
This site can’t be reached The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID I want the correct starting page of first page of project.I tried multiple times, but the error is same. -
how can I stop django-elasticsearch-dsl search_index command from taking input?
In order for django-elastic-dsl to index the documents we have to run python manage.py search_index --rebuild on every deploy. so I faced an issue having docker-compose executing my django project and that is: File "/root/.local/share/virtualenvs/django-lHo0u5mj/lib/python3.11/site-packages/django_elasticsearch_dsl/management/commands/search_index.py", line 172, in _delete 2023-08-20T13:58:47.033526087Z response = input( 2023-08-20T13:58:47.033533712Z ^^^^^^ 2023-08-20T13:58:47.033537712Z EOFError: EOF when reading a line apparently this command is prompting an input from the user and it's called on every docker-compose build command, here is my start.sh file: #!/usr/bin/env bash pipenv run python manage.py makemigrations pipenv run python manage.py migrate pipenv run python manage.py search_index --rebuild #pipenv run python manage.py collectstatic --no-input pipenv run gunicorn --reload --bind 0.0.0.0:8000 service_monitoring.wsgi:application what is the workaround of not running the command mannually everytime I start the container? -
Wagtail fields not showing up in pages list response
Im using Wagtail with django and I'm following the tutorial. I've got a BlogPage like so: class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) # Add this: authors = ParentalManyToManyField("blog.Author", blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) api_fields: list[APIField] = [ APIField("tags"), APIField("date"), APIField("authors", serializer=AuthorSerializer(many=True)), APIField("intro"), APIField("body"), ] and when I go to a detail view, I'm able to see the fields e.g.http://127.0.0.1:8000/api/v2/pages/5/ { "id": 5, "meta": { "type": "blog.BlogPage", "detail_url": "http://localhost/api/v2/pages/5/", "html_url": "http://localhost/blog/first-blog-post/", "slug": "first-blog-post", "show_in_menus": false, "seo_title": "", "search_description": "", "first_published_at": "2023-08-20T04:37:17.102729Z", "alias_of": null, "parent": { "id": 4, "meta": { "type": "blog.BlogIndexPage", "detail_url": "http://localhost/api/v2/pages/4/", "html_url": "http://localhost/blog/" }, "title": "Our blog" } }, "title": "First blog post", "tags": [ "react" ], "date": "2023-08-20", "authors": [ { "name": "Brad", "author_image": "/media/original_images/71UHg51kgKL._AC_SY679_.jpg" } ], "intro": "This is a blog post intro", "body": "<p data-block-key=\"q28xv\">Hello World</p>" } However, in the list view, this same page does not contain those fields. I have tried using the fields=* parameter in the url and still, all that shows up is the title e.g http://127.0.0.1:8000/api/v2/pages/ { "meta": { "total_count": 3 }, "items": [ { "id": 3, "meta": { "type": "home.HomePage", "detail_url": "http://localhost/api/v2/pages/3/", "html_url": "http://localhost/", "slug": "home", "first_published_at": "2023-08-20T04:23:02.114917Z" }, "title": "Home" }, { "id": … -
Initilized django form field value not being saved in database
I am trying to create a form that creates a new model instance like below. But, although the instance is created, the fields are empty even though I initilized the form fields using the init method. Here is my forms.py class ChatForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id') super(ChatForm, self).__init__(*args, **kwargs) user = User.objects.get(id=self.user_id) self.fields['user'].initial = user self.fields['var1'].initial = "new string data" class Meta: model = NewModel fields = ( 'var1', 'user', ) Here is my views.py. I am using django forms for backend validation only. def view(request): if request.method == 'POST': user_id = request.POST.get('user_id') form = ChatForm(request.POST, user_id=user_id) if form.is_valid(): form.save() return JsonResponse({'status': 'success'}) else: errors = form.errors.as_json() return JsonResponse({'status': 'error', 'errors': errors}) return HttpResponse('Not a valid request method') My models.py is simple. var1 is a charfield and user is a foreignkey field to a User model. The problem is that the instance is created, but var1 and user is blank for some reason. I hope you can help me with this, and leave any comments below. -
how to use apache cordova in front-end with django in backend
i wanna turn my django e-commerce website to mobile app using apache cordova what it is the method to do it, i wanna really lInk apache cordova to django in order to have mobile e-commerce web app. so, i wanna know if there exist api or a method to do that , my main purpose it is to have django e-commerce website and mobile e-commerce app wchich work together -
Get date in seconds in Python with lambda
I use the following code to get the time in seconds NowS = lambda : round(datetime.now().timestamp()) class api_REMITTANCE_(APIView): Now_ = NowS() def post(self,request): return_serial = {"status_" : "OK_","time":self.Now_}` But surprisingly, when I call again a minute later, it returns the previous time -
i cant understand why i am getting this error on django, help im a new programmer learning django from a tutorial and getting this error idk why?
enter image description here i tried to print "hello world" using django templates watching a tutorial of this person - https://www.youtube.com/watch?v=GNlIe5zvBeQ&list=PLsyeobzWxl7r2ukVgTqIQcl-1T0C2mzau&index=5 And im still getting error even though i did what he said idk why?? pls help im new programmer and i cant solve this problem no matter what pls help your fellow junior developer in this bug -
How do i get the seal_ids that have a manytomany field passed to a form before a user creates a dispatch
i have two models a Seal model and a Dispatch model, where there is a seal_id field that has a manytomany relationship with Seal model. I want to only list seal_ids on the modelform where a dispatch seal_location_status="Received" and station_from = request.user.station. here are my models class Seal(models.Model): s_id = models.AutoField(primary_key=True) # Auto-generated unique ID seal_no = models.CharField(max_length=12, unique=True) imei = models.CharField(max_length=15, unique=True) seal_type = models.ForeignKey(SealType,to_field='name', on_delete=models.SET_NULL, null=True) class Dispatch(models.Model): STATUS_CHOICES=( ('Dispatched','Dispatched'), ('Received','Received') ) dispatch_id = UniqueIDGeneratorField() seal_id = models.ManyToManyField(Seal,related_name='seals') # Change to CharField with appropriate max_length # seal_type = models.ForeignKey(SealType,to_field='name', on_delete=models.SET_NULL, null=True) handler = models.CharField(max_length=100) station_from = models.ForeignKey(Station, related_name='dispatches_from', on_delete=models.CASCADE) station_to = models.ForeignKey(Station, related_name='dispatches_to', on_delete=models.CASCADE) dispatched_by = models.ForeignKey(CustomUser,on_delete=models.CASCADE,null=True) seal_location_status = models.CharField(max_length=20, choices=STATUS_CHOICES) here is my modelform class DispatchForm(forms.ModelForm): class Meta: model = Dispatch exclude = ['dispatched_by','station_from' ] fields = ('seal_id','handler','station_to','seal_location_status') widgets = { 'seal_id': forms.CheckboxSelectMultiple } -
How do I authenticate only particular users into using the site?
I want the users, who have the email, that has the domain name '@example.com', to be able to use the buttons, that directs them to different url patterns. To carry out the above operation, I have created the following in my templates. Here is code snippet of my template {% if user.is_authenticated %} <a href="{% url 'quizlist' %}" class="btn btn-secondary btn-lg">Quizzes</a> <a href="{% url 'profile' %}" class="btn btn-secondary btn-lg">Profile</a> <a href="{% url 'logout' %}" class="btn btn-secondary btn-lg mr-2">Log Out</a> {% else %} <div class="d-flex justify-content-center"> <a href="{% url 'register' %}" class="btn btn-primary btn-lg mr-2">Register</a> <a href="{% url 'login' %}" class="btn btn-secondary btn-lg">Log In</a> </div> {% endif %} But this authenticates all logged in users and not only the users with a particular domain name. So any thoughts on how to do this? -
How to do django form backend validation for user inputs
I am NOT trying to use Django Form for rendering, but only for backend validation. I heard that doing backend validation increases security and santizes the user inputs, since hackers could inject harmful codes through the form inputs to accesss the database. This is my current code for a chat app: views.py def send(request): var1 = request.POST['var1'] user_id= request.POST['user_id'] main_user = User.objects.get(id=user_id) new_instance = ModelName.objects.create(var1=var1, user=main_user) new_instance.save() # Below is the alert message in ajax in template. return HttpResponse('Message sent successfully') html ... <form id="post-form"> {% csrf_token %} <input type="hidden" name="user_id" id="user_id" value="{{user_id}}"/> <input type="text" name="var1" id="var1" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/send/', data:{ user_id:$('#user_id').val(), var1:$('#var1').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function(data){ // alert(data) } }); document.getElementById('var1').value = '' }); </script> </html> However, I am thinking about changing this to include django backend validation. I am thinking that the structure should be something like below, but I am not sure. views.py def send(request): user_id= request.POST['user_id'] main_user = User.objects.get(id=user_id) if request.method =='POST': form = ChatForm(request.POST, user=main_user) if form.is_valid(): form.save() return HttpResponse('successful.') return HttpResponse('Not successful') forms.py class ChatForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.main_user = kwargs.pop('user') super(ChatForm, self).__init__(*args, **kwargs) # Some kind of code to automatically … -
purpose of argument name="home" in django path definatioin
I write a path in Django with an argument name and with its value home to display a simple HttpResponse. My question is why we use name="home" while writing a path. path('',views.home, name='home'), Kindly reason??? path('',views.home, name='home'), Kindly reason??? -
oracle storage with django
I'm having trouble using oracle object storage as a static file store using django-storages. # Storage settings STORAGES = {"staticfiles": {"BACKEND": "storages.backends.s3boto3.S3StaticStorage"}} ORACLE_BUCKET_NAME = "crescendo-bucket" ORACLE_NAMESPACE = "ax0elu5q0bbn" ORACLE_REGION = "us-phoenix-1" AWS_ACCESS_KEY_ID = "<:)>" AWS_SECRET_ACCESS_KEY = "<:)>" AWS_STORAGE_BUCKET_NAME = ORACLE_BUCKET_NAME AWS_S3_CUSTOM_DOMAIN = ( f"{ORACLE_NAMESPACE}.compat.objectstorage.{ORACLE_REGION}.oraclecloud.com" ) AWS_S3_ENDPOINT_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_DEFAULT_ACL = "" # STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/{ORACLE_BUCKET_NAME}/" I have entered this setting and when I enter the `collectstatic` command, I get the error `botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://ax0elu5q0bbn.compat.objectstorage.us-phoenix-1.oraclecloud.com/crescendo-bucket/admin/css/rtl.css"`. https://docs.oracle.com/en-us/iaas/Content/Object/Tasks/s3compatibleapi.htm Cannot set up Oracle bucket for django static files storage Using this link as a guide, I think I have the right URL configured, but when I make the bucket public and access it as an admin user, the browser still shows a "connection refused" message. I'm pretty sure I've configured that URL (AWS_S3_ENDPOINT_URL in settings.py) correctly, but it's preventing me from making API calls and accessing the browser. Please let me know what I'm doing wrong. -
Nginx replaces media paths
My image is not displayed on the remote server. Nginx replaced my-dns.com adress to 127.0.0.1 and picture is not displayed. if i replace 127.0.0.1:7000/media/... to my-dns.com/media/... the picture opens Here's my nginx media settings: server { listen 80; client_max_body_size 50M; server_tokens off; location /media/ { alias /media/; } location /back_static/ { alias /static/; } } It would seems that a static should not work, but it works. They have very similar path but media didn't work and static work. My django constants MEDIA_URL = "media/" MEDIA_ROOT = "/media/" STATIC_URL = "back_static/" STATIC_ROOT = BASE_DIR / "collected_static" What should i do to replase 127.0.0.1 to my-dns.com? -
Django how to add a model instance with a foreign key field if the referenced model instance does not exist
I am working with a legacy database within an AS400 system connected to my Django project. I am trying to configure my models in the best way possible and set up relationships correctly but I am running into an issue related to adding an instance of a model that has a foreign key field to another model but the instance of that model might not exist yet. Here is an example, consider the following two models: class CLIENTPF(models.Model): id = models.BigAutoField(db_column='CLNTID', primary_key=True) fname = models.CharField(db_column='CLNTFNAME', max_length=30, unique=True, null=True) lname = models.CharField(db_column='CLNTLNAME', max_length=30) dob = models.CharField(db_column='CLNTDOB', max_length=10) class Meta: managed = False db_table = '"XPFLORIS"."CLIENTPF"' class MOVIEPF(models.Model): movie_name = models.CharField(db_column='MOVNAME', max_length=30, primary_key=True) star_fname = models.ForeignKey(CLIENTPF, to_field='fname', on_delete=models.PROTECT, db_column='STARACTF', max_length=30) star_lname = models.CharField(db_column='STARACTL', max_length=30) genere = models.CharField(db_column='GENERE', max_length=30) release_date = models.CharField(db_column='RELDATE', max_length=10) class Meta: managed = False db_table = '"XPFLORIS"."MOVIEPF"' The "star_fname" field in MOVIEPF is a Foreign key to the "fname" field in CLIENTPF. So if I wanted to add an instance to the MOVIEPF table in my views.py with the following ORM I would get an error since "Rowan" is just a string and not an instance of the CLIENTPF model. new_movie = MOVIEPF(movie_name="Johnny English", star_fname="Rowan", star_lname="Atkinson", genere="Comedy", release_date="02/12/2003") new_movie.save() … -
Django + TelegramClient RuntimeError: There is no current event loop in thread 'Thread-1'
I'm trying to make a parser like a web application. Where, from the POST form, the username of the telegram group will be sent with a request, parsing the data of users of this group and saving to a file. I transferred this parser to Celery, in view I call this function and I give the name of the group as a parameter and request. I get this error RuntimeError: There is no current event loop in thread 'Thread-1'. If run without Django, the code works fine My tasks.py from telethon.sync import TelegramClient import csv from celery import shared_task @shared_task def main(url): api_id = ******** api_hash = '********' phone = '******' client = TelegramClient(phone, api_id, api_hash) client.connect() target_group = client.get_entity(url) print('Fetching Members...') all_participants = [] all_participants = client.get_participants(target_group, aggressive=True) print('Saving In file...') with open("members.csv","w",encoding='UTF-8') as f: writer = csv.writer(f,delimiter=",",lineterminator="\n") writer.writerow(['username','user id', 'access hash','name','group', 'group id']) for user in all_participants: if user.username: username= user.username else: username= "" if user.first_name: first_name= user.first_name else: first_name= "" if user.last_name: last_name= user.last_name else: last_name= "" name= (first_name + ' ' + last_name).strip() writer.writerow([username ,user.id, user.access_hash, name, target_group.title, target_group.id]) print('Members scraped successfully.') My view.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from .tasks import main … -
add attrs to a relationship model field on django forms
hi all need help adding some style to a relationship field on django form. have this models.py class Empresa(models.Model): idEmpresa= models.CharField(unique=True, max_length=10) nombreEmpresa = models.CharField(max_length=50, unique=True) class Cliente(models.Model): idCliente = models.CharField(unique=True, max_length=9) nombreCliente = models.CharField(max_length=64) ... empresa= models.ForeignKey(Empresa, on_delete=models.CASCADE)` forms.py class ClienteForm(forms.ModelForm) class Meta: model = Cliente fields = '__all__' widgets = { 'idCliente': forms.TextInput(attrs={'class': 'form-control mb-3', 'id': 'idCliente', 'name': 'idCliente', 'type': 'text'}), 'nombreCliente': forms.TextInput(attrs={'class': 'form-control mb-3', 'id': 'nombreCliente', 'name': 'nombreCliente', 'type': 'text', 'placeholder': 'Ingrese nombre y apellidos', 'maxlength': '64'}), } and I need to add the attrs to the field empresa on my ClienteForm... try this 'empresa' : forms.ModelChoiceField(queryset=empresa, widget=('class' : 'form-select')), and this def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["empresa"].widget.attrs.update({"class": "form-select", 'id' : 'empresasss'}) I don't know what I am doing wrong, have read the documentation several times but I'm stuck, real stuck at this. help me please!!! -
I Want To Save The Data In My Database Depending On The Catgory Of Data Chosen by User Like I Have 4 Lisiting
I Want To Save The Data In My Database Depending On The Catgory Of Data Chosen by User Like I Have 4 Lisitings Like APparetements, Food And Life, Car And Travelling if User Selects Appartements Then Area, location Fields Are Showed An getiing Data And Saved Data Else Hidden and Disabled For Other Fields Like Food And Life, Car And Travellig. MY COde Of MyListing.html {% extends 'home.html' %} {% load static %} {% block content %} <div class="page-heading"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="top-text header-text"> <h6>Add Plots In Your Listing</h6> <h2>If You Want To Buy The Plot Then Add It In Your Listing</h2> </div> </div> </div> </div> </div> <div class="contact-page"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="inner-content"> <div class="row"> <div class="col-lg-6 align-self-center"> <form id="contact" action="" method="POST" enctype="multipart/form-data"> <div class="row"> {% csrf_token %} <div class="col-lg-12"> <label for="">Listing Type</label> {{ form.listing_type }} <label for="" >Area</label> {{ form.area }} <label for="">Location</label> {{ form.location }} <label for="">Price</label> {{ form.price }} <label for="">Title</label> {{ form.title }} <label for="">Upload An Image</label> {{ form.image }} </div> <div class="col-lg-12"> <fieldset> <button type="submit" id="form-submit" class="main-button "><i class="fa fa-paper-plane"></i>Add Your Listing!</button> </fieldset> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() … -
Django template language checking the value
I need to check if value in m2mfield of django and then get it selected if it is <option value="Clothes" {% if "Clothes" in product.categories.all %} selected {% endif %}>Clothes</option> i tried this but seems like it doesnt work the view function def update_page(request, param): if request.method == "POST": product = Product.objects.get(pk=param) print(request.POST.getlist('categories')) data = request.POST title = data.get('title') categories = data.getlist('categories') price = data.get('price') description = data.get('description') rating = data.get('rating') product.title = title product.categories.clear() for i in categories: product.categories.add(Category.objects.get(title=i)) print(i) product.price = price product.description = description product.rating = rating product.save() # if data.get('test'): # print("loh") # else: # print("not found") return redirect('product', param=param) else: product = Product.objects.get(pk=param) context = { "product": product } return render(request, "update.html", context=context) -
Django translate tag with dynamic url
I would like to translate a sentence with a url inside. I tried the following: First option yields an error as it is not possible to have another '{%' inside the blocktrans. {% blocktrans %} <p><a href="{% url 'register' %}"><strong>Register</strong></a> and be happy</p> {% endblocktrans %} Second is based on this answer, but it does not work either. {% blocktrans with link={% url 'register' %} %} <p><a href="{{ link }}"><strong>Register</strong></a> and be happy</p> {% endblocktrans %} Any idea how to make it work? -
I can't loaddata from backup.json, in django
I hosted a site and around 200 persons data is stored in that, I took backup of it to test in my modified site, I mean I am developing that site more, But when I loaddata then it gives errors like: django.db.utils.IntegrityError: Problem installing fixture 'C:\Users\siddh\Projects\Django_Projects\XtraROMs\dump.json': Could not load app.UserProfile(pk=1): UNIQUE constraint failed: app_userprofile.user_id I tried many things like deleting the database and migrations and many other things on stackoverflow, github and chatgpt, But It is not loading, even I tried to use same models as my hosted site but it gives errors These are models in my running project: class CustomROM(models.Model): class CustomMOD(models.Model): class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) is_authorized = models.BooleanField(default=False) class Contact(models.Model): class Comment(models.Model): These are models in my running project: (It is same as my running project except some extra attributes in my UserProfile model) class CustomROM(models.Model): class CustomMOD(models.Model): class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) is_authorized = models.BooleanField(default=False) profile_picture = models.ImageField(upload_to='profile_pictures/', blank=True) bio = models.TextField(null=True, blank=True) google_username = models.CharField(max_length=100, blank=True) local_username = models.CharField(max_length=100, blank=True) email = models.EmailField(blank=True) class Contact(models.Model): class Comment(models.Model): Also, I used django allauth feature in modified site but it is not related to this i guess I already used these commands … -
Django marshmallow validate error message not translating
I have defined a shema in django project. gross_weight = fields.Decimal(required=True, validate=validate.Range(min=0, max=9999.99, error=translation.ugettext(INVALID_RANGE_DURATION).format("0", "9999.99"))) Here the error message is not getting translated But the same thing is getting translated when i call in pre_load or post load functions. My guess is that the format is putting value first and then the translation is happening. .po file msgid "Value must be between {} and {}" msgstr "आज भारी बारिश का पूर्वानुमान{} है {}" -
Django (RF) : Allow child comments (MPTT model) to be created within same Post as parent comment
I have a Post model and Comment model. The second one based on MPTT model to achive comments arrangement in a tree format. Everything works but the problem is to restrict new child Comment to be linked with other then parent Post on creation. Example: Let's say I have Post objects with ID = 1 and 2. I have a parent Comment object with ID = 10 linked with Post ID = 1 (defined above). Now I can create a new child Comment object, wire it with a parent Comment but Post ID may be passed equal to 2 which is not the same as parent's one. And as a result: related comments devided in a separate Post objects. I can just make some validation like (schema without python syntax): if new_comment.post_id != new_comment.parent__post_id: return Response({"error": "Child comment must be linked with the same post as parent"}) But is there any Django way to do this to make this validation work in django-admin as well? For example when I create a Comment object and choose a parent in a dropdown section then only Post related to parent Comment will be available in a dropdown section? My code : Models: class …