Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django restframework: ReadOnlyModelViewSet create HTTP_403 but expected HTTP_405
I creating a REST-API with django and the django restframework, therefore I am using the ReadOnlyModelViewSet. In my unittest for testing the create / POST method, I was expecting an HTTP_405_METHOD_NOT_ALLOWED but actually it is an HTTP_403_FORBIDDEN. For the update / PUT it is a HTTP_405 as expected. Is this behaviour the default behaviour or do I have a dumb bug? And yes the user is authenticated. The Viewset: class StudentSolutionReadOnlyModelViewSet(viewsets.ReadOnlyModelViewSet): queryset = StudentSolution.objects.all() serializer_class = StudentSolutionSerializer def get_permissions(self): if self.request.method == 'POST': return (permissions.IsAuthenticated(), ) return (permissions.IsAuthenticated(), IsStudentSolutionOwnerOrAdmin(),) def get_queryset(self): if self.request.user.is_staff: return StudentSolution.objects.all( course_assignment=self.kwargs['course_assignment_pk'] ).order_by('student__last_name', 'course_assignment__due_date') return StudentSolution.objects.filter( student=self.request.user, course_assignment=self.kwargs['course_assignment_pk'] ).order_by('course_assignment__due_date') -
Django template Javascript passing a python variable to a javascript one
I did create a python function called generate_random_number that generate a random number between 1 and 9 and compare it to the id of each video in my database and return the url of the video corresponding to the id matching the random number. Here is the function: from random import randint from dash_interface.models import Video from django import template r = template.Library() @r.simple_tag def random_video(): random_number = randint(1, 9) all_videos = Video.objects.all() for video in all_videos: if video.id == random_number: random_url = video.video_url return random_url I want to pass random_url to a javascript variable in a django template. My template looks like this: <video id="videoplayer" controls></video> <script> {% load generate_random_number %} // setup the video element and attach it to the Dash player function setupVideo() { var url = " "; var context = new Dash.di.DashContext(); var player = new MediaPlayer(context); player.startup(); player.attachView(document.querySelector("#videoplayer")); player.attachSource(url); } </script> <style> video { width: 60%; height: 40%; } </style> The variable concerned is url. I did a {% load generate_random_number %}, but I don't know if I can replace the quotation marks in url by {{ random_url }}. -
Which characters to allow for international usernames and passwords, Django, PostgreSQL
I am working on an internationally oriented e-commerce website. Our first target audience is Russian, and Arabic speaking people after that. Currently I am working on the input validation for the account registration and log in. Now I wonder which characters I should allow in usernames and passwords. The website is build with Django and Django Rest Framework, using PostgreSQL for the database. Any advice on that? Some (beginner friendly) sources that help a beginner find his way in this area would be appreciated. Thanks. -
Django m2m_changed signal with additional model
I have a model looking like this: class Recipe(models.Model): name = models.CharField(_('Name')) components = models.ManyToManyField(RecipeComponent, through='alchemy.RecipeComposition') total_weight = models.FloatField(_('How much recipe will weight')) class RecipeComponent(models.Model): name = models.CharField(_('Name')) class RecipeComposition(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) component = models.ForeignKey(RecipeComponent, on_delete=models.CASCADE) number = models.FloatField(_('Defines how much of the component you need'), default=1) I have to do some calculations (for example total weight) of the recipe after any updates in RecipeComposition. Trying to do like this unfortunately doesn't help: @receiver(m2m_changed, sender=Recipe.components.through, weak=False) def recipe_components_changed(sender, **kwargs): print("meow >^-_-^<") # some calculations for recipe.total_weight here Found question with same problem but it's old (3 yrs ago) and has no correct answer. There is a link to ticket 17688 there which is opened 6 yrs ago but still not solved. I do not want to use post_save like this: @receiver(post_save, sender=RecipeComposition) because in this case when new Recipe created total_weight will be recalculated after each component added. Are there any other ideas how to make this work? -
how to combine queryset in django listview
I was using products.objects.all() to display all the values in the database but i want to do something more.I want to filter some specific data from the database using products.objects.filter()it worked but it is not working when i use this query in listview coordinates = [1231,1231] for i in coordinates: queryset = products.objects.filter(lat=i) This code returning only one value insted of multiple Thankyou. -
cannot connect to Django on nginx with android retrofit
We Published a mobile application and SOME of our users have trouble to connect to our app. first of all we guess it was a dns Issue so we change our DNS from Digital ocean to Cloudflare but it didn't fix anything. We use Django 2.0 with gunicorn and DRF on Nginx with Letencrypt certificate. There is UFW firewall on server. on Android Device we use Retrofit 2.4 to connect to server. but some of our users cannot connect to server but they have ping on server and can open website but they can connect with vpn to android app. I really have no Idea where should I troubleshoot or what is the problem. -
how to attach a pdf in google app engine python send_mail function?
I cannot find any example on how to attach files(pdf) that are within my root folder of the site in python (google app engine) send_mail function. url_test = "https://mywebsite.com/pdf/test.pdf" test_file = urlfetch.fetch(url_test) if test_file.status_code == 200: test_document = test_file.content mail.send_mail(sender=EMAIL_SENDER, to=['test@test.com'], subject=subject, body=theBody, attachments=[("testing",test_document)]) -
Cannot assign "'HR'": "Employee.department" must be a "Department" instance
when I try to feel department field is show me this error. I don't understand this error.. please help me out Cannot assign "'HR'": "Employee.department" must be a "Department" instance. here is my model.py class Department(models.Model): name = models.CharField(max_length= 20,null=True) def __str__(self): return self.name class Employee(models.Model): employee_name = models.CharField(max_length= 20, null=True) surname = models.CharField(max_length= 20, null=True) address = models.CharField(max_length = 50, null=True) qualification = models.CharField(max_length = 30,null=True) contact_num = models.IntegerField(null=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return self.employee_name here is my form.py class AdForm(forms.ModelForm): employee_name = forms.CharField() surname = forms.CharField () address = forms.CharField () qualification = forms.CharField () contact_num = forms.IntegerField () department = forms.CharField() class Meta: model = Employee fields = ('employee_name', 'surname', 'address', 'qualification', 'contact_num', 'department') here is my view.py def create(request): if request.method == 'POST': form = AdForm(request.POST) if form.is_valid(): #getting me error on this form.save() return HttpResponseRedirect(reverse('employee-list')) else: form = AdForm() return render(request, 'employee/create.html', {'form': form}) -
makemigrations on heroku is not reflecting on the table content....All tables are empty
I have hosted my app on heroku and it has two tables with 1000 rows but running the code: heroku run python manage.py makemigrations heroku run python manage.py migrate is migrating only the tables and not the contents...How do I migrate the tables contents Thank you -
Django: delete object when checkbox is checked
I'd like to delete objects when the table row is checked in Django. After following answers on Stackoverflow, I've got the code below. However, it doesn't delete the objects of the model. I log the code; the onclick delete button works. It calls delete_test function, but the test model isn't delete. The terminal says Forbidden (CSRF token missing or incorrect.): /test-management/delete_test/ Thank in advance! urls.py from test_management.views import (test_list, add_test , delete_test) urlpatterns = [url(r'^test-management/test/', test_list, name='test'), url(r'^test-management/add_test/', add_test, name='add_test'), url(r'^test-management/delete_test/', delete_test, name='delete_test'),]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) views.py def delete_test(request): if request.is_ajax(): selected_tests = request.POST['test_list_ids'] selected_tests = json.loads(selected_tests) for i, test in enumerate(selected_tests): if test != '': Test.objects.filter(id__in=request.POST.getlist('items')).delete() return HttpResponseRedirect('/test-management/test/') test_list.html </button> <button class="btn btn-round delete-btn" data-toggle="modal"> <i class="material-icons" action >delete</i> Delete </button> <div class="table-container"> <table id="fresh-table" class="table table-striped test-list"> <thead class="thead-table-list"> <tr> <th scope="col"> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" id="checkall" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </th> <th scope="col">#</th> <th scope="col">Test</th> <th scope="col">Type</th> <th scope="col">Test Date</th> </tr> </thead> <tbody> {% for test in tests %} <tr data-id="{{ test.id }}"> <td> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input check-ele" type="checkbox" value=""> <span class="form-check-sign"> <span class="check"></span> </span> </label> </div> </td> <td>{{ test.id}}</td> <td>{{ test.test_name}}</td> <td>{{ test.test_type}}</td> <td>{{ test.test_date}}</td> </tr> {% … -
Separate a 'for loop' in multiple sections by a divider
I have a for loop {% for d in list %} <a href="#">{{ d.name }}</a> {% endfor %} What I want is for every 3, of them to be separate like: <div> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> <div> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> <a href="#">{{ d.name }}</a> </div> -
Use saved form instead of cleaned form django
I am not able to display the invoice number in the receipt.html models.py class Buyer(models.Model): name_of_buyer = models.CharField(max_length=200,null=True) address_of_buyer = models.CharField(max_length=200,null=True) interested_in = models.ForeignKey(Box,on_delete=models.CASCADE,null=True) Pickup_dt = models.DateField(null=True) Pickup_time = models.CharField(max_length=80,null=True) Invoice_number = models.CharField(max_length=12,blank=True,unique=True) def save(self, *args, **kwargs): if self.interested_in == 'Mangos': x=randint(99,99999) self.Invoice_number = str('MAN') + str(x) elif self.service == 'Banana': x=randint(99,99999) self.Invoice_number = str('BAN') + str(x) elif self.service == 'Apple': x=randint(99,99999) self.Invoice_number = str('APP') + str(x) super(imfc_one,self).save() def __str__(self): return str(self.Invoice_number) forms.py class Sale(forms.ModelForm): def clean_interested_in(self): buyer_interested_in_box = self.cleaned_data['interested_in'] if buyer_interested_in_box.mango < 10: raise forms.ValidationError('Not enough fruits.Please select another box') class Meta: model = Buyer fields = '__all__' view.py def ind(request): form = Sale() if request.method == 'POST': form = Sale(request.POST) if form.is_valid(): form.save(commit=True) return render(request,'app_one/receipt.html',{'upform':form.cleaned_data}) else: print("form is not vaalid") return render(request,'app_one/index1.html',{'form':form}) receipt.html receipt : {{ upform.Invoice_number }} How can I have the invoice number in the receipt.html Thank you. -
302 recv() failed(104:Connection reset by peer) while proxying upgraded connection
302 recv() failed(104:Connection reset by peer) while proxying upgraded connection client:xx.xx.xx.xx,server:localhost,request:GET /dbconnect/ HTTP/1.1, upstream:"uwsgi://unix:/usr/local/djcmb/hcDjango/hcDjango.sock" i use dwebsocket and the environment is linux+uwsgi+nginx+django -
subprocess.Popen or proc.stdout.read() corrupting JSON data
I am running a PHP script through Python Django as it contains legacy code for a client. Data is passed to through to the PHP script via JSON and after the script is computed a string is returned for display like so. proc = subprocess.Popen(["php -f script.php " + json.dumps(data_for_php, sort_keys=True)], shell=True, stdout=subprocess.PIPE) script_response = proc.stdout.read() return HttpResponse(script_response) The issue I am having is something in this process is corrupting the data. i.e. one JSON field 'xxx_amount': u'$350,000.00', returns ,000.00, at the value. It's not doing this for anything else. I have been doing a bit of debugging and have determined that json.dumps(data_for_php, sort_keys=True) is not causing the issue, also data_for_php is good too. It leads me to believe that this command proc.stdout.read() is some how mutating $350 to (space). Note: same thing is occurring for other dictionary values. -
Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured
from django.urls import path from django.conf.urls import include, url #22.JUN.2018 #25.Jun.2018 from django.contrib import admin #from bookmark.views import BookmarkLV, BookmarkDV urlpatterns = [ url(r'^admin/',admin.site.urls), url(r'^bookmark/',include('bookmark.urls', namespace='bookmark')), url(r'^blog/', include('blog.urls', namespace='blog')), I need you guys help!!! This is my code. And i have a error....please help me.... " 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead." -
Django Password Reset No reverse match
I am trying to use password reset of django I am getting the following error after I have entered email for password reset django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. my dashboard/urls.py is from django.conf.urls import include, url # from graphene_django.views import GraphQLView # from django.contrib import admin from django.contrib.auth import views as auth_views from . import views as core_views from .product.urls import urlpatterns as product_urls urlpatterns = [ url(r'^$', core_views.index, name='index'), url(r'^products/', include(product_urls)), # url(r'^login/$', auth_views.login, name='login'), url(r'^login/$', auth_views.login, {'template_name': 'dashboard/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'), # url(r'^logout/$', auth_views.logout, name='logout'), # url(r'^admin/', admin.site.urls), url(r'^', include('django.contrib.auth.urls')), url(r'^password_reset/$', auth_views.password_reset, { 'post_reset_redirect': '/dashboard/password_reset/done/' , 'template_name': 'registration/password_reset_form.html'}, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, {'template_name': 'registration/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, {'template_name': 'registration/password_reset_confirm.html'}, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, {'template_name': 'registration/password_reset_complete.html'}, name='password_reset_complete'), ] -
Call function from button in django
On one of my pages I want to display a button, whenever this button is clicked I want to display the following in my display "Button clicked". However the following message displays in my console.""GET /account/all-plan/?print_btn=Click HTTP/1.1" 200 5025" This is my view def print_from_button(request): if(request.GET.get('print_btn')): print('Button clicked') return HttpResponse('testklik') html <form method="get"> <input type="submit" class="btn" value="Click" name="print_btn"> </form> and url in urls.py path('all-plan/print_from_button', views.print_from_button, name='print_from_button'), Can anyone point me into the right direction, I cannot find what I am missing. Thanks a lot! -
Can not get value from sorted method in the Elasticsearch dsl
I want sorted by distance witch help Elasticsearch dsl. But I can not get value from sorted method. test = MyIndex.search()\ .sort( { "_geo_distance" : { "location" : { "lat": "21.567", "lon": "31.957"}, "order" : "asc", "unit" : "km", } }) print(test.sort) and I get this method <bound method Search.sort of <django_elasticsearch_dsl.search.Search object at 0x7f141a8008d0>> How get value from this object? I want see new 'sorted' field for each object in MyIndex according to documentation: https://www.elastic.co/guide/en/elasticsearch/guide/current/sorting-by-distance.html -
How to access Django Service(hosted on another IP) from chrome extension
I have hosted DjangoServices on particular IP address (xx.xx.x.x:8000) and want to access them from chrome extension. I am unable to access those services while making a connection from javascript like as follows: xmlhttp = new XMLHttpRequest(); theUrl = "http://xx.xx.x.x:8000/polls/neo4jSample/"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ } } But, this works when I hosted on local machine as follows: xmlhttp = new XMLHttpRequest(); theUrl = "http://127.0.0.1:8000/polls/neo4jSample/"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200){ } } Please, anyone can help me out of this issue. Thanks in advance. -
Heroku dynos: can I technically use less dynos in my Django setup?
I'm using the following with my Django application: Django channels Celery with both regular and periodic tasks Deployed on Heroku My Procfile looks like this: web: daphne artist_notify.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py migrate --noinput && python manage.py runworker -v2 celerybeat: celery -A artist_notify beat -l info celeryworker: celery -A artist_notify worker -l info This combination seems to be expensive, and I'm wondering if I can make it better. I tried combining celerybeat and celeryworker (with &&) into one dyno called celery, like so: celery: celery -A artist_notify beat -l info && celery -A artist_notify worker -l info But that doesn't work, although other && combinations do work. I'm wondering if I can maybe combine the workers from worker and celeryworker? -
Redirect URL in python
I'm breaking my head around this from couple of days now, here is the scenario. I have written a class for our internal sso validation. When my Django app loads i'm calling a fucntion to validate the whether the sso user is a valid one or not, if no the page should redirect to the sso login page. import webbrowser @csrf_exempt def Sso(request): #Initializing the sso class ssoObj = sso(True) applicationURL = 'http://app.com' if not(ssoObj._isValidUser): redirectionUrl = ssoObj.GetRedirectionUrl(applicationURL) webbrowser.open(redirectionUrl) return HttpResponse("reached last line") Note: default ssoObj._isValidUser will return False. ssoObj.GetRedirectionUrl function will return SSO URL + "return=" + applicationURL. When ever the webbrowser.open is getting hit, its opening the redirected link Mozilla(might be my default browser,not sure). I want the redirect url to open at the same tab user is accessing the application url. How do i do this? any Suggestions are greatly appreciated. -
Django sending user password in plain text when
I'm utilizing the ADMINS setting so Django can send more detailed error logs when my Heroku setup crashes. However, when the error occurs upon/after a user submits a registration form, Django is sending me (alongside the error) their username and password in plain text. I'm using django-registration and haven't played around with the form at all. Is this by design? seems incredibly irresponsible to me. -
What's the best way to make an email sending progress bar in Django 2.x?
I use this code from documentation in order to send emails: from django.core import mail connection = mail.get_connection() connection.open() email1 = mail.EmailMessage( 'Hello', 'from@example.com', ['to1@example.com'], connection=connection, ) email2 = mail.EmailMessage( 'Hello', 'from@example.com', ['to2@example.com'], ) connection.send_messages([email1, email2]) connection.close() What library should I use in order to make a progress bar which will be indicate how much emails were sent? Is it Django Channels or there is a better way? -
Loop over dictionary list and retrieve values in django
I am new to Python/Django, coming from PHP, and have difficulty understanding the best way to deal with what I am used to calling multidimensional arrays in PHP. So I have a CSV file: name,age,phone marta,30,12345 bob,22,33555 alice,55,1939 In my model, I'm reading this CSV file line by line. I will then analyze the code, manipulate some of the data, and then I want to display the data in a table. Here is what I do: data = {} with open(path) as f: reader = csv.reader(f) i = 0 for row in reader: i += 1 data[i] = {'name': row[0], 'age': row[1], 'phone': row[2]} This seems to work and it creates a variable that contains all the rows, plus all the info for each row. My idea, for better or for worse, is to get this list: data[1] = {name: marta, age: 30, phone: 12345} data[2] = {name: bob, age: 22, phone: 33555} data[3] = {name: alice, age: 55, phone: 1939} Which I then pass onto my view, where I do something like this: {% for details in data %} <tr> <td>{{ details.name }}</td> <td>{{ details.age }}</td> <td>{{ details.phone }}</td> </tr> {% endfor %} The loop is successful and I … -
Integrating instamojo payment gateway with Django application (Webfaction)
I am integrating instamojo payment gateway With django app on webfaction. For instamojo webhook url I have created one custom app(listening a port) on webfaction, and using that port but getting OSError at / [Errno 98] Address already in use I am using this sample code for webhook url - https://support.instamojo.com/hc/en-us/articles/208485745-Webhook-URL-in-PHP-Python