Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
disk-cache is not happening for one-endpoint in browser + django
kindly advise why there is no client level caching is not happen when i use @method_decorator , even i am seeing cache_control attribute set as max_age in response header. and after i use method_decorator, I am not seeing as Disk-cache in the browser, due to this, everytime request is going to server, which we dont need to go request to server for particular time class WithdrawViewSet(AbstractViewSet): group_permissions = { 'GET': ( roles.xyz ) } class AbstractViewSet(ModelViewSet): http_method_names = ['get', 'options'] permission_classes = [IsAuthorizedUser] def _list(self, request, *args, **kwargs): try: response = wrapper.get(‘test_url’, timeout=50) except : raise exception return Response(data= response) @method_decorator(cache_page(“60 * 60 * 2”)) def list(self, request, *args, **kwargs): return self._list(request, *args, **kwargs) urls.py : from django.urls import re_path from test import WithdrawViewSet urlpatterns = [ re_path(r'^withdraw/$’, WithdrawViewSet.as_view(), name=‘withdraw’), ] Browser inspect : and I am not seeing as Disk-cache in the browser, due to this we everytime request is going to server, we dont need like that -
Redirecting with Additional Arguments after Script Function
I have a Django site running with Jinja2 templates where I need to create a form that takes an username variable and returns a User ID on the same page. For this, I have both a standard viewbase as well as a function in my views.py. The function takes the POST request from the HTML form on the 'List' page, transforms it into an ID using a python script stored in the app, and then redirects back to the main page which has an 'if' statement to display the text. I cannot simply render 'list.html', as additional context in the original view creates a list. The issue is, no matter what I try I cannot receive the data back on the main page. My latest error is (ignore my test values please): NoReverseMatch("Reverse for 'list' with keyword arguments '{'username': 'asdfa', 'ID': 'hi'}' not found. 1 pattern(s) tried: ['/list/$']",) My end goal is to make the '{% if 'username'} section into a modal, but until I can confirm the data is being handled, I assume I shouldn't even think about that. Here is the code: views.py class ListView(TelegramViewBase): template_name = "telegram/list.html" @method_decorator(login_required) @method_decorator(permission_required("sig.telegram.view", raise_exception=True)) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, … -
How to add mobile number validater in Django model?
def validate_mobile_number(value): if not str(value).isdigit(): raise ValidationError("Please Enter Valid Mobile Number") class ModelA(AbstractUser): mobile = models.CharField(_("Mobile"), unique=True, max_length=10,validators[validate_mobile_number,validators.MinLengthValidator(limit_value=10)]) -
(DJANGO) How to save session for user shopping cart in to restore session in next login?
guys, I create a shopping cart in Django with using session, but after logout, it removes my cart, and also I cannot see my cart on another computer . so please help me -
Why does Django not render a basic form?
I have a simple form that doesn't render on the frontend: Forms.py class PollsForm(forms.Form): poller_version = forms.ChoiceField(choices=("Question", "Information")) poller_text = forms.CharField(strip=True) poller_choice_one = forms.CharField(label='Choice one', max_length=20) poller_choice_two = forms.CharField(label='Choice two', max_length=20) Views.py from django.shortcuts import render, HttpResponseRedirect from .forms import PollsForm def raise_poll(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollsForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = PollsForm(), return render(request, 'pollinator/raise_poll.html', {'form': form}) raise_poll.html <form action="/post-poll/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py path('raisepoll/', raise_poll, name='raise_poll'), When I use {{ form.as_p }}it renders just nothing, but if I use `{{ form }} it renders the form but as string not as html elements: What do I miss? -
django.db.utils.ProgrammingError: relation "Industry" does not exist
return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "Industry" does not exist LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR... -
Django Unable to load static files - internal-nginx-static comes in URL
Hope you are all having a very good Friday! I am running a django project on nginx, and my project is each time going into this url - https://sitename.com/internal-nginx-static-location_uat/project_name/static/images/success.svg I didn't configure this internal-nginx-static, and If I load the same project on another website, it works fine, is it something I can handle in code, or I have make changes in server conf. Here is my URL.py Files from django.conf import settings from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include urlpatterns = [ path('', include('portal.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(DATA_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Django migrate command doesn't create any table on Heroku
It shows that tables are successfully created when I do heroku run -a "app-name" python manage.py migrate Running python manage.py migrate on ⬢ app_name... up, run.0000 (Free) System check identified some issues: ... Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK ... But when I create a superuser, it tells me that there is no table Any suggestions? I’m sticking in it for 3 days now so I will be grateful for any help. P.S. I use heroku postgresql hobby-dev. P.P.S. File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: auth_user My production configuration from .base import * import dj_database_url import environ DEBUG = False try: from .local import * except ImportError: pass environ.Env.read_env() env = environ.Env() DATABASES = { 'default': env.db() } -
Django finds template but doesn't render it and throws out an empty HTML page
I have a view in views.py: def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) print(uploaded_file_url) context = { 'uploaded_file_url': uploaded_file_url } return render(request, 'simple_upload.html', context) return render(request, 'simple_upload.html') Then, a url in urls.py: urlpatterns = [ path('', views.project_index, name='project_index'), path('<int:pk>/', views.project_detail, name='project_detail'), path('upload/', views.simple_upload, name='upload') ] And when I hit the route /projects/upload, instead of a form I get an empty page. However, the simple_upload.html route has this structure: {% extends "base.html" %} <h1>H</h1> {% load static %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> </form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} You can see, I'm getting a blank page. No errors are occurred. -
Why media files are not rendered and are not shown when I run the application?
I am working with Django 3.2.6 and I am just a beginner. I have one project(AwsomeWeb2) which has 4 applications(Users, Posts, PasswordReset, Contact). I have one class in Users that saves the information of user's profiles: class MyUser(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) mobile_number = models.CharField(max_length=20, unique=True, null=True, blank=True) birthday = models.DateField( null=True, blank=True) profile_photo = models.ImageField(default="images.png", null=True, blank=True,upload_to='profiles') date_joined = models.DateTimeField(auto_now_add=True, null=True, blank=True) country = models.CharField(max_length=15, null=True, blank=True) city = models.CharField(max_length=15, null=True, blank=True) region = models.CharField(max_length=15, null=True, blank=True) address = models.TextField(null=True, blank=True) postal_code = models.CharField(max_length=10, unique=True) is_active = models.BooleanField(default=True) user_email = models.EmailField(null=True, blank=True) uni_name = models.ForeignKey('University' , on_delete=CASCADE , default='university name') major_name = models.ForeignKey('Major' , on_delete=CASCADE , default='major name') def __str__(self): return f"{self.first_name} {self.last_name}" User.profile = property(lambda u : MyUser.objects.get_or_create(user = u)[0]) And I have one field as profile_photo that is for saving users' profile pictures. I have a form in forms.py which is related to this model: class MyUserProfile(forms.ModelForm): class Meta: model= MyUser fields = ( 'first_name', 'last_name', 'mobile_number', 'birthday', 'profile_photo', 'country', 'city', 'region', 'address', 'postal_code', 'user_email' ) I also add a few lines in setting.py for media files: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') And when … -
How to override the model's update method in django?
I have a class model which has some fields and I have put up unique constraints on some of those fields. Now my query is I am updating some of my classes status to cancelled, that led me to the error. duplicate key value violates unique constraint "unique-class" DETAIL: Key (class_id, calendar_date, is_cancelled, cancellation_count)=(6-9Hip523, 2021-10-27, t, 0) I want to skip this error on model level. How to do that? My custom update method is not getting called, please let me know what I am doing wrong here. my model class Meta: constraints = [ models.UniqueConstraint(fields=['class_id', 'calendar_date', 'is_cancelled', 'cancellation_count'], name='unique-class') ] def update(self, *args, **kwargs): if self.is_cancelled: try: super().update(*args, **kwargs) except: print("Classes are already cancelled.") -
how to add custom permissions and role based in django rest framework
models.py =============== from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): username = models.CharField(max_length=10, unique=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="admin_account") def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="teacher_account") def str(self): return self.user.username class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="student_account") def str(self): return self.user.username -
How to create extra option in django admin
want to create similar in Django admin for movies website extra option how i can do this ? what is best way? -
Access a view variable within a template
I have a context variable which is dynamic because of a loop I perform: context['categories'] = choices.CATEGORIES for category_type, category in context['categories']: context[category_type] = Article.objects.filter(category=category_type).count() But in the template it just prints the category type instead of the number which is on the variable but I also need type for a link: {% for type, category in categories %} <a href="{% url 'app:category' type %}">{{category}}</a> {{type}} {% endfor %} How can I access this dynamic variable in a for loop? -
django TypeErrorin admin panel bug with database (expected a number but got)
hello i'm trying to make model manytomany field. my main goal is to write a model where i can assing my users human skills. for instance, i have skills[Good judgment, Patience with others, Strong communication] and i want to assign this 3 skill to user when i am doing that i am getting error like this. Field 'id' expected a number but got <Id: luka>. luka is one of my user which i created from admin panel. this is my models file class Skills(models.Model): skill_name = models.CharField(max_length=30) def __str__(self): return self.skill_name class Id(models.Model): first_name = models.CharField(max_length=100, null=True) human_skills = models.ManyToManyField(Skills, related_name="SkillsNames") def __str__(self): return self.first_name and when i am saving this is error: -
When I run my Django app using python manage.py runserver on a different pc I get a sqlite3.OperationalError: unable to open database file
Error message 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2021-09-03 13:07:38.728939: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 2021-09-03 13:07:44.525563: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found 2021-09-03 13:07:44.525916: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303) 2021-09-03 13:07:44.533594: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: LAPTOP-673JJ4RS 2021-09-03 13:07:44.533921: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: LAPTOP-673JJ4RS 2021-09-03 13:07:44.535340: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 209, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line … -
Django - how to get id of get_or_create model instance?
assuming the following code: new_file, created = Files.objects.get_or_create( descriptor=somevalue, file_path=somevalue, file_name=somevalue, s3_backend=somevalue ) if created: new_file_id = ??? where << new_file, created >> is a tuple formed out of the model instance and a bool. At my if statement I only want to retrieve the id of new_file as string not as model instance. How can I do that? Thanks in advance -
Django/Python used two model in one html
I created movies website, using Django , I have two model first one is class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) and second is class Series(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) in view.py def home(request): user = request.user # Movies_obj = models.Movie.objects.all().order_by('-id')[:10] Movies_obj = models.Movie.objects.filter(category__in=['A']).order_by('-id')[:10] Movies_main_slider = models.Movie.objects.filter(category__in=["M"]).order_by('-id')[:10] Movies_main_suggest = models.Movie.objects.filter(status__in=["Suggest"]).order_by('-id')[:10] serial_obj = Serial seriali = models.Serial.objects.all().order_by('-id')[:10] return render(request,'index.html',{'user':user,'movies':Movies_obj,"main_slider":Movies_main_slider, "favorite":Movies_main_suggest,"serils":seriali}) def details(request,post_slug): movies_obj = Movies get_movie = Movies.objects.filter(slug = post_slug) return render(request,'Movie/movie_details.html',{"movies":get_movie}) also have two HTML file , index.html and movie_details.html , but when i add new Series not working in movies_details.html in movies_details i am using {% for i in movies %} {{ i.descritpion }} {% endfor %} and when i add series not working ,only movie models working , what is best way to used two model in one html ? created new html for series model ? -
How to implement audit trail in django?
I need to maintain the audit trail of all the actions and the user responsible for them, in Django. How should I implement it? It will also be great if I have the ability to revert my system to a previous state and replay the actions during an audit. One way is to add some sort of log in every API call. Is there more scalable way? And how to achieve database reversion? -
Which is Better Framework, in terms of handling Large Volume of Data, among Django, Flask, and FastAPI?
I want to know which python framework among Django, Flask, and FastAPI will be best in terms of performance (compute) and speed (latency), for building an API which will be able to handle database with millions if not not billions of records. So far I have studied that FastAPI is fastest in terms of speed (TechEmpower Benchmarks) but I want to know if it can handle high volume of data. -
How to implement OPA with Django microservices?
I am starting a project where there'll be a bunch of microservices in Django. I want to implement a separate Authentication and Authorization system that all the microservices will talk to for end-user auth. So, my doubts are: What approach should I take? I have looked at OPA and it seems promising but I can't seem to figure out the implementation. I also looked at some other authorization systems like Google's Zanzibar. Is it any good? -
How much people can Django's developement server handle (is suitable for 6 or 7 user at the time)?
I´m currently working on a project using Django, and everything seems to be working fine using the developement server for testing the app in one device (the same device where the command runserver is executed), and this Django project is configured with Xampp's MySQL But now I would like to test my app in several devices for acquiring information from several different users as the project main purpose is to captured certain data (the user write it manually). Would be about 6 or 7 people, so, can I move my project to a desktop computer (by example) and test my app with that amount of people using only the developement server ? or this number of users is more than the developement server can handle ? -
Access json _embedded and _links objects in Django template
I am working on a tool to print out API content (json) to an Django template, but I cannot seem to find out how I can access the _embedded and _links. Hope soneone can help views.py def get_certificate_view(request): certificates = xolphin.get_certificate_requests() context = { 'certs': certificates, } return render(request, "CreateCsr/certificates.html", context) myfunc.py: def get_certificate_requests(): api_url = "https://test-api.xolphin.com/v1/requests" r_get = requests.get(api_url, headers=headers).text data = json.loads(r_get) return data['_embedded']['requests'] my template view: {% for item in certs %} <h3>Item</h3> <p>{{item}}</p> <p>{{ item.id }}</p> <p>{{ item.domainName }}</p> <p>{{ item.validations }}</p> {% endfor %} Result of {{item}} = {'id': 960000021, 'domainName': 'test21.ssl-test.nl', 'company': 'Xolphin B.V.', 'dateOrdered': '2016-05-23T10:43:40+0200', 'validations': {'organization': {'status': False}, 'whois': {'status': False}, 'docs': {'status': False}, 'phone': {'status': False}, 'dcv': {'status': False}}, '_links': {'self': {'href': '/v1/requests/960000021'}}, '_embedded': {'product': {'id': 24, 'name': 'EV', 'brand': 'Sectigo', '_links': {'self': {'href': '/v1/products/24'}}}}} I know I can look through it in the function, but I want to loop through them inside my template view. hope that someone can help. I also know that their is an Xolhpin Python package but I don't want to relay on other packages so I want to use the API itself. Thanks in advance. Dave -
connect Django with react.js
enter code here function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="l ogo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <h1>wow sucess</h1> </header> </div> ); } I am working on Django project. so I built UI with html and bootstrap .now I want work with reactjs so how i impalement similar or existing ui in react and how I send httprequest and response from view to template -
How can we listen continous without running seperate file for RabbitMQ
In python Django micro-service, we are using rabbitMQ for internal communication,Now i have to run two terminal for a single service run manage.py run receive.py for consuming How can we combine this together to listening and run project.