Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Store value in a variable in jinja template for later use
Hello please give a solution to my problem: I want to store a value to a variable by the below method but unable to do that {% if tags %} {% for t in tags %} {% if t.job_post_one != "hide" %} "Store the value of t.job_post_one here "` later use that value at the end of the html for filtering results based on that value. -
In Django have created custom permissions and assigned permissions to group and user but @permission_required fails
I have created a custom permission in my user model: class User(AbstractUser): first_name=models.CharField(max_length=40, null=True, blank=True) actual_user = models.CharField(max_length=20, null=True, default=None) class Meta: permissions = (("can_switch_user", "Switch user"),) I have migrated the permissions in, added the permission to a group, and have assigned the user the permission and the group. When I test to see if the user has the permission it does not. @login_required def hello(request): context = { "name": request.user.username, "actual_user": request.user.actual_user, "groups": Group.objects.all(), "permissions": request.user.user_permissions.first(), "switch_user": request.user.has_perm('users.can_switch_user')} return render(request, "testapp/hello.html", context) I have also tried the permission "users.user.can_switch_user' When I display the results via hello.html I get: Hello user1 Actual user: user1 Group: Perms: users | user | Switch user Can Switch User False Why am I not getting the correct permissions? Do I need to create a check_permissions method in my user model to make this work or am I doing something else incorrectly. -
Serving static files through a view in Django
I am following this example to add Djangos template functionality to my css files. I got it all running, however during this process I encountered a problem I am not sure what to think about. I tried to redirect the created css files to the static directory, so I could still use the {% load static %} methods. However this does not seem to be possible! For example my static URL looks as follows: STATIC_URL="/static/" Now when I create my urls as following: #in urls.py path("static/", include([path('<str:filename>', views.css_renderer), ])), And my views as following: # in views.py def css_renderer(request, filename): return render(request, 'example_website/css_templates/{filename}'.format(filename=filename), content_type="text/css") And my empty template # file location: \example_website\css_templates\basic_style.css # This file is just empty Now when I try to access the file under http://127.0.0.1:8000/static/basic_style.css I get a Page not found (404) which was raised by example_website.views.css_renderer. Now if I just change the static URL in the settings to STATIC_URL="/something_else/" then the css file is found and all is fine. Why and how is that and how might I circumvent this maybe? Thanks very much! -
Is there a way to update cart and navigate to a different page with a button?
Please i have a code which when the button Get Ticket is clicked, i want it to update the cart and navigate to the Cart page here's the code: <a href="{% url 'cart' %}"><button type="button" data-post={{post.id}} data-action="add" class="btn btn-primary update-cart">Get Ticket</button></a> from the code: <button type="button" data-post={{post.id}} data-action="add" class="btn btn-primary update-cart"> this part updates the cart but doesnt allow it to navigate to cart, when i delete it, it navigate accordingly, how do i go about it please. Thank you -
Invalid Token Error : Invalid token specified: Cannot read property 'replace' of undefined
Hi I'm using Django for the Backend and Angular for the Frontend , when I try to login I receive a Invalid Token Error : Invalid token specified: Cannot read property 'replace' of undefined , Do you know what is the problem ?? here is the sode of user.service.ts import { Injectable } from '@angular/core'; import {HttpClient,HttpHeaders, HttpInterceptor, HttpRequest, HttpHandler, HttpEvent} from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { CanActivate,Router } from '@angular/router' import { tap, shareReplay } from 'rxjs/operators'; import * as jwtDecode from 'jwt-decode'; import * as moment from 'moment'; import { environment } from '../environments/environment'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http:HttpClient, private _router: Router) { } private setSession(authResult) { const token = authResult.token; const payload = <JWTPayload> jwtDecode(token); const expiresAt = moment.unix(payload.exp); localStorage.setItem('token', authResult.token); localStorage.setItem('expires_at', JSON.stringify(expiresAt.valueOf())); } loginUser(userData):Observable<any>{ return this.http.post('http://127.0.0.1:8000/MyProjects/auth/', userData ).pipe( tap(response => this.setSession(response)), shareReplay(), ); } } interface JWTPayload { user_id: number; username: string; email: string; exp: number; } -
Celery with Redis broker and multiple queues: all tasks are registered to each queues
I am using celery with Django and redis as the broker. I'm trying to setup two queues: default and other. My tasks are working, but the settings I have configured are not working have I am expecting them to work. I'm having two related issues: celery tasks are not respecting the task_routes setting (see below). all of the celery tasks (no matter how they are defined) are registered to each of the two queues when they are started Here are the relevant parts of my code: the celery app definition file task definitions/declarations commands to start workers celery app definition: from celery import Celery from django.conf import settings from kombu import Exchange, Queue CELERY_QUEUE_DEFAULT = 'default' CELERY_QUEUE_OTHER = 'other' app = Celery('backend') app.conf["broker_url"] = f"redis://{settings.REDIS_SERVICE_HOST}:6379/1" app.conf["result_backend"] = f"redis://{settings.REDIS_SERVICE_HOST}:6379/2" app.conf["accpet_content"] = ['application/json'] app.conf["task_serializer"] = 'json' app.conf["result_serializer"] = 'json' app.conf["task_acks_late"] = True app.conf["task_default_queue"] = CELERY_QUEUE_DEFAULT app.conf["worker_send_task_events"] = True app.conf["worker_prefetch_multiplier"] = 1 app.conf["task_queues"] = ( Queue( CELERY_QUEUE_DEFAULT, Exchange(CELERY_QUEUE_DEFAULT), routing_key=CELERY_QUEUE_DEFAULT, ), Queue( CELERY_QUEUE_OTHER, Exchange(CELERY_QUEUE_OTHER), routing_key=CELERY_QUEUE_OTHER, ), ) app.conf["task_routes"] = { 'backend.core.tasks.debug_task': { 'queue': 'default', 'routing_key': 'default', 'exchange': 'default', }, 'backend.core.tasks.debug_task_other': { 'queue': 'other', 'routing_key': 'other', 'exchange': 'other', }, } app.conf["task_default_exchange_type"] = 'direct' app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Task definitions (defined in a file called tasks.py in an … -
Python gnupg verify detached file signature when both file and signature are in memory (Django ContentFile objects)
I have a django server to which two files are sent - a document, and a signature. These are both Django ContentField objects (FileObjects, to all intents and purposes, so seekable, readable, etc). I am trying to verify the signature using python gnupg's verify_data or verify_file methods (I've tried both). I've used all combinations of passing in the raw file object, converting it to a string first - etc, everything. Everytime, the output suggests that there is no valid signature. Is the only way to do this to write the files to disk, and then verify the signature? I'm trying to avoid this, since the intention is not to store the files if the signature doesn't check out. -
Django React multiple app Deploy to Heroku Module Error
I have a project with django for backend, django for part of the front end, and react for the rest of the front-end. yourenv -bin -lib -src --api (django) ---apps.py ---models.py ---... --frontend (react) ---build ---node_modules ---src ----App.css ----App.js ----... --frontendOld (django) ---apps.py ---models.py ---... --staticfiles --trydjango ---_pyache_ ---urls.py ---settings.py ---wsgi.py ---Procfile ---requirements.txt ---runtime.txt ---... --manage.py Before I had successfully deployed with the files in their current hierarchy and git init inside of trydjango, but when I went to the Heroku url there was an Application Error; the error included "cannot find module trydjango". I tried to make git init inside of yourenv instead of inside of trydjango, moved and returned the Procfile, requirements, and runtime files and am now getting this error after git push heroku master: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed I have the heroku/python and heroku/nodejs web packs attached. Procfile: release: python3 manage.py migrate web: gunicorn trydjango.wsgi --log-file - requirements.txt: asgiref==3.2.7 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 click==7.1.2 coreapi==2.3.3 coreschema==0.0.4 Django==3.0.7 django-bootstrap3==14.0.0 django-bootstrap4==2.2.0 django-cors-headers==3.4.0 django-filter==2.3.0 django-jquery==3.1.0 django-rest-registration==0.5.6 django-und==0.1.1 djangorestframework==3.11.0 djangorestframework-jsonapi==3.1.0 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==4.4.0 dominate==2.5.1 Flask==1.1.2 Flask-Bootstrap==3.3.7.1 gunicorn==20.0.4 idna==2.10 inflection==0.5.0 itsdangerous==1.1.0 itypes==1.2.0 Jinja2==2.11.2 MarkupSafe==1.1.1 PyJWT==1.7.1 pytz==2020.1 requests==2.24.0 soupsieve==2.0.1 sqlparse==0.3.1 typing==3.7.4.3 uritemplate==3.0.1 urllib3==1.25.10 … -
Returning altered text after Markdown to HTML Conversion
I'm creating my own markdown-to-html converter. In this piece of code the text should be returned bolded, but it doesn't. Here is the code: def query(request, title_name): content = util.get_entry(title_name) bold_pattern = re.compile('[(\*\*|__)]{2}(?P<bold_text>[\w\s]+)[(\*\*|__)]{2}') bold_matches = re.finditer(bold_pattern, content) new = "" for match in bold_matches: pos_x = content.find(match.group()) pos_y = pos_x+len(match.group()) new = re.sub(bold_pattern, match.group("bold_text"), content[pos_x:pos_y]) content = content.replace(content[pos_x:pos_y], f'<b>{new}</b>') mark_safe(content) return render(request, ".../entry.html",{ "content": content, "title": util.get_page_name(title_name) }) Is there something im missing before returning it to HTML? Here is my simple entry.html: {% extends ".../layout.html" %} {% block title %}{{ title }}{% endblock title %} {% block body %} {{content}} <p>Edit this page <a href="{% url 'edit' title %}">here</a></p> {% endblock body %} -
Migration error on Django + django-oauth-toolkit
I have an django application with version 2.2.13 and django oauth toolkit 1.0.0. In the effort to update to Django 3.0, I need to update the django-oauth-toolkit, but every version after version 1.0.0, I run into a migration problem because my application (oauth2) extends the abstract application (AbstractApplication) model from the oauth2_provider (from django-oauth-toolkit). from oauth2_provider.models import AbstractApplication class Application(AbstractApplication): # there are more fields added here pass This custom oauth application (oauth2) has 28 migrations that were generate inside the project itself. When we try to run all migrations from scratch (we do this on our CI Server), we get an error trying to run migration 0001 for this app: ValueError: Related model 'oauth2.Application' cannot be resolved. There is an issue similar to my problem open on the project, https://github.com/jazzband/django-oauth-toolkit/issues/778, but workaround provided does not work, and I have not found other solution to it. Thanks. -
"Authentication credentials were not provided." Django and AWS application
I am implementing an application in Django with a TokenAuthentication extension that I found here https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05 Everything works perfect in localhost but when I upload my application to AWS, postman doesn't recognize the token that I send in the headers. Is there a reason for this? I don't know if I am missing something, the response is { "detail": "Authentication credentials were not provided." } But in localhost is OK :( -
django loop static files directory
Iam trying to loop thru images in static/folder. I can loop thru images in main 'static' folder but when i put them in 'static/folder' iam not sure how to do it in html. my html lines(works when img in main 'static' folder) {% for file in files %} <img src=" {% static file %}" height="800"> <p>File name:{{ file }}</p> {% endfor %} my views.py def album1(request): images = '/home/michal/PycharmProjects/Family/gallery/static/' files = os.listdir(os.path.join(images)) context = {'files': files} return render(request, 'gallery/album1/main.html', context) If i change views to: def album1(request): images = '/home/michal/PycharmProjects/Family/gallery/static/' files = os.listdir(os.path.join(images, 'folder')) context = {'files': files} return render(request, 'gallery/album1/main.html', context) It loops filenames in 'static/folder/' as expected, but then i cant figure out how to change it in html ,as its adding file names to: /static/{{ file }} instead to /static/folder/{{ file }}. I think iam missing something or something need changing in load static on this particular page? {% load static %} # either here <img src=" {% static file %}"> # or here? -
How to run function in django on clicking item from a list?
In my template I have a list containing some items under headings of name and id and i want to add hyperlink to each of them item and when i click an item it takes it's id as argument to the function in views.py of django and run that function. Currently my templates looks like: <html> <head> <body> <table border="1" cellpadding="5" cellspacing="5"> <td>ID</td> <td>Name</td> {% for i in data%} <tr> <td>{{i.ID}}</td> <td>{{i.Name}}</td> </tr> {% endfor %} </table> </body> </head></html> -
Django project layout
I would like to change the layout of standard django project and I also run django with virtual env. How can I do it? Current project structure looks like this: app1 - __init.py__ - admin.py - apps.py - models.py - tests.py - views.py mysite - __init.py - asgi.py - settings.py - urls.py - wsgi.py db.sqlite3 manage.py .gitignore requirements.txt I would like to move these files into separate folder called src and leave some non-django files outside of the structure (things like gitignore, requirements, etc.), so the directory looks like this src app1 - __init.py__ - admin.py - apps.py - models.py - tests.py - views.py mysite - __init.py - asgi.py - settings.py - urls.py - wsgi.py db.sqlite3 manage.py .gitignore requirements.txt -
Cant filter this variable (Python)
Im using python to filter this variable a = " ".join(map(str, items)) a = {'id': 10, 'product': {'id': 10, 'name': 'Modelo Jungla', 'price': Decimal('19.50'), 'imageURL': '/images/s10_2mkhtq7.png'}, 'quantity': 1, 'digital': False, 'get_total': Decimal('19.50')} I want to get some specific part of the string, or delete some parts -
Azure-cli fails to add extensions on termux
I've installed the Azure-cli on termux. I followed this tutorial it works fine except when I attempt to setup "UP extension", with this command : $ az extension add --name db-up It gave me this error : An error occurred. Pip failed with status code 1. Use --debug for more information. -
Built-In callable as a default argument for a Django Field
I have a JSONField that I need to apply a default dictionary to. As per the documentation, I am avoiding passing the mutable dictionary to the default field. This is done by instead passing the copy method to the default argument like such: default_dict = {'some_key': 'some value'} class MyModel(models.Model): my_field = models.JSONField(default=default_dict.copy) When applying makemigrations, this is failing because of the following condition in django.db.migrations.serializer.FunctionTypeSerializer: if self.value.__module__ is None: raise ValueError("Cannot serialize function %r: No module" % self.value) I can get around this by defining a callable that returns a copy, but I think this is adding unnecessary syntax and makes it harder to read: class ADict(dict): def __call__(self): return self.copy() default_dict = ADict({'some_key': 'some value'}) class MyModel(models.Model): my_field = models.JSONField(default=default_dict) Is there a way to pass a built-in objects method as the default value for a Django field? -
How to add title without losing option selected in form select multiple ( django )
Here are my models.py: class Student(models.Model): course = models.ManyToManyField( CourseInstance) Here are my views.py: class StudentUpdate(UpdateView): model = Student fields = '__all__' student_form.html: <form action="" method="post" id = "group-form"> {% csrf_token %} <table> {% for field in form %} <div class="row"> <div class="col-md-2"> {{ field.label_tag }} {% if 'курсы:' in field.label_tag|lower %} <div> <a href="{% url 'GroupCreate'%}" id="add_group" onclick="return showAddPopup(this);">Добавить</a> </div> {% endif %} {{ field.errors }} </div> <div class="col-md-10 pull-left"> {% if 'курсы:' in field.label_tag|lower %} {% comment %} {% load widget_tweaks %} {% render_field field class="help-title-on" %} {% endcomment %} <select name="course" required id="id_course" multiple> {% with value=form.course.value %} {% for value in form.course.field.choices.queryset %} <option title="{{value}}" value="{{ value.id }}">{{ value }}</option> {% endfor %} {% endwith %} </select> {% elif 'modelfield' not in field.name %} {{ field }} {% endif %} </div> </div> {% endfor %} </table> <input type="submit" value="Submit"> When I render the form template this way, I lose the "course" selected, but the title is added. Tried to do with widget settings. I don't know how to refer to "option" in "select". How to assign: option title="{{text_value}}" with title but lose selected without title but with selected -
Javascript & Django: Event listener for form submit (Multiple forms using for loop) for AJAX
I tried posting before but I was not able to get a clear answer so I thought I would reframe it simply. My template currently uses a for loop to print the posts of a "blog" and another for loop inside that to print comments belonging to the post. Before I continue, just want to make it clear that my models and database is functioning. I even currently have a working comment section, it just keeps refreshing the page and so I would like to incorporate JS and AJAX instead. Because I have multiple posts with their own comment sections, I tried creating individual id's for each form in the loop by saying . However, I am slightly confused as to how I am supposed to create an EventListener to make sure that no matter which of these forms are pressed, it takes the correct data and sends it to the backend. Any help would be appreciated. Thank you! Code upon request is available. However, I would like to stress that it is unnecessary to ask for my model code as it works just fine. -
Reactify Django or separated frontend and backend
I would like to know why sould reactify Django or why should we use separated django backend and react frontend. which implementation is more scalelable I hope you could help me ;) -
How do I continue work on a django project I created with cmd and using sublime text?
How do I continue work on a django project after I switched off my laptop. I'm using sublime text to edit and my command prompt to runserver. I have created a virtual environment and also activate it at the beginning of my work. -
How do fix form has no attribute get for my Django form
I am displaying the filled data by filling in form fields with data filled in sessions. Previously I implemented it using class where I had self variable so form = self.get_initial_data(request) worked However trying to do it via function based view yields me this error. How do I correct it? my views.py file def get_initial_data(request): form=RegForm(initial={ 'first_name':request.session.get('first_name',''), 'last_name':request.session.get('last_name',''), 'personal_email':request.session.get('personal_email',''), 'official_email':request.session.get('official_email',''), 'permanent_address':request.session.get('current_address',''), 'current_address':request.session.get('permanent_address',''), 'pan_card_number':request.session.get('pan_card_number',''), 'aadhar_card_number':request.session.get('aadhar_card_number',''), 'loan_amount':request.session.get('loan_amount','')}) return form @login_required(login_url='login') def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): request.session['first_name']=form.cleaned_data['first_name'] request.session['last_name']=form.cleaned_data['last_name'] request.session['personal_email']=form.cleaned_data['personal_email'] request.session['official_email']=form.cleaned_data['official_email'] request.session['current_address']=form.cleaned_data['current_address'] request.session['permanent_address']=form.cleaned_data['permanent_address'] request.session['pan_card_number']=form.cleaned_data['pan_card_number'] request.session['aadhar_card_number']=form.cleaned_data['aadhar_card_number'] request.session['loan_amount']=form.cleaned_data['loan_amount'] form.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') else: if request.session.has_key('pan_card_number'): form=RegForm(get_initial_data(request)) context = {'form': form} return render(request, 'customer/index.html', context) else: context = {'form': form} return render(request, 'customer/index.html', context) My forms.py file class RegForm(ModelForm): class Meta: model=Customer fields=['first_name', 'last_name','personal_email','official_email','current_address','permanent_address','pan_card_number','aadhar_card_number','loan_amount','personal_photo','bank_statement','salary_slip','pan_card','aadhar_card'] The error I am getting AttributeError at /form/ 'RegForm' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/form/ Django Version: 3.1 Exception Type: AttributeError Exception Value: 'RegForm' object has no attribute 'get' -
Is there a way to take data from a django form and upload it to database?
I am trying to pull data from a Django form and upload it to the database. Here are my models: class Category(models.Model): category = models.CharField(max_length = 128) def __str__(self): return f"{self.category}" class Meta: verbose_name_plural = 'Categories' class Listing(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, default = None) title = models.CharField(max_length = 64) description = models.TextField(max_length = 128) bid = models.ForeignKey(Bid, on_delete = models.CASCADE, related_name = 'listing') url = models.URLField(max_length = 350, blank = True) category = models.ManyToManyField(Category, related_name='listings') watchers = models.ManyToManyField(User, blank = True, related_name='listings') So, when a user adds a new listing, they should choose from categories. Here is how I did it after trying for quite a bit: def new_listing(request): if request.method =="POST": form = ListingForm(request.POST) if form.is_valid(): bid = Bid(amount = int(request.POST['bid'])) bid.save() listing = Listing() listing.bid = bid listing.user = request.user listing.title = form.cleaned_data['title'] listing.description = form.cleaned_data['description'] listing.url = form.cleaned_data['url'] listing.save() listing = Listing.objects.reverse()[0] for category in form.cleaned_data['category']: listing.category.add(category) The issue here is that I have to first save the listing, then pull it again and manually add Categories. I am just wondering if there is a cleaner way of doing this? Or is this how it is done in Django? Cause' I had a really … -
How to retrieve data from SQLite in django (NO PYTHON SHELL)
I looked at many feed/tutorial and when I try to look at retrieving data from SQLite in Django in it always related to Python shell but I do not find any example about how to get data in python files, by this I mean for example getting all database's row in a list with which I can create class instance based on those data. Admitting I have a model looking like this: class Example(models.Model): str = models.CharField() boolean = models.BooleanField(default=False) int = models.IntegerField(default=0) And my own made class: from XXX import Example data = Example.objects.all() for row in data: Class(str=row.str , bool=row.bool, int=row.int) class Class: def __init__(self, str="", bool="False", int=0) In addition, "objects" appears colored in yellow in PyCharm, saying it can't find the meaning/origin. I can't make it work and it actually give me the following error (no idea if it is related): django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Thank you in advance ! -
DATABASE DRIVEN PWA (Progressive Web App) or Mobile App
This is a general question. My goal is to NARROW DOWN what I need to focus in learning how to code and which programming language to start with. I'm checking into PYTHON and PHP but leaning towards PHP just because I'm familiar with Joomla CMS. My goal is to create a DATABASE-DRIVEN PWA & Mobile App. Summarize the problem: all programming languages has several areas (e.g. machine learning, AI, data analysis, data science, web development, etc.). It's like academics we learned in grade school and high schools that no longer serves us in the profession we choose, agree? Case in point: How many of you are using biology or chemistry that we learned in high school? Describe what you’ve tried: I looked into HTML, PYTHON, JAVA, MySQL, SQLite, Postgre, and PHP When appropriate, show some code: This irrelevant as this is more of a GENERAL QUESTION just to narrow down where I need to focus. I only want to learn what is related to what I want to do (DATABASE-DRIVEN PWA & Mobile App), Here's the question: Is it same to assume that... if and when using or customizing a CMS like Joomla or Django... all programming languages have the …