Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to verify hashed passwords in Bcrypt?
I have been using bcrypt for hashing my passwords for an authentication system in Django. I could succesfully hash it but not not decrypt for getting inside my login system. -
Django: why is ViewClass.as_view used with brackets in URLconf?
If I have a view-class and I want to use it in URLconf, I will have to use its as_view()-method, since the view-class isn't a function, but a class. My question is, in URLconf, why is as_view() called with brackets? Doesn't this mean that the function will be run upon reading URLconf? If so, what is it exactly that as_view does? Example: # urls.py from django.conf.urls import url from some_app.views import AboutView urlpatterns = [ url(r'^about/$', AboutView.as_view()), # <--- We're calling the method. Why? ] -
Remove history button from Django admin
I want to enable/disable history from django admin button based on the type of user. My end goal here is to be able to understand how to show hide this button. -
Django LocaleMiddleware permanent redirects
I want to be able to have https://example.com/ 301 redirect to https://example.com/en/ https://example.com/fr/ https://example.com/de/ etc depending on what the LocaleMiddleware determines the users language to be (for SEO purposes). Currently it 302 redirects by default. This was apparently added but I can't figure out how to do it. The documentation doesn't mention anything about it. Any help would be much appreciated. -
How can I force the page refresh with Django Channels?
i am looking for a way to reload a web page whenever a server side event occour with Django Channels. -
django using can_order to change order of form fields
I'm new to django. I have a form with one field that keeps only the name of family members. I want user be able to change the order as he/she wishes. Now he order is the order of their creation. I found something can_order that when I added it to my form, another field appeared aside names and was an integer showing the number in the list. My question is can I change order playing with this number? If yes how should I do that? my form: class FamilyMemebrsNameForm(forms.Form): name= forms.CharField(label=_('name'), max_length=250) FamilyMemberNameItem= formset_factory(FamilyMemebrsNameForm, can_delete=True, can_order=True) FamilyMemberNameItem is what I use.Thanks -
Recursive app dependencies django
Django's INSTALLED_APPS is a list in the settings file, which ultimately the devops girl/guy of the wsgi-application is responsible for. However, when creating an app, I often use templates and templatetags of other apps, for example django-bootstrap4. Consider a simple bootstrap4-with-butter app, that only proivides this template: bs4wb/templates/bs4wb/base.html {% extends "bootstrap4/bootstrap4.html" %} {% block bootstrap4_extra_head %} <script> confirm('with butter?!'); </script> {% endblock bootstrap4_extra_head %} It is not enough for the devops to install and add to INSTALLED_APPS bs4wb, they also need to do the same for django-bootstrap4, and moreover, he/she also needs to keep track of the version I used whenever I upgrade from django-bootstrap4 to django-bootstrap5` or something. That is, I need to document an extra step which can change. How can I specify recursive INSTALLED_APPS? Is there something like an app-union? For example (obviously ugly syntax, sorry): export('bs4wb', app_by_union(['bootstrap4', 'bs4wb']) ) which would insert bootstrap4 and bs4wb next to each other whenever bs4wb is added to INSTALLED_APPS? -
Failed to start Redis In-Memory Data Store
After trying to establish WebSocket Connection using Redis this error was appeared. I have no idea what happened because I've established this connection well but soon after publishing a message using RedisPublisher in Django-websocket-redis, Redis seems to be dead. What's going on and how can I make Redis work in this situation? -
event.save() gives error in Django
I am getting sqlite3 Integrity Error - Datatype Mismatch. But python manage.py migrate and python manage.py makemigrations run well. My form data is valid. I am getting this error if I try to save the data to the database by making use of event.save in views. My model is: class createEvent(models.Model): FirstName = models.CharField(max_length=150) LastName = models.CharField(max_length=150) EventName = models.CharField(max_length=150) EventOrganizer = models.CharField(max_length=150) Location = models.CharField(max_length=200) Date = models.DateField() LastDateOfRegistration = models.DateField() EventDetails = models.TextField() My views.py is def create_event(request): title = "Drizzlelore" subtitle = "Create event" if request.method == "POST": form = createEventForm.createEventForm(request.POST) print(form.errors) if form.is_valid(): fname = form.cleaned_data.get('FirstName') lname = form.cleaned_data.get('LastName') eventName = form.cleaned_data.get('EventName') eventOrganizer = form.cleaned_data.get('EventOrganizer') location = form.cleaned_data.get('Location') date = form.cleaned_data.get('Date') lastDateofReg = form.cleaned_data.get('LastDateOfRegistration') eventDetails = form.cleaned_data.get('EventDetails') event = form.save(commit=False) event.save() context = { "title":title, "subtitle":subtitle, "form" : form, } return HttpResponse("Success form submitted") else: print("Form not valid") return HttpResponse("Failure") else: form = createEventForm.createEventForm() context = { "title":title, "subtitle":subtitle, "form":form, } return render(request,"home/createevents.html",context) My form is class createEventForm(forms.ModelForm): class Meta: model = createEvent fields = [ 'FirstName', 'LastName', 'EventName', 'EventOrganizer', 'Location', 'Date', 'LastDateOfRegistration', 'EventDetails', ] -
How do I use Django's return JsonResponse in the template and show it as a notification message?
I have this return JsonResponse in a method in views.py: return JsonResponse({"message": "You're Successfully Registered!"}) I want this message to show as a notification message in the HTML template. What is the ajax function that I should use to retrieve the data returned from this JsonResponse? -
How to add select all in django?
i want have a form like this https://www.jquery-az.com/boots/demo.php?ex=63.0_9 How i can make this form in django ? Thank you -
Django registration redirect to profile after login
I'm using django-registration-redux and have most of it working. I'm trying to redirect to the user profile after login. Currently the URL for user profile is: url(r'^user/(\w+)/$', views.profile, name='profile'), ...and the view for the profile is: def profile(request, username): user = get_object_or_404(User, username=username) products = Product.objects.filter(user=user) if not request.user == user: return render(request, 'no.html') else: return render(request, 'profile.html', {'user':user,'products': products}) I've added LOGIN_REDIRECT_URL = 'profile' to settings.py but am getting the error: Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['user/(\\w+)/$'] I've gone around this so many times I'm totally confused. I could simply set LOGIN_REDIRECT_URL = 'home' and be done with it, but then I wouldn't have gotten past this error. Do I need to create a different view for this? -
Access denied using Django with oAuth2 (django-oauth-toolkit)
First I made a test application, and after the user is logged in and authorizes the app, he receives the code that later will be used to grant access. As a test, I made a basic html site with many things hardcoded to check it works: <!DOCTYPE html> <html> <head> </head> <body> <form method="post" action="http://localhost:8000/o/token/"> {% csrf_token %} <input type="hidden" name="code" value="{{ code }}" /> <input type="hidden" name="redirect_uri" value="http://google.com" /> <input type="hidden" name="grant_type" value="authorization_code" /> <input type="hidden" name="client_id" value="{{ client_id }}" /> <input type="hidden" name="client_secret" value="{{ client_secret }}" /> <input type="submit" value="GO" /> </form> </body> </html> Here I get the code I received before, the client id and secret, received when I created the application, and I sent it in a post form to token. I was expecting that after clicking in GO I will be redirected to google, but it just raised an error "access denied". I tried other things but I got other errors and I stuck myself in here because it seems that "access denied" is just about the credential. Or maybe I'm not sending the right data? Thanks. -
Accessing form data in-between steps outside Django FromWizard’s class (accessing kwargs outside of class)
I’m trying to implement aRkadeFR’s solution for repeating steps of the form wizard dynamically (I'm using django-formtools 2.0). My code looks something like this: def form_factory(request, *args, **kwargs): FORMS = [ ('choose_transaction', generator_forms.TransForm), ('choose_functions', generator_forms.ChooseFunctionForm), ] print kwargs # always prints {} x_id = kwargs.get('pk') # this is always None if x_id is not None: x = ContributionDescription.objects.get(pk=x_id) try: functions_ids = request.session['wizard_return_class']['step_data']\ ['choose_functions']['choose_functions-funct_title'] if functions_ids is not None: print functions_ids # prints what I need, but never when I need except KeyError: pass # some logic to be inserted here, like # for i in list_of_x # index_in_form_list = FORMS.index(('choose_functions', enerator_forms.ChooseFunctionForm)) + 1 # placeholder logic # new_form = ('choose_f_description', generator_forms.ChooseFunctionDescriptionForm) # FORMS.insert(index_in_form_list, new_form) class ReturnClass(TestWizardView): form_list = FORMS return ReturnClass.as_view()(request, *args, **kwargs) Is accessing request.session a way to go? The print functions_ids runs not right after pressing next of the 'choose_functions' step, but after pressing next of the subsequent step (here: after the 'choose_f_description' step), which is not sufficient for me. In other examples I’ve found there is no problem with accessing wizard’s kwargs outside the wizard class, but I don’t understand how they’ve done it: DynamicQnaire’s load_questionnaire function surveyweb’s do_survey_factory function Thanks in advance. I’m beginner so I … -
(Django) How to transfer value from field to the custom ImageKit processor inside the model?
I use Django ImageKit to process/crop uploaded photos. I added my own custom processor to add text to the photo (like watermark): # ./example/processors.py from django.conf import settings from PIL import Image, ImageDraw, ImageFont _default_font = ImageFont.truetype(settings.TEXT_OVERLAY_FONT_REGULAR, 24) def add_text_overlay(image, text, font=_default_font): rgba_image = image.convert('RGBA') text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) image_draw = ImageDraw.Draw(text_overlay) text_size_x, text_size_y = image_draw.textsize(text, font=font) text_xy = ((rgba_image.size[0] / 2) - (text_size_x / 2), (rgba_image.size[1] / 2) - (text_size_y / 2)) image_draw.text(text_xy, text, font=font, fill=(255, 255, 255, 255)) image_with_text_overlay = Image.alpha_composite(rgba_image, text_overlay) return image_with_text_overlay class TextOverlayProcessor(object): def __init__(self, text='Lorem ipsum dolor sit amet'): """ :param text: The overlay text, string. """ self.text = text def process(self, img): return add_text_overlay(image=img, text=self.text) But how to transfer value from field to the custom ImageKit processor inside the model? Something like this: # ./example/models.py from imagekit.models import ImageSpecField from imagekit.processors import ResizeToFill from .processors import TextOverlayProcessor class Example(models.Model): description = models.CharField('Description', ...) image = models.ImageField('Picture', default=None) image_800x800 = ImageSpecField( source='image', processors=[ ResizeToFill(800, 800), TextOverlayProcessor(text=self.description) # but `self` is wrong and raise error ], format='JPEG', options={'quality': 100} ) ... I will be glad to explanatory comments and/or use cases. -
Moving margins bug that is not activating - bootstrap
I have a django project and I am working on a template. I have a template that has some html and css. I want to have an image that is inline with text. That is happening but I wan tot move the text down a little bit by adding padding or margin. So what i have right now is bootstrap incorporated with my html and css. I have added custom css to the template that over ride the bootstrap to get more refined css. Now what i want is to move the | username down a few pixels. I will have all of my code below and a sample image.. Here is my html template code: <div class="row solid-borders"> <div class=" col-md-2 border-padding"> <img src="{% static 'images/yap-logo-possible-1.png'%}" class="header-icon-size" style="display:inline;" alt=""> <h1 class="border-padding border-margin-top" style="display:inline;">| {{ user.username }}</h1> </div> </div> here is my custom css that I have added: .border-padding { padding: 8px !important; } .border-margin-top { padding-top: 25px !important; } .solid-borders { border-bottom: 1px solid black !important; } and I have bootstrap incorporated in it sample image: -
How to render Django query set as column wise into html table?
Let's say my sql table looks like this.. products table -------------------------------- | id | Model| Manufacturer | -------------------------------- | 1 | ABC | Samsung | | 2 | XYZ | LG | | 3 | ZYX | Sony | -------------------------------- in django view i fetched all records from this table and passed it to template.. def compare(request): product_ids = request.GET.get('product_ids') products = Product.objects.filter(id__in=product_ids) return render(request, 'compare.html', {'products': products}) as query_set result records comes like one after the other we can say it is following row wise but for this case in template i wanted to create an html table and the result should come like this .. -------------------------------------------- |id | 1 | 2 | 3 | |Model | ABC | XYZ | ZYX | |Manufacturer | Samsung | LG | Sony | -------------------------------------------- By looking at above example you can see data is rendered as column wise. so please suggest me a better method in Django by which i can achieve this and also please correct me if i'm wrong as i'm beginner in Django. Thanks in advance -
PyPDF2 PdfFileMerger replacing PDF in memory with blank pages when merging
I am sending a PDF via POST to Django using ajax // Set up form data var formData = new FormData(); formData.append("docfile", myPDFreport) $.ajax({ url: "{% url "process_report" %}", type: 'POST', data: formData, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', // If sucess, download file success: function(data, status, xhr) { // Get the name of the file // https://stackoverflow.com/questions/40939380/how-to-get-file-name-from-content-disposition var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition && disposition.indexOf('attachment') !== -1) { var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches != null && matches[1]) { filename = matches[1].replace(/['"]/g, ''); } } download(data, filename, "application/pdf"); } }); Then I am receiving the PDF in my views.py file, scraping it for some new information to create a second PDF, and am merging the two PDF files to return def process_report(request): # Handle file upload if request.method == 'POST': # Grab report report_file = request.FILES['docfile'] # Create merged coversheet and report by passing PDF object merged_pdf, coverSheetNameFinal = analyzer(report_file) response = HttpResponse(merged_pdf.getvalue(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{}"'.format(coverSheetNameFinal) return response else: return HttpResponseBadRequest('Must be Post') The files are being merged in the analyzer function as def analyzer(report_filePDF): .......generate a PDF named "coverSheetFinal" using reportLab... coverSheetPDF = StringIO.StringIO(coverSheetFinal.getpdfdata()) merger = … -
Filtered Django result not getting displayed properly
I have a kanban board and there seems to be something strange going on with it. If If I move a card more than once in the same day, it won't stay even though I can see it updated the database properly. views.py def account(request): if not request.user.is_authenticated(): return render(request, 'kanban/signup.html') users_jobs = Job.objects.filter(user=request.user).exclude(status='INACTIVE') stages = create_stage_dict() for job in users_jobs: job_tracker = Tracker.objects.filter(job=job.id).latest('id') job_stage = Stage.objects.get(id=job_tracker.stage.id) stages[job_stage.reference_name]['jobs'].append(job) return render(request, 'kanban/board.html', {'navbar_template': choose_navbar(request.user.is_authenticated()), 'stages': stages.items()}) board.js function draggableInit() { var sourceStageID; $('[draggable=true]').bind('dragstart', function (event) { sourceStageID = $(this).parent().attr('id'); event.originalEvent.dataTransfer.setData("text/plain", event.target.getAttribute('id')); }); $('.panel-body').bind('dragover', function (event) { event.preventDefault(); }); $('.panel-body').bind('drop', function (event) { var children = $(this).children(); var targetStageID = children.attr('id'); if (sourceStageID != targetStageID) { var jobID = event.originalEvent.dataTransfer.getData("text/plain"); setTimeout(function () { var job = document.getElementById(jobID); children.prepend(job); }, 1); $.ajax({ type: 'POST', url: '/account/update_tracker/', data: {'job': jobID, 'source_stage': sourceStageID, 'target_stage': targetStageID }, dataType : 'json', }); } event.preventDefault(); }); views.py - view for the url called in the ajax request @csrf_exempt def update_tracker(request): if not request.POST: return render(request, 'kanban/board.html') job_id = request.POST.get('job') job = Job.objects.get(id=job_id) target_stage_id = request.POST.get('target_stage') target_stage = Stage.objects.get(id=target_stage_id) Tracker.objects.create(job=job, stage=target_stage) return HttpResponse(json.dumps({'job': job_id, 'target': target_stage_id}), content_type='application/json') The database does update when the card gets moved and I've used … -
Django form idea how to do this
I dont know how to do this in Django. I want to fill The form with data, next render The page with all information from previous page with form and then submit IT to database can anyone help me plase. -
Django: How to pass a javascript var to Django URL as parameter in ajax?
How can I pass a javascript variable to a Django URL? It presents a, TypeError at /object/Query/details view() got an unexpected keyword argument 'query' I am trying to redirect to another HTML page following this process: HTML Search Input > Pass to Javascript through input button onclick > Pass to JQuery Ajax sendQueryData> Redirect to another page using Django render() ;considering I had to do more things on the passed parameters to the URL upon passing them in AJAX. The main problem lies on this two lines (I think): url_page = url + "{% url 'view' 'query'%}"; //supposedly how we get parameters (but query is a javascript `var` and url =url.replace('query' , query); //where I intend to correctly build the url forcing the query to take its place in the url I'm just not quite sure if my urls.py, ajax call on javascript in Django url are all aligned at all. My urls.py urlpatterns = [ url(r'^$', views.index, name='homepage'), #--- Home --- url(r'^search/pass/$', views.pass_query, name='pass_query'), # View Object Details url(r'^object/(?P<query>\w+)/details', views.view(), name='view') My HTML <div id="button-group" class="button-group"> <input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(0)" value="View Routes"/> <input type="submit" class="btn btn-primary btn-lg btn-space col-sm-3" onclick="redirect_to_url(1)" value= "View City Details"/> <input … -
Nginx Gunicorn one ip multiple django sites in folders
thanks for reading my question. I'm trying to serve multiples Django sites on their own folders in one server without domain (only IP address) using Gunicorn and Nginx. Something like that: 20.20.20.20/demos/myapp1/ --> Django app 20.20.20.20/demos/myapp2/ --> Django app 20.20.20.20/demos/myapp3/ --> Django app I have tested a lot of settings but I can't make it work. When i tried to load URL 20.20.20.02/demos/myapp1/ i get a 404 not found error :( Example one site nginx conf: upstream app1_server { server unix:/webapps/myapp1/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name 20.20.20.20; keepalive_timeout 5; client_max_body_size 4G; location /static/ { alias /webapps/myapp1/static/; } location /media/ { alias /webapps/myapp1/media/; } location /demos/myapp1/ { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app1_server; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /webapps/myapp1/static/; } } What is wrong with my myapp1.conf file? For the record, if i change "location /demos/myapp1/" to "location /" my first app works, but the others apps still not working. Thanks in advance. -
Django check upload file content
I'm new with Django. I have facing problem that I want to check the file content before letting user upload the file. Please give me some example to show how to do it. Thanks -
Uploading and processing a csv file in django using ModelForm
I am trying to upload and fetch the data from csv file uploaded by user. I am using this method for doing the same, which pretty much explains everything and gives me result also. What I am not able to get is that in his view function it says: def upload_csv(request): data = {} if "GET" == request.method: return render(request, "myapp/upload_csv.html", data) # if not GET, then proceed but when I am printing request.method: def upload_csv(request): print request.method it says "GET" not "POST". My doubt is, if the request.method is GET then why the code is not skipping the "try-except" block and how is it processing the csv file? when the HTML form method is set as "post", why is it showing request.method as "get" ? I have looked for this and this (which is somehow related to my question) but there is no final answer on these questions. I have also tried the append slash redirect by typing the proper URL but the request.method remains "GET". Can anyone clarify this? -
Django DRF JWT authentication get, refresh, verify token
I have simple Django DRF application setup which I have implemented JWT authentication. I used the Django REST framework JWT documentation I can successfully get a token using the following notation used in the documentation: $ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/ However, when I try using this other variation, I get an error: $ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/ The error I get is: {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} I also had the same error when trying to refresh or verify the token: Refresh: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/ Verify: $ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-verify/ I was adding the token as follows: curl -X POST -H "Content-Type: application/json" -d '{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NDg5MjIsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.T5h_PSvzvKOZCPTS60x5IUm3DgAsRCRmbMJeGWZk3Tw"}' http://localhost:8800/api-token-refresh/ Am I perhaps adding the token incorrectly? Does it need some other formatting with quotes?