Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Unit test exceptions for redis in DRF
I have serializers.py like this for post request import redis redis_client = redis.Redis().json() class MySerializer(serializers.Serializer): ... def validate(self, attrs): ... try: ... except redis.ConnectionError: raise ValidationError("Redis server is down.") except redis.TimeoutError: raise ValidationError("Redis server is slow or unable to respond.") How do i write unit test cases for these two exceptions ? -
Does `cache.set()` use `version=1` by default instead of `version=None` in Django?
If I only set and get David with version=0, then I can get John and David in order as shown below. *I use LocMemCache which is the default cache in Django and I'm learning Django Cache: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=0) print(cache.get("name")) # John print(cache.get("name", version=0)) # David And, if I only set and get David with version=2, then I can get John and David in order as well as shown below: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=2) print(cache.get("name")) # John print(cache.get("name", version=2)) # David But, if I only set and get David with version=1, then I can get David and David in order as shown below so this is because John is set with version=1 by default?: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David", version=1) print(cache.get("name")) # David print(cache.get("name", version=1)) # David In addition, if I set and get John and David without version=1, then I can get David and David in order as well as shown below: from django.core.cache import cache cache.set("name", "John") cache.set("name", "David") print(cache.get("name")) # David print(cache.get("name")) # David I know that the doc shows version=None for cache.set() as shown below: ↓ ↓ Here ↓ ↓ cache.set(key, value, … -
Unused path imported from django.urls
THIS IS THE ERROR Unused path imported from django.urlsPylintW0611:unused-import I don't know how to solve this. iam using vscode django version 4.2.4 Python 3.11.4 clientes/urls.py from django.urls import path urlpatterns = [ ] -
Django hosting providers [closed]
I am searching for a django hosting service provider and I found some hosting service providers which costs a little bit high. Since we are starting a small scale ecommerce startup we cant afford that much pricing they offer Can someone suggest me a hosting service provider that hosts a django application at a cheaper rate? -
mozilla_django_oidc package returning redirect error
Getting the following error while trying to login with keycloak through django application (mozilla_django_oidc). Settings, redirect URI - everything looks fine. After providing the login credentials, it suppose to redirect to the app itself and by that time encountering this error. Any idea? -
Asynchronous tasks in Django
I want to implement a telegram group parser (namely users) into the Django application. The idea is this, from the post request I get the name of the group entered into the form, I pass it to the asynchronous function (which lies in a separate file) and parsing starts. And so at a call of asynchronous function in view, constantly I receive errors. Such as "RuntimeError('The asyncio event loop must not change after connection", "RuntimeError: There is no current event loop in thread 'Thread-1'" etc. Please help me, how would this be better organized? Function for parsing users below: api_id = **** api_hash = '*****' phone = '+******' client = TelegramClient('+********', api_id, api_hash) client.start() async def dump_all_participants(url): """Writes a csv file with information about all channel/chat participants""" offset_user = 0 # member number from which reading starts limit_user = 200 # maximum number of records transferred at one time all_participants = [] # list of all channel members filter_user = ChannelParticipantsSearch('') while True: participants = await client(GetParticipantsRequest(await client.get_entity(url), filter_user, offset_user, limit_user, hash=0)) if not participants.users: break all_participants.extend(participants.users) offset_user += len(participants.users) all_users_details = [] # list of dictionaries with parameters of interest to channel members for participant in all_participants: all_users_details.append({"id": participant.id, …