Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework method in action decorator needs be specified in class http_method_names
DRF version is 3.11.2 I was working on some existing code to add an extra "delete" action to a viewset, but I got 405 Method not allowed, consider the following made up example class UserViewSet(ViewSet): .... queryset = User.objects.all() http_method_names = ['get', 'post'] @action(detail=True, method=['delete']) def delete_profile(self, request, pk=None) Profile.objects.get(user=pk).delete() .... Like I said, when I make a delete method call to /user/123/delete_profile, I get 405 Method not allowed, however, if I add delete to http_method_names as below, it works fine. class UserViewSet(ViewSet): .... queryset = User.objects.all() http_method_names = ['get', 'post', 'delete'] @action(detail=True, method=['delete']) def delete_profile(self, request, pk=None) Profile.objects.get(user=pk).delete() .... But this is not ideal as I don't want to allow "delete" operation on the User, whilst I can overwrite the delete method on the viewset to avoid user being deleted, this is not very elegant. So the question is, is this a bug or by design? -
Page redirection with populated data
I have a django site which has the name records as model in which it stores the data of particular items i have other model task in which we give the information of records(dropdown shows the records related to that particular user) to create the task, so inside the record we are adding a create task button upon clicking it redirects to the task creation page and it should populate the record details in the record dropdown on page how can i achieve this. -
UNIQUE constraint failed: auth_user.username while creating the user using a custom designed form
I am new to django and I am working on student login for examination portal. I am basically passing two forms in my view. One form is for getting the user details and second is for storing details of student. I have used django widget tweak package to load the fields of my forms. My user gets created but at the same time I still get the error- UNIQUE constraint failed: auth_user.username. Here's my model.py class StudentInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.IntegerField(max_length=20, blank=True) branch = models.CharField(max_length=50, blank=True) forms.py class StudentForm(forms.ModelForm) class Meta(): model = User fields = ['username', 'email', 'password'] widgets = { 'password': forms.PasswordInput() } class StudentInfoForm(forms.ModelForm): class Meta(): model = StudentInfo fields = ['mobile','branch'] views.py def register(request): userForm= forms.StudentForm() studentForm=forms.StudentInfoForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentForm(request.POST) studentForm=forms.StudentForm(request.POST) if userForm.is_valid() and studentForm.is_valid(): user=userForm.save() user.is_active = True user.set_password(user.password) messages.success(request,"Student User created Succesfully.") student=studentForm.save(commit=False) student.user=user student.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user) return redirect('login') return render(request,'student_signup.html',context=mydict) html file {% load widget_tweaks %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Student Signup</title> </head> <body> <h1 style="text-align: center; margin-top: 5px;">Student Signup</h1> <div class="container mt-5" style="width: 50%;"> <form … -
django not functioning over HTTPS with apache and mod_wsgi
My requirement is to take my django app over HTTPS. I generated ssl certs with the help of command: openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout ssl_cert.key -out ssl_cert.crt Installed mod_wsgi and mod_ssl and configured them into httpd.conf as: SSLCertificateChainFile "location/to/certs/ssl_cert.cert" WSGIScriptAlias / /location/to/django/app/wsgi.py WSGIPythonHome /root/python3.9 #WSGIPythonPath "/root/python3.9/lib;/root/python3.9/lib/python3.9/site-packages" WSGIPythonPath /location/to/django/app <Directory /location/to/django/app> <Files wsgi.py> Require all granted </Files> </Directory> And restarted apache service. I made changes in settings.py as: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Now on starting Django App with command: HTTPS=on python3 manage.py runserver 8000 It says: Django version 2.2, using settings 'djangoApp.settings' Starting development server at http://localhost:8000/ And its still accessible over http only and if trying to access over HTTPS, it gives error as: This site can’t provide a secure connection from debug.log: You're accessing the development server over HTTPS, but it only supports HTTP. Can somebody please help what I'm missing to configure and how to solve this issue? -
44 connect() failed (111: Connection refused) while connecting to upstream on AWS Elastic Bean
I want to upload my django project to AWS ElasticBean but I have been getting 502 error. I have gone through few videos on youtube but it doesn't seems to work. Here is my project directory ├───.ebextensions ├───.elasticbeanstalk ├───ebdjango ├───.gitattributes ├───.gitignore ├───db.sqlite3 ├───manage.py ├───Pipfile ├───Pipfile.lock └───requirements.txt Here is my django.config setting The tutorials i have been seeing does not explain most of their settings in details and I don't want to just copy and paste code without knowing it's application. option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "awsdjango.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application I dont't have a Procfile, Gunicorn package nor their config in my project. Please let me know in details where i'm not getting it right whether in my settings file or anywhere, just point it out for me. -
Accessing Parent Model from child element of ManyToManyField (Django)
I am having a models.py as follows class Comment(models.Model): auther_name = models.CharField(max_length=20, null=False, blank=False) comment_body = models.TextField(max_length=200, null=False, blank=False) class Post(models.Model): comments = models.ManyToManyField(Comment) So let's say i have a comment Object Instance which's id is 2 and raw content How to get parent post_id which contains this comment?? -
Django object’s attributes becomes a strings if accessed through get first object attribute in queryset
I have a problem that if I access objects attributes in queryset like queryset.0.attr1 it looses it’s type and become a string (Django template processor processes it like a string) Simlple example: I got queryset, that have related set, but when I access this related set first object’s attibute by index.attribute_name it becomes string. If I do the same thing in a loop - this attribute maintain it’s type {% for p in periods %} BECOMES STRINGS accessed via .0.attr {{ p.productions.0.time }} str {{ p.productions.0.ammount }} str MANTAIN TYPES accessed in a loop {% for pp in p.productions %} {{ pp.ammount }} timedelta {{ pp.time }} decimal {% endfor %}{% endfor %} I want somehow to access attributes of first object in queryset with it’s original type -
How to send an email to email@somedomain.com in react frontend when update db column value (django+react+Mysql)
export class Employee extends Component{ constructor(props){ super(props); this.state={ employees:[], modalTitle:"", EmployeeId:0, EmployeeName:"", EmployeeEmail:"", Department:"", DateOfJoining:"", } } refreshList(){ fetch(variables.API_URL+'employee') .then(response=>response.json()) .then(data=>{ this.setState({employees:data}); }); } componentDidMount(){ this.refreshList(); } changeEmployeeName =(e)=>{ this.setState({EmployeeName:e.target.value}); } changeDepartment =(e)=>{ this.setState({Department:e.target.value}); } changeDateOfJoining =(e)=>{ this.setState({DateOfJoining:e.target.value}); } updateClick(){ fetch(variables.API_URL+'employee',{ method:'PUT', headers:{ 'Accept':'application/json', 'Content-Type':'application/json' }, body:JSON.stringify({ EmployeeId:this.state.EmployeeId, EmployeeName:this.state.EmployeeName, EmployeeEmail:this.state.EmployeeEmail, Department:this.state.Department, DateOfJoining:this.state.DateOfJoining, }) }) .then(res=>res.json()) .then((result)=>{ alert(result); this.refreshList(); },(error)=>{ alert('Failed'); }) } render(){ const { employees, modalTitle, EmployeeId, EmployeeName, EmployeeEmail, Department, DateOfJoining, }=this.state; return( {EmployeeId!=0? <button type="button" className="btn btn-primary float-start" onClick={()=>this.updateClick()} >Update</button> :null} ) } } I can update employee details in the above "updateClick()" I am updating "Department" in front end and it is updating. how to trigger an automatic email to "EmployeeEmail" with updated Department value inside "updateClick()" can someone help here please.. I am learning full stack development -
TAG INPUT BOX DJANGO [closed]
How to implement tag input box in Django in which the options or items would only come from the specific table in database? -
cannot convert null to strftime in django
I'm trying to convert the time in 12 hours format where I have few rows with time as NULL. I'm passing it as dictionary. How could I leave that NULL rows and convert others rows with have time Here, what I have tried views.py def GetUserInProgress(userid): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetUserInProgress] @UserId=%s', (userid,)) result_set = cursor.fetchall() data =[] for i in range(len(result_set)): data.append({ 'TaskId':result_set[i][0], 'CreatedOn':result_set[i][13], 'CreatedBy':result_set[i][14], 'StartedOn':result_set[i][15], 'ClosedOn':result_set[i][16], 'Requester':result_set[i][17], 'StartedOnPST':result_set[i][31], 'ClosedOnPST':result_set[i][32], 'ClosedonPST_Final':result_set[i][33].strftime('%d-%m-%Y %I:%M %p'), }) return Response(data) -
How to handle star topology in the Django Rest Framework
I have a Django model like this: class A(models.Model): slug = models.CharField(max_length=20, primary_key=True, unique=True) dataA = models.IntegerField(null=True, blank=True) class B(models.Model): slug= models.OneToOneField(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='b') dataB = models.IntegerField(null=True, blank=True) class C(models.Model): ticker = models.OneToOneField(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='c') dataC = models.IntegerField(null=True, blank=True) class D(models.Model): ticker = models.ForeignKey(A, to_field="slug", db_column="slug", on_delete=models.CASCADE, related_name='d') dataD = models.IntegerField(null=True, blank=True) It's like a star topology. B, C is making an OneToOne relation with A and D is making an OneToMany relation with A. So, I want a Django rest framework to get API in which when the user access the API with the slug field in A. It would retrieve the B, C, D data too in one call. I have written the code like this. class DSerializer(serializers.ModelSerializer): slug = serializers.PrimaryKeyRelatedField(queryset=D.objects.all()) class Meta: model = D fields = ['dataD', 'slug'] class ASerializers(serializers.ModelSerializer): d = DSerializer(many=True, read_only=True) class Meta: model = A fields = ['slug','dataA', 'd'] @api_view(['GET']) def api(request, slug): if request.method == 'GET': try: a= A.objects.prefetch_related('d').get(slug=slug) except A.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializers = ASerializers(a) return Response(serializers.data) My output returns like the below JSON format. { "slug": "term", "dataA": 1, "d": [{ "dataD": 2, "slug": "term" }, { "dataD": 3, "slug": "term" }, { "dataD": 4, … -
ManytoMany query and template rendering from one model to another
I'm new to Django. I had two different questions. I can't query between one of my model and another model (ManyToMany). I can do this with the shell, but I couldn't handle it in the template. I cannot assign a default value from one model to another model's field. For the first question; What I want to do is show values for multiple options. For this, I could make a query similar to this in the shell: room[0].room_type_id.all() But I can't do this in the template. On the other hand, when I want to show it with display, it returns empty. What I want to do here; returning the room types for each room or or accessing the room_cost of the RoomType class and displaying it in the template, repeated for each room type. {% for room in rooms %} <h3 class="card-title pricing-card-title"> {{room.room_type_id_display}} </h3> {% endfor %} My second question is; To set the value from the property of a different model as default in the other model field. That is, to assign the value returned from the total_price of the Booking model to the price field in the Payment model by default. I would appreciate it if anyone … -
PostgreSQL OLD not working in after update statement level trigger
It is working if I do select particular ID like this: BEGIN UPDATE course SET points = (SELECT COALESCE(SUM("lesson"."points"), 0) AS "sum_points" FROM "course" LEFT OUTER JOIN "lesson" ON ("course"."id" = "lesson"."course_id") WHERE "course"."id" = 7) WHERE "course"."id" = 7; RETURN NULL; END; But not working with OLD which is the updating instance. BEGIN UPDATE course SET points = (SELECT COALESCE(SUM("lesson"."points"), 0) AS "sum_points" FROM "course" LEFT OUTER JOIN "lesson" ON ("course"."id" = "lesson"."course_id") WHERE "course"."id" = OLD."course_id") WHERE "course"."id" = OLD."course_id"; RETURN NULL; END; I'm using django-pgtriggers -
According to doctors name (dropdown) and date selected ,change timeslot dropdown using AJAX in django
//This is my book_appoint.html <!DOCTYPE html> <html> <div class="wrapper"> <div class="register-page"> <div class="register-container"> <form id="appointment-form" role="form" method="post" enctype='multipart/form-data'> <!-- SECTION TITLE --> <div class="section-title wow fadeInUp" data-wow-delay="0.4s"> <h2>Book Appointment</h2> </div> {% csrf_token %} <input name="patient_name" value="{{request.user}}" hidden> <div class="wow fadeInUp" data-wow-delay="0.8s"> <div class="col-md-6 col-sm-6"> <label for="qualification">Doctor Name</label> {{ form.doctor_name }} </div> <div class="col-md-6 col-sm-6"> <label for="specialist"> Date</label> {{ form.date }} </div> <div class="col-md-6 col-sm-6"> <label for="location">Time slot </label> {{ form.time_slot }} // want to apply ajax to select available slot only </div> <div class="col-md-12 col-sm-12"> <label for="description"> Description</label> {{ form.description }} <br> <button type="submit" class="submitButton" id="cf-submit" name="submit">Submit Button</button> </div> </div> </form> </div> </div> </div> </html> //This is my view file: def book_appointment(request): if request.method == 'POST': form = BookAppointmentForm(request.POST or None, request.FILES or None) if form.is_valid(): patient_name = request.POST.get('patient_name') patient = form.save(commit=False) patient.patient_name = User.objects.get(username=patient_name) form.save() messages.success(request, 'appointment booked Successfully') return redirect(homepage) else: form = BookAppointmentForm() messages.error(request, 'Please Enter valid Request ') print(form) return render(request, 'book_appointment.html', {'form': form}) else: form = BookAppointmentForm() return render(request, 'book_appointment.html', {'form': form}) //Here is my models: class BookAppointment(models.Model): TIME_SLOT = ( (0, '09:00 - 10:00'), (1, '10:00 - 11:00'), (2, '11:00 - 12:00'), (3, '12:00 - 13:00'), (4, '13:00 - 14:00'), (5, '14:00 - 15:00'), … -
KeyError in pandas dataframe
in the below code my problem is , when word (which s given by user) is searched when is not in the my table column, pop up message appears and says user doesn't exist , but my if searched is not working, does any body have an idea where i'm doing it wrong, please let me know , i'm working in django, pandas def products(request): if request.method == "POST": df = pd.read_csv("media_cdn/media/user_change_history.csv",header=None) searched = request.POST['searched'] context = {} if searched in df.index: data = df.loc[df[0] == searched] #if data in df.index: data = data.transpose() data = data.to_html(classes='table-wrapper') context = {'d': data} else: messages.info(request, 'Username is incorrect') return render(request, 'blog/products.html', context) else: return render(request, 'blog/products.html') in the above code my problem is , when word (should represent a cell in user ID column) (which s given by user) is searched when is not in the my table column, pop up message appears and says user doesn't exist , but my if searched is not working, does any body have an idea where i'm doing it wrong, please let me know , i'm working in Django, pandas -
How to setup elasticsearch with mongodb, mysql and python flask and django?
I am new to Elasticsearch and have no idea about setting up Elasticsearch with MongoDB and python. I am working on a project which is dependent on 2 microservices. First microservice runs on Django which uses MySQL as database and the other microservice runs on flask which uses MongoDB as database. Now I want to setup Elasticsearch with these 2 microservice so that I can make efficient and fast searches in my project. If anyone has any idea about setting up Elasticsearch with MongoDB, MySQL and python, then kindly help me. -
Why my random picture is not getting uploaded in the media path i provided in the model [duplicate]
i want to upload random pictures from a static named folder to my database. These are my files. Please suggest a way. I am stuck here forever. views.py class VerifyOTPView(APIView): permission_classes = (AllowAny,) serializer_class = VerifyOTPSerializer def post(self, request): serializer = VerifyOTPSerializer(data=request.data) mobile = request.data['mobile'] otp_sent = request.data['otp'] #print('one_time_password', one_time) if mobile and otp_sent: old = Profile.objects.filter(mobile = mobile) if old is not None: old = old.first() otp = old.otp if str(otp) == str(otp_sent): serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp, 'name':instance.name, 'username':instance.username, 'logo':instance.logo, 'profile_id': instance.profile_id } return Response(content, status=status.HTTP_201_CREATED) else: return Response({ 'status' : False, 'detail' : 'OTP incorrect, please try again' }) serializers.py class VerifyOTPSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile','otp'] def create(self,validated_data): instance = self.Meta.model(**validated_data) mywords = "123456789" res = "expert@" + str(''.join(random.choices(mywords,k = 6))) path = os.path.join(BASE_DIR, 'static') dir_list = os.listdir(path) random_logo = random.choice(dir_list) instance = self.Meta.model.objects.update_or_create(**validated_data, defaults = dict( username = res, name = instance.mobile, logo = random_logo, profile_id = res))[0] instance.save() return instance models.py class Profile(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) logo = models.ImageField(upload_to ='profile/', blank=True,null = True) profile_id = models.CharField(max_length=200) settings.py ` STATIC_URL = … -
Need to link my existing view to the admin using admin plus module in a table type view
admin.py def my_view(request): pass admin.site.register_view('timelogreport', view=my_view, name='TimeLog Report') views.py def dictfetchall(cursor): "Return all rows from a cursor as a dict" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] @api_view(['GET']) def job(self): cursor = connection.cursor() with open('C:\\Users\\gobs4\\stage\\Project-Management-Tools\\query.sql','r') as inserts: query = inserts.read() cursor.execute(query) return Response(dictfetchall(cursor)) I have used the django admin plus module for creating a view in admin page, But i dont know how to link the above views.py to the admin register view. Can you please help me to do that and i need to show it as table view and not as a json view in the admin, is that possible? -
Changing Request header definition and forwarding to application server
I apologize if my terminology is incorrect. I'm trying to change the name of an incoming header without changing the frontend connection configuration because I have a current server that uses the current value and a new server that has to use a different value on the same physical machine and same IP. Currently getting from front end RequestHeader set X-Y_Z %{SSL_CLIENT_S_DN_CN}e <---- with an underscore in the definition On the new application, using python / django, django framework apparently doesn't accept any headers with an underscore in them. It strips them completely. In apache logs, it shows up and the information is being passed, but not to the application. I set up a reverse proxy with apache in front of the application and tested it out with a dash instead of underscore, and everything works fine. In django, the default for remote user authentication is remote_user everywhere so instead of using X-SSL-Client-CN, I just used Remote-User and that worked. Client authentication from CAC is coming across fine. Is there some method to rewrite the header definition using the reverse proxy in front of the apache server with the application or, within the server if possible? Basically, I want to … -
Django allauth emailverification
I use allauth and want to send a verfication email. ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.ionos.com' EMAIL_HOST_USER = 'info@mydomain.com' EMAIL_HOST_PASSWORD = 'secretpassword' EMAIL_PORT = 587 I use Ionos, the error which shown in browser: SMTPAuthenticationError at /accounts/signup/ (535, b'Authentication credentials invalid') Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.1 Exception Type: SMTPAuthenticationError Exception Value: (535, b'Authentication credentials invalid') The credentials are correct, maybe there's an error with the passwordencoding, or I'm doing it completly wrong. Do I need any smtp client in the django backend? -
File/data recovery
Very specific question. I was storing a copy of my data in the system folder of a package. Made it easier to run from system.file(). Unfortunately, I accidentally reinstalled the package, and my personal files were "deleted" when R reinstalled the package. They vanished after reinstalled. I searched for the files in my system, but only the shortcut of where they used to be are found. Are the copies of my data actually deleted? If not, how can I recover them? -
NoReverseMatch at /auth/password/reset/
I am using dj-rest-auth package to do auth related functions, installed the package and added to installed apps and included it in main url as follows path('auth/', include('dj_rest_auth.urls')), it works for login, logout etc, but when I do password reset it throws the error http://127.0.0.1:8000/auth/password/reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name -
Call property from one model class to another model class
I'm new to Django. My goal is to send the value of a method belonging to a model class by default in the other model class. class Booking(models.Model): room_number_id = models.ForeignKey(Room,on_delete=models.DO_NOTHING) customer_id = models.ManyToManyField(Customer) check_in = models.DateTimeField(auto_now_add=True) check_out = models.DateTimeField(auto_now_add=False,auto_now=False,auto_created=False, null=True) status = models.BooleanField(default=False) @property def calculate_day(self): day = self.check_out - self.check_in return str(day.days) @property def total_price(self): day = self.check_out - self.check_in price = self.room_number_id.room_type_id.room_cost return price\*day.days class Payment(models.Model): booking_id = models.ForeignKey(Booking,on_delete=models.DO_NOTHING) ACCEPT_CHOICES = ( ('Cash','Cash'), ('Credit','Cash'), ) payment_type = models.CharField(max_length=1,choices=ACCEPT_CHOICES) total_price = models.IntegerField(default=Booking.total_price()) payment_detail = models.TextField() In short, I want to make the value of the total_price method of the Booking model the default value of the price in the Payment model. Apart from that, if you have different advice and suggestions, I'm waiting for a reply. -
How to integrate Django Project with Kafka
I know there is python library of kafka for python: confluent-kafka. But How can I integrate Web (Django) application with kafka? I found django-logpipe library. But I am not sure Its production ready or not -
Pass a list of start_urls as parameter from Django to Scrapyd
I'm working in a little scraping platform using Django and Scrapy (scrapyd as API). Default spider is working as expected, and using ScrapyAPI (python-scrapyd-api) I'm passing a URL from Django and scrap data, I'm even saving results as JSON to a postgres instance. This is for a SINGLE URL pass as parameter. When trying to pass a list of URLs, scrapy just takes the first URL from a list. I don't know if it's something about how Python or ScrapyAPI is treating or processing this arguments. # views.py # This is how I pass parameters from Django task = scrapyd.schedule( project=scrapy_project, spider=scrapy_spider, settings=scrapy_settings, url=urls ) # default_spider.py def __init__(self, *args, **kwargs): super(SpiderMercadoLibre, self).__init__(*args, **kwargs) self.domain = kwargs.get('domain') self.start_urls = [self.url] # list(kwargs.get('url'))<--Doesn't work self.allowed_domains = [self.domain] # Setup to tell Scrapy to make calls from same URLs def start_requests(self): ... for url in self.start_urls: yield scrapy.Request(url, callback=self.parse, meta={'original_url': url}, dont_filter=True) Of course I can make some changes to my model so I can save every result iterating from the list of URLs and scheduling each URL using ScrapydAPI, but I'm wondering if this is a limitation of scrapyd itself or am I missing something about Python mechanics. This is how …