Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django password reset not sending mail
when i am resetting my password in django everything goes well but i am not getting any mail . urls.py path('password_reset/',auth_views.PasswordResetView.as_view(success_url=reverse_lazy('blogapp:password_reset_done')),name='password_reset'), path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(),name='password_reset_done'), path('password_reset/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='blogapp/password_reset_confirm.html',success_url=reverse_lazy('blogapp:password_reset_complete')),name='password_reset_confirm'), path('reset/done/',auth_views.PasswordResetCompleteView.as_view(),name='password_reset_complete'), ] -
Django doesn't use atomic transactions by default?
I read the django documentation about Database transactions. Then, this section says: Django’s default behavior is to run in autocommit mode. Each query is immediately committed to the database, unless a transaction is active. So, as the section says, Django doesn't use atomic transactions by default? So, if Django doesn't use atomic transactions by default, when updating data in Django Admin Panel, there can be Race Condition right? -
How to solve refused to connect problem in Kibana?
I wrote a function for creating charts in Kibana. Firstly, I installed Kibana and Elasticsearch on my local PC. I am sending a request for creating data and charts and taking the embedded iframe code from there. In this scenario everything is okay. I could create charts clearly and my functions are working great. I could show charts on my page. Then I installed my project, kibana and elastic search on a server. And I get this error inside of the iframe tag: 2**...**6 refused to connect. What can be the problem? part of my functions elasticsearch_address= 'http://localhost:9200' self.es = Elasticsearch([elasticsearch_address], use_ssl=False, verify_certs=False, ssl_show_warn=False, send_get_body_as='POST', ) It works fine. I can get and post requests to this address. So, I think the problem is in Kibana. part of my functions url3 = "http://localhost:5601/api/saved_obj..." headers3 = {"Accept-Language": "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3", "Accept-Encoding": "gzip, deflate", "Referer": "http://localhost:5601/app/management/kibana/objects", "Content-Type": "multipart/form-data; boundary=-..." "Origin": "http://localhost:5601", "kbn-xsrf": "true", "Sec- Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin"} data3 = "--...." r3 = requests.post(url3, headers=headers3, data=data3) destinationid = re.findall(r"\"destinationId\":\"(.*?)\"", r3.text) destinationid = destinationid[-1] request_text = "http://localhost:5601/app/dashboards#..." user = request.user user.iframe = request_text.replace("localhost", "2**.***.***.**") user.save() in the part of user.iframe, I get the iframe code. I change it with the server's IP number … -
Django - How to make a current object "ImageField attribute" as the pre-defined value in a Update_Object view?
I'm creating an update view using django-form for updating one of my objects that have the following fields: class Object(models.Model): name = models.CharField(max_length=40) logo = models.ImageField(upload_to='object_logo/') text_1 = models.TextField() text_2 = models.TextField() So, i have created the following form in forms.py: class ObjectForm(forms.ModelForm): class Meta: model = Object fields = [ 'name', 'logo', 'text_1', 'text_2', ] labels = { 'name': 'Name', 'logo': 'Logo', 'text_1': 'Text 1', 'text_2': 'Text 2', } and defined the following view called update_object: def update_object(request, value): object = get_object_or_404(Object, pk=value) if request.method == "POST": form = ObjectForm(request.POST, request.FILES) if form.is_valid(): object.name = form.cleaned_data['name'] object.logo = form.cleaned_data['logo'] object.text_1 = form.cleaned_data['text_1'] object.text_2 = form.cleaned_data['text_2'] object.save() return HttpResponseRedirect(reverse('myApp:detail_object', args=(value, ))) else: form = ObjectForm( initial={ 'name': object.name, 'logo': object.logo, 'text_1': object.text_1, 'text_2': object.text_2, } ) context = {'object': object, 'form': form} return render(request, 'myApp/update_object.html', context) My problem is: even with an "initial" value stetted up for logo, i have to select an image every time i will update my object (otherwise i receive the update_object page with the message "This field is required"). Is there a way to make the current object.logo as the pre-defined value of the input in my ObjectForm in the update_object view? I've already tried … -
ImportError: cannot import name 'url' from 'django.conf.urls'
ImportError: cannot import name 'url' from 'django.conf.urls' (/home/chams/pfe_project/CarApp/venv/lib/python3.8/site-packages/django/conf/urls/_init_.py) I can't find any mistakes in my code ! -
add expire time for validation and verification in Djoser
I'm using Django==4.0.3 ,djangorestframework==3.13.1 and djangorestframework-simplejwt==5.1.0 and djoser==2.1.0 I have used djoser to authenticate, and all works fine. how can add expiration datetime for validation and verification link in Djoser ? any idea ? -
Error when running “virtualenv <name>” command
I’ve tried a lot of things but it’s not working, it’s hitting me up with a prompt msg “‘virtualenv’ is not recognized as an internal or external command “ Any solutions? -
Django error cannot import name 'views' from 'device' (unknown location)
I can create django project to run in server without error. After that, I upload project from my computer to replace same project name in the server. Then, it show error like this. Exception Type: ImportError at / Exception Value: cannot import name 'views' from 'device' (unknown location) In urls.py still import views like this code. from django.contrib import admin from django.urls import path from device import views from django.conf.urls.static import static from django.conf import settings It have no problem in my computer but it have problem when upload to server. where I should to check path? How to fix it? -
Revalidate on-demand a Next.js site from Django model's save method
I have a next.js site deployed to Vercel, that fetches data from an API provided by Django. Next.js has this new feature (Incremental Static Regeneration On-Demand) where you can rebuild a specific page without need to rebuild the entire site with an url like this: https://<my-site.com>/api/revalidate?secret=my-token I need the next.js site rebuild some pages when the database changes, so it shows the new data, and i tried to make a request (with requests package) in the save method like this: def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>") It seems to work when it trigger that url from my browser, but it doesn't work when i trigger it from Django. The response of this Response object (r) is a 200 Status Code, as expected, with {"revalidated":true} (r.text), but it doesn't update the site anyways. How can i implement this? -
Build folder ./build does not exist
I was trying to deploy my django project using render and I am getting this error that build does not exists.. I have no idea how to fix this. Can anyone help? I tried to look for any solutions on the internet but could not find any...I don't know if I typed any code wrong or am I missing some commands. -
Manager isn't available auuth.User has been swapped
As a precursor to asking, I have already looked at a few similar questions and answers. I am trying to extend my user class to include other fields and then pass down these extra fields as payload on my access_token. I get this error message when I try to run makemigrations/migrate or run my code AttributeError: Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomerUser' This is what I have in models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser # #extending user model to include class CustomerUser(AbstractUser): city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) serializers.py: from django.contrib.auth import get_user_model User = get_user_model() class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = User.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.country token['city'] = user.city token['bio'] = user.bio return token class UserSerializer(serializers.ModelSerializer): class Meta: model = User … -
Adding extended user class fields to payload data in access token
I extended my user class to include other fields (city, country, bio). I would like to pass these down along to customizing my JWT access_token to include these fields as a payload in addition to username. This is what I have in my models.py (extending my user class): from django.db import models from django.contrib.auth.models import User #extending user model to include class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=50,blank=True) country = models.CharField(max_length=50, blank=True) bio = models.CharField(max_length=500, blank=True) def __str__(self): return self.user.username serializers.py: #changed from serializers.HyperLinked to ModelSerializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = Profile #removed url from fields fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country', 'bio'] extra_kwargs = { 'password': {'write_only': True}, } def create(self,validated_data): user = Profile.objects.create_user( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], city=validated_data['city'], country=validated_data['country'], bio=validated_data['bio'], email=validated_data['email']) user.set_password(validated_data['password']) user.save() return user #customizing the payload we get from our access tokens class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['first_name'] = user.first_name token['last_name'] = user.last_name token['country'] = user.profile.country token['city'] = user.profile.city token['bio'] = user.profile.bio return token and api.py #Register API class RegisterApi(generics.GenericAPIView): serializer_class = RegisterSerializer #remove this if it doesn't work authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) … -
How the through model object is created in django?
I want to overwrite a creation of M2M through model object. I thought that overwriting save method will be sufficient, but it appears that after saving admin form, the method is not called. I am having a hard time finding how this object is created. Here is the code snippet class ProductVariantToAttributeValue(models.Model): product_variant = models.ForeignKey(ProductVariant, on_delete=models.CASCADE) attribute_value = models.ForeignKey(AttributeValue, on_delete=models.CASCADE) attribute = models.ForeignKey( Attribute, on_delete=models.CASCADE, null=True, blank=True ) class Meta: db_table = "productvariants_to_attributevalues" unique_together = [("product_variant", "attribute")] verbose_name_plural = "Product Variants To Attribute Values" def save(self, **kwargs): self.attribute = self.attribute_value.attribute super().save(**kwargs) -
DRF Framework - allow User CRUD on another Users related field if they are in relationship through another model
I have a model Application that has fields applicant = ForeignKey('User'...) and coapplicant = ForeignKey('User'...). There is also a model Income that has field user = ForeignKey('User'.... I want to allow User A to create, edit, delete Income objects of User B if A and B are in a relationship through Application. That means: User A can CRUD Incomes of User B and vice-versa if there is such Application object where A is an applicant and B co-applicant or A is a co-applicant and B applicant. Do you know how to make that work? -
Django multiple image upload like ecommerce website
I want to let the user upload multiple images per model as Instagram or Amazon does. Till now I have title and featured_images fields in my model but the "multiple" attribute seems not to work. Thanks models.py class Project(models.Model): title = models.CharField(max_length=200) featured_images = models.ImageField(null=True, blank=True) forms.py class ProjectForm(ModelForm): class Meta: featured_images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) model = Project fields = ['title', 'featured_images'] views.py def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST, request.FILES.getlist('featured_images')) if form.is_valid(): project = form.save(commit=False) project.save() context = {'form':form} return render(request, 'projects/project_form.html', context) project_form.html <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input type="submit" name="" id=""> </form> -
How to fetch integer values from the Django objects?
I already created integerField for saving data in the model. But showing the bellow error. How can I convert a string list into an integer list? Django Model: class Frontend_Rating(models.Model): Rating = models.IntegerField( null=True) Views: #index def index(request): frontend_all_ratings = Frontend_Rating.objects.all() number_of_frontend_rating = frontend_all_ratings.count() frontend_rating_list = [] total_ratings = 0 for frontend_rating_item in frontend_all_ratings: frontend_rating = int(frontend_rating_item.Rating) frontend_rating_list.append(frontend_rating) total_ratings = total_ratings+frontend_rating_list[frontend_rating_item] context = { "number_of_frontend_rating":number_of_frontend_rating, "frontend_rating_list":frontend_rating_list, "total_ratings":total_ratings } return render(request,'0_index.html',context) Erorr: TypeError at / list indices must be integers or slices, not Frontend_Rating Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.3 Exception Type: TypeError Exception Value: list indices must be integers or slices, not Frontend_Rating Exception Location: D:\1_WebDevelopment\Business_Website\business_app\views.py, line 33, in index Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 -
Catch errors in password validation in Django
i have a problem. I'm trying to catch errors from password validation in Django, but I don't know how to do it. Password validation is called in forms.py, and form.isValid() is called in views.py I'd like to know exactly what errors has been found in the password validation called in forms.py, so i can do use an if to launch a bootstrap warning chosen by me. Here is the code: forms.py class RegistrationForm(forms.Form): username = forms.CharField(label="Inserisci username", max_length=50) password = forms.CharField(label="Inserisci password", widget=forms.PasswordInput) repeatPassword = forms.CharField(label="Ripeti password", widget=forms.PasswordInput) def clean_username(self): username = self.cleaned_data['username'] if User.objects.filter(username=username).exists(): raise forms.ValidationError('Nome utente già in uso') return username def clean_password(self): username = self.cleaned_data['username'] password = self.cleaned_data['password'] validate_password(password, username) return password def clean_password2(self): password = self.cleaned_data['password'] repeatPassword = self.cleaned_data['repeatPassword'] if password != repeatPassword: raise forms.ValidationError('Le password devono corrispondere') return password views.py def registration(request): if request.method == "POST": registrationForm = RegistrationForm(request.POST) if registrationForm.is_valid(): # Creazione utente username = RegistrationForm.cleaned_data['username'] password = RegistrationForm.cleaned_data['password'] playerStatistics = Statistics(health=randint(90, 110), armor=0, strength=randint(5, 15), speed=randint(15, 25), dexterity=randint(15, 25)) equipmentStatistics = Statistics(health=0, armor=0, strength=0, speed=0, dexterity=0) playerStatistics.save() equipmentStatistics.save() equipment = Equipment(statistics=equipmentStatistics) equipment.save() inventory = Inventory() inventory.save() newPlayer = Player(username=username, password=password, statistics=playerStatistics, equipment=equipment, inventory=inventory) newPlayer.save() return render(request, "playerHome.html") else: return HttpResponse("Errore nell'inserimento dei dati") … -
How I get all products into subcategories when I filter through the parent category in django rest
When I filter by subcategories, only those products that are directly related to this category are displayed, and when I filter, the parent category returns an empty one, but in fact there is a subcategory on this parent category and there are products on this category. I wanted to make sure that all products related to the parent categories were returned. in views.py class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductsSerializer serializers = { 'create': ProductsSerializer, 'list': ProductDetailSerializer, 'retrieve': ProductDetailSerializer, 'default': ProductsSerializer, 'add_favorite': FavouriteSerializer } filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = { 'category__title': ["in",] } in models.py class Category(MPTTModel): """Categorizing posts""" title = models.CharField(max_length=128, verbose_name="Title", unique=True, default=None) description = models.TextField(verbose_name="Description", null=True, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['title'] class Product(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey( Category, on_delete=models.PROTECT, related_name="products", verbose_name="Category of a product" ) in screen i have 2 category Parent and Child in screen when i filter by Child category in screen when i filter by Parent category and its response is empty how can I fix this and get all the products from the subcategories through the parent category filter -
Why is the Django template file not updating value from the context?
(I am a beginner in Django) I am following along a tutorial in Django where we can dynamically pass some variable to a template file from associated function in views.py When I am running the code for the first time, it works fine, but when I change the values within the context, the template does not update with the new values even when I refresh it Here is my views.py code - from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # return HttpResponse('<h1>Hey, welcome</h1>') # we can dynamically send data to our index.html file as follows - context={ 'u_name': 'Ankit', 'u_age': 25, 'u_nationality': 'Indian', } return render(request,'index.html',context) Here is my template index.html - <h1> How are you doing today {{u_name}} <br>You are {{u_age}} years old<br>Your nationality is {{u_nationality}} </h1> settings.py has been correctly set as well - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,'templates'], Here is my output - does not take the values from the context Would be glad if someone could point out what error I am making. Thanks in advance -
How to retrieve data from html form and pass it into my database as an sql query in django
i am trying to make use of django to retrieve data from my sign up form and pass it into my database in pgadmin 4 as a query. I got error and doesnt know how to go about doing it. This is my code which i tried to use pymysql. Thanks in advance def booknow(request): c = pymysql.connect(host='localhost', user='postgres', password='pw', db='users') cur = c.cursor() if request.method == 'POST': display_name = request.POST.get['your-name'] email = request.POST.get['your-email'] age = request.POST.get['your-age'] phone_number = request.POST.get['phone-number'] gender = request.POST.get['your-gender'] vaccination_status = request.POST.get['your-vaccination'] password = request.POST.get['your-password'] insert_query = "INSERT INTO users (display_name, email, age, phone_number, gender, vaccination_status, password) VALUES ('%s','%s','%s','%s','%s','%s','%s');" % (display_name,email,age,phone_number,gender,vaccination_status,password) c = connection.cursor() c.execute(insert_query) return render(request, 'booknow.html') -
Reverse for 'temp1' with arguments '('',)' not found. 1 pattern(s) tried: ['userinput/(?P<id>[0-9]+)/\\Z']
I just want to retrieve data dynamically. urls.py I think there is something error in views.py or urls.py from django.urls import path from . import views urlpatterns = [ path("", views.home, name='home'), path("userinput/", views.template, name='template'), path("userinput/<int:id>/", views.temp1, name='temp1'), ] views.py from django.shortcuts import render, HttpResponseRedirect from home.models import UserDetail # Create your views here. def template(request): if request.method == 'POST': nm = request.POST['name'] eml = request.POST['email'] adrs = request.POST['address'] data = UserDetail(name=nm, email=eml, address=adrs) data.save() return render(request, 'template.html') def temp1(request, id): userdetail = UserDetail.objects.get(pk=id) return render(request, 'temp1.html', {'userdetail':userdetail}) template.html I think my error is related to views.py or in template.html file {% load static %} {% block css_files %} <link rel="stylesheet" href="{% static '' %}"> {% endblock %} {% block content %} <form id="resume-form" action="" method="POST"> {% csrf_token %} <h1>Enter your details</h1> <div class="generate"> <div class="per"> <h2>Personal details</h2> <div class="a"> <label for="namefields">Your Name</label><br> <input type="text" class="" id="namefields" placeholder="Enter here" name="name"> </div> <div class="a"> <label for="emailfield">Your Email</label><br> <input type="email" class="" id="emailfield" placeholder="Enter here" name="email"> </div> <div class="a"> <label for="addressfield">Your Address</label><br> <textarea id="addressfield" placeholder="Enter here" rows="3" cols="" name="address"></textarea> </div> <div class="generatebtn"> <a href="{% url 'temp1' userdetail.id %}"><button type="Submit">Submit</button></a> </div> </form> {% endblock %} can anyone say why it shows "NoReverseMatch at /userinput/" … -
Does select_for_update() work if AUTOCOMMIT is set to False in Django Rest-Framework
I am writing a celery task which would get invoked if a row is being inserted into a table. This task is being executed in a transaction and the task also locks the certain rows of several tables. Now lets assume this task is being executed when AUTOCOMMIT & ATOMIC_REQUESTS is enabled. This is how it looks like - @app.task @transaction.atomic def celery_task(a, b): result = Orders.objects.filter(filed = "Value") # here the result might have 10 of records but I just need few of them based on a very # specific business logic. # so I pick those which are required and should be locked. rows_to_lock = [result[0], result[1]] # has only ids of the rows in this list # Now to put on the records which are in - rows_to_lock result = Orders.objects.select_for_update().filter(id__in=rows_to_lock) ... ... Now when this celery task is being invoked twice with two different arguments and at the same time and if the resultant rows of orders are exactly same then I have noticed that the locks to update the records aren't working. Does the decorator @transaction.atomic works with the current database configurations that I have? Will I be able to solve the issue if I … -
Django - How to go back to previous url
I have multiple todo lists on different pages in an app written in python. I dont want to use delete and update functions over and over again. I want to use one for all pages. In update and delete functions, I can redirect to a certain page after code execution. But its not dynamic. How can I make it dynamic? def updateTodo(request, pk): task = Todo.objects.get(id=pk) form = FormTodo(instance=task) if request.method == 'POST': form = FormTodo(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/page_path') context = {'form':form} return render(request, 'update_task.html', context) What should I write instead of page_path so that it redirects to the page it comes from? I thought going back to the latest page would be an option but guess what? I couldnt do it either. Also, would going back create an error or something? since I'm updating an entry. Any suggestions ? (I saw some options with selenium but it seems to work for chrome or selected browsers only. I'd like to avoid using selenium if there is another way) -
Prevent overwriting existing objects when applying fixture
I have a model representing my application's settings. The settings I define in a fixture. Now, everytime I redeploy the app I also apply the fixture with ./manage.py loaddata settings. The problem I noticed now is that everytime I do this already changed settings get reset as well, it's appearantly deleting the dataset and creating it new. Is there a way to avoid this? settings.yaml: ## Einstellungen - model: preferences.settings pk: agent_name fields: name: Agenten-Name description: Name, welcher dem Kunden im Chat angezeigt wird default: Agent public: true type: text category: 2 - model: preferences.settings pk: greeting fields: name: Begrüßungstext description: Begrüßungstext der dem Kunden angezeigt wird wenn ein Agent Online ist default: Hallo, wie können wir Ihnen helfen? public: true type: textarea category: 2 -
covert txt file into json python django
i have this file of weather data i'm trying to send it through API: view.py: @api_view(['get']) def weatherDataList(request,region,parameter): try: url = 'https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/'+parameter+'/date/'+region+'.txt' print(url,"this is url") r=requests.get(url) data = r.text new_data = data[274:] a=json.loads(new_data) return Response({"message":"Data List","status":True,"data":a},status=status.HTTP_200_OK) except Exception as e: print(e) return Response({"message":str(e),"status":False,"data":{}},status=status.HTTP_400_BAD_REQUEST) i'm not able to format and output the data. what should be the better way to achieve this. output the whole data as json.