Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to generated HMTL Sitemap in Django
I want to create HTML sitemap in Django like enter image description here -
django-oscar-api conflict with Django's UpdateCacheMiddleware: {TypeError}cannot pickle '_io.BufferedReader' object
I implemented django's per site cache in a django-oscar project with django-oscar-api. I use LocMemCache as a cache backend. Before adding django.middleware.cache.UpdateCacheMiddleware to my middlewares, everything worked fine and I could make a request to the "basket" endpoint like this and it returned a 200 response: import requests session = session.Session() r_basket = session.get("http://127.0.0.1:8000/api/basket/") After adding the per-site caching the response has the status code 500. I debugged it and it fails in the UpdateCacheMiddleware with the following error: {TypeError}cannot pickle '_io.BufferedReader' object. Other endpoints seem to work fine, but I haven't tested them all yet. The error can also be reproduced on a freshly installed django-oscar sandbox. I pip-installed the django-oscar-api and added it to the installed apps, and the MIDDLEWARE setting looks like this: MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', # Allow languages to be selected 'django.middleware.locale.LocaleMiddleware', 'django.middleware.http.ConditionalGetMiddleware', 'django.middleware.common.CommonMiddleware', # per site caching 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', # Ensure a valid basket is added to the request instance for every request 'oscar.apps.basket.middleware.BasketMiddleware', ] My package versions are Django v.3.2.9, django-oscar v.2.2 or 3.0, django-oscar-api v.2.1.1. What object can not be pickled? Or is the order of the middlewares possibly wrong? -
Foreign Key relationship at second level
Suppose I have three models such as - class company(models.Model): companyName = models.charField() class branch(models.Model): branchName = models.charField() company = models.ForeignKey(company, on_delete=models.CASCADE) Now in the third model, that is customer I want to have unique customer per compnay so I did - class customers(models.Model): customerName = models.charField() branch= models.ForeignKey(branch, on_delete=models.CASCADE) company = models.ForeignKey(company, on_delete=models.CASCADE) class Meta: unique_together = ( ('company', 'customerName'), ) Now since the branch has already got company as a foreign field and I'm again using both branch and company in the customers model, will this form a cyclic structure, or is this a wrong way of doing it? And if I remove the company from the customers model because branch already has company as a foreign field, how can I set unique customers per company at the database level? -
Django Tempus Dominus: setting a format makes the form invalid
I have a very simple form to submit a date. By default, the date format is 'yyyy-MM-dd' and the form works. However as soon as I change format to anything (I tried False and 'LL'), I get an error message on submission: 'Enter a valid date'. So it looks like on submission the default format is used rather than the one I've set. How do I get the preferred format working? Here is the form: class DateForm(forms.Form): date_field = forms.DateField( required=True, label='The Date', widget=DatePicker( options={ 'minDate': '1900-01-01', 'maxDate': '2050-12-31', 'format': 'LL', }, ), initial='2001-01-01', ) And here is the view: def date_input(request): if request.method == 'POST': form = DateForm(request.POST) if form.is_valid(): the_date = form.cleaned_data['date_field'] print(the_date) else: form = DateForm() return render(request, 'calculators/date-input.html', { 'form': form, }) -
How to create a django rest api for django website users
I am new to django rest framework and have basic knowledge of django. I have a note taking app where user can signin add,edit and delete there notes. I want to create an drf api for user so that they can get, post, updated and delete there notes using api. I don't find any tutorial similar to my requirements on internet. Any advice/examples will be appreciated -
Slug field does not work for Bengali language in django. How to work with slug in bengali
Django slug field does not work for any other language except English. I want to work with Bengali language here is the code class Post(models.Model): title = models.CharField(max_length=140) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) content = RichTextField(default="") image = models.ImageField(upload_to="media/post") url = models.SlugField(unique=True, max_length=250, null=True, blank=True) likes = models.IntegerField(default=0) created_date = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.title}" def save(self, *args, **kwargs): # new if not self.url: slug_str = f"{self.title}-{datetime.datetime.now()}" self.url = slugify(slug_str) return super().save(*args, **kwargs) -
How to change path to file in django
I use private storage in django, files are saved in a private path. In django setting the path to the files: PRIVATE_STORAGE_ROOT_FILES = os.path.join(BASE_DIR, 'private/private_files') I declare the file path for the model: ##storage for the private files private_storage_fles = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT_FILES) And in my Model: private_file = models.FileField(blank=True, null=True, storage=private_storage_files) Now i want to copy the project to another computer for testing. However the files are not found on the new computer because the file paths are different on the new computer. Sow on computer 1 the saved instance has the following file path: c:/users/computer1/document/djangoproject/private/file.pdf But on computer 2 this path does not exist. Can i solve this problem? -
How can i print out multiple querried objets via html template
class License(models.Model): agency = models.ForeignKey(Agency, on_delete=models.CASCADE) contact_person = models.ManyToManyField(ContactPerson()) description = models.CharField("License Description", max_length=250) location = models.CharField(max_length=20) renewal_frequency = models.CharField("Renewal Frequency", max_length=20) sop = models.FileField(upload_to="sop") class Timeline(models.Model): license = models.ForeignKey(License, on_delete=models.CASCADE) last_renewed = models.DateField() due_date = models.DateField() lpo = models.FileField(upload_to="lpo") comment = models.TextField("Comment", max_length=250, null=True, blank=True) report = models.FileField(upload_to="reports", null=True,blank=True) def home(request): title = "Licences" agencies = Agency.objects.all() agent =Agency.objects.get(pk=1) licenses = License.objects.all() for license.id in licenses: timeline = Timeline.objects.select_related().filter(license_id = license.id).order_by('-id')[:1] print(timeline) {% for renewal in timeline %} <tr> <td align="center"> <a href="{% url 'licenseupdate' renewal.license.id %}" class="btn btn-default"><em class="fa fa-pencil"></em></a> <a href="{% url 'removeobject' renewal.license.id %}" class="btn btn-danger"><em class="fa fa-trash"></em></a> </td> <td> <a href="{% url 'timelines' renewal.license.id %}"> {{renewal.license.description}}</a></td> <td>{{renewal.license.location}}</td> <td>{{renewal.license.renewal_frequency}}</td> <td>{{renewal.last_renewed}}</td> <td>{{renewal.due_date}}</td> i am trying to pring out all my License models with the latest timeline related to it, but the for loop only returns one license. only one license gets displayed to my template. -
Django Reverse One-To-One relationship
I am trying to access via One-to-One reverse relationship characteristics in my django project. my models.py: class MyCustomUser(AbstractUser): username = models.CharField(max_length=50, unique="True", blank=False, primary_key=True) password = models.CharField(max_length=200, blank=False) class Researcher(models.Model): user = models.OneToOneField(MyCustomUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True) email = models.EmailField(blank=True, unique="True") in my views.py: def loginView(request): if request.method == "POST": user = authenticate(username=request.POST['username'], password=request.POST['password']) print(user.researcher.name) if user is not None: login(request, user) if user.isResearcher == True: return redirect('diagnosis:index') elif user.is_superuser == True: return redirect('diagnosis:index') return redirect('diagnosis:index') in my template: <div class="fw-bolder d-flex align-items-center fs-5">{{ user.researcher.name }} <p class="fw-bold text-muted text-hover-primary fs-7">{{ user.researcher.email }}</p> Now it shows an error with the line(views.py): print(user.researcher.name) Also, with {{ user.researcher.email }} I can't get reverse access of email field in my template. Please suggest me how can I fix this? -
Django UNIQUE constraint failed when using signals
UNIQUE constraint failed: brand_brand.slug. class Brand(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) log = models.ImageField(upload_to='brands') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.name = self.name.lower() return super(Brand, self).save(*args, **kwargs) @receiver(pre_save, sender=Brand) def create_brand_slug(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.name) class BrandForm(ModelForm): class Meta: model = Brand fields = ['name', 'log'] I am saving the brand name in small letters in the database. When am tried to save the existing brand name in the capital letter, I Got UNIQUE constraint failed: brand_brand.slug error. When tried to save the exiting brand name with all in small letters, I got the proper error 'Brand with this Name already exists.' -
Django Inline Formset Clean method not raising validation error in template?
i am using inline formset and i have use clean method but clean method not raising error and i used '{{ formset.non_form_errors }}' also. below clean method snipped print statement reaching last moment till reaching after not raising validation error. why ? if self.instance.tax not in (None, ''): if total != self.instance.tax: self.errors.append({"error":"The Sum of different Tax Breakups should be equal to total TAX rate"}) print("reaching last moment") raise forms.ValidationError("The Sum of different Tax Breakups should be equal to total TAX rate") -
Hello, I cannt write Georgian shrift, when I generate pdf , using django . My code writes black squares besides georgian letters
I generate pdf files about each models object, but in pdf, i cannt write with Georgian letters, it returns black squares. here is some code, i am using : from xhtml2pdf import pisa in my urls.py :path('pdf/', views.customer_render_pdf_view, name='costumer-pdf-view') def customer_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') customer = get_object_or_404(id, pk=pk) template_path = 'test.html' context = {'customer': customer} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename= "report.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF( html, dest=response, encoding='utf-8' ) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response -
ModuleNotFoundError: No module named 'brandscrispy_forms'
my crispy form is not working showing, ModuleNotFoundError: No module named 'brandscrispy_forms'. I think brandcrispy is the inner package of crispy forms -
No module named 'keyboard' in Pythonanywhere
I successfully installed the keyboard module with pip install keyboard. But when I run the code it says No module named 'keyboard'. All other modules run successfully after installing. I don't know what I am missing here. Any help would be appreciated. -
DJANGO: Set site_id to sites pk
I am following this tutorial for email verification.The version the author is working with is old.I got an error that said Reverse for ‘activate’ with keyword arguments ‘{‘uidb64’: b’OA’, ‘token’: ‘4tm-3fcfb375c8ba14f9a95b’} . I got that fixed through the first comment . The email got sent .But the link led to www.example.com . The second comment tells how to fix that . The comment was : For those are using Django 3, You should change some code Six is deprecated in Django 3, you can use ‘import six’ instead of ‘from django.utils import six’ To send html email, add email.content_subtype = “html” after EmailMessage Object. activate url should be path(‘activate//’, views.activate, name=’activate’), get_current_site(request) will return example.com as default when SITE_ID=1 in your settings.py. Add your site name and domail in admin site (/admin/sites/site/) and replace SITE_ID with your sites pk. But I did not understand how to set SITE_ID to my sites pk. -
Django change __str__ depends on a field
I need to show a description in the field that depends on the "TYPE" in another field and look for an ID that is at the top level. Exemple: 3 types of accounts: P - TOP LEVL S - Syntetic A - Analitic Should show a dropdown just "A" and descriprion with up level of that. P: 1. Main S: 1.1 - base 1 A: 1.1.1 - value 1 - base 1 A: 1.1.2 - value 2 - base 1 S: 1.2 - base 2 A: 1.2.1 - value 1 - base - 2 My model and data: class Plano_Conta(models.Model): id = models.CharField(max_length=12, primary_key=True) descricao = models.CharField(max_length=100) tipo = models.CharField(max_length=1, choices=TIPO_CONTA) def __str__(self): return self.id + ' - ' + self.descricao class Meta: ordering = ('id',) class Lancamento(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plano_conta = models.ForeignKey(Plano_Conta, on_delete=models.CASCADE) no_documento = models.CharField(max_length=100) data = models.DateTimeField() descricao = models.CharField(max_length=100) valor = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.CharField(max_length=1, choices=TIPO_OPERACAO) def __str__(self): return self.descricao class Meta: ordering = ('data',) database: id |descricao |tipo| -----+-----------------------+----+ 1 |Receita |P | 1.1 |Vendas Internas |S | 1.1.1|Escola |A | 1.1.2|Escritório |A | 1.2 |Vendas Externas |S | 1.2.1|Livro |A | 1.2.2|Brinquedos |A | 2 |Despesas |P | 2.1 |Fornecedores |S … -
I want to restrict multiple user logins but no previous answers are helping me?
I want to restrict multiple user logins like when a user tries to login again i want to give him a error saying you already have a active session This is how i am doing it right now my middleware.py class MySessionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) print(request.user.is_authenticated) if request.user.is_authenticated: print('here2') try: user = LoggedInUser.objects.create(user=request.user) except: user = LoggedInUser.objects.filter(user=request.user).first() print(type(user)) if not request.session.session_key: request.session.save() prev_session_key = request.user.logged_in_user.session_key print(prev_session_key) if prev_session_key: print(prev_session_key) print(request.session.session_key) print('here5') #check whether old key is same as current print('here inside user.session_key') if prev_session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() return response my models.py class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True) session_key = models.CharField(max_length=32, null=True, blank=True) But this approach is not working as previous session key always comes out to be None , please suggest changes in my approach , i tried many solutions but they didnt work -
How to get value of the field of a referenced model in django?
Say, I have defined two models like so My_CHOICE_SELECTION = ( ('Option_1', 'Option_1'), ('Option_2', 'Option_2'), ) class CustomUser(AbstractUser): user_field_1 = models.CharField(max_length=100, blank=True, null=True) user_field_2 = models.CharField(max_length=20, choices=My_CHOICE_SELECTION) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # Some Profile fields here profile_filed_1= models.CharField(max_length=100, blank=True, null=True) # Over-ride save method def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) # **** How do I get the value here for my if condition? **** if (<--Check for value in CustomUser.user_field_2 -->): # If true do something else: # Else do something else How do I get I check for value of user_field_2 of CustomUser model in my UserProfile model? I tried doing like so if CustomUser.objects.user_field_2 == 'required_value': # Do something I am getting the following error 'UserManager' object has no attribute 'user_field_2' -
How to transition from M2M created with 'through' to a M2M managed by Django
I'm working in a Project where there were multiple fields created as M2M using the through related model, however they were wrongly created by then and the related models have no additional fields, so I would like to use a regular M2M managed by Django. The existing models I have are: cass Student(models.Model): # ... other fields..." course = models.ManyToManyField( Course, related_name='students', through='StudentCourse' ) class StudentCourse(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) cass Course(models.Model): # ... other fields..." And I would like to have: class Student(models.Model): # ... other fields..." course = models.ManyToManyField(Course, related_name='students') class Course(models.Model): # ... other fields..." I'm not able to find a way in Django to do this without losing the data that was already inserted. I was thinking of renaming the tables in the same way Django does and manipulate the Django migration metadata but it is an ugly way to solve it. Is there a Django way to solve this without losing the data (or creating backup tables)? -
How do not flush django session?
My django cart based on django session, when i log out django uses flush() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True and cart is emptied. I dont want it. -
Django exclude url pattern
i have a basic django app and want to exclude a route from matching other routes with similar structure below is my urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('', views.index, name = 'index'), path('<str:handle>', views.show, name = 'blogs'), ] i want path('create'), views.create, name = 'create') to go to the create blog page, and path('<str:handle>', views.show, name = 'blogs'), to go to the details page for a blog. i get a 404 blog not found error when i navigate to http://localhost:8000/blogs/create how do i exclude the create from matching the <str:handle> for a blog detail page? -
Django bug report, different foreign key as URL parameter will cause detailed view not executing
This bug is so subtle I couldn't really find a niche way to describe it, For example I have two apps, News and Blogs In blogs.py model I have something like this: class BlogType(models.Model): blog_type = CharField(max_length=20) def __str__(self): return self.blog_type class Blogs(models.Model): title = models.CharField(max_length=20) blog_author = models.ForeignKey(User, on_delete=models.CASCADE) blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING) here a blog_type is a foreignkey defined inside the same models.py In blogs url.py from django.urls import path, re_path from . import views from .views import blogspage urlpatterns = [ path('', views.blogs, name='blogs'), re_path(r'(?P<blog_type>[\w-]+)/(?P<pk>[0-9]+)$', blogspage.as_view(), name='blogspage'), ] Here using the forignkey as a url parameter And in blogs views.py class blogspage(DetailView): model=Blogs template_name='blogs/blogspage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print('Print the object if this is executed', self.get_object()) In Django template you would pass something like: <div><a href="{% url 'blogspage' b.blog_type b.id %}">{{b.title}}</a></div> Now the news model.py you have: class NewsType(models.Model): news_type = CharField(max_length=20) def __str__(self): return self.news_type class News(models.Model): title = models.CharField(max_length=20) news_author = models.ForeignKey(User, on_delete=models.CASCADE) news_type = models.ForeignKey(NewsType, on_delete=models.DO_NOTHING) The news views, news urls, news templates, are the exactly the same as blog except the name and template name, basically replacing every single "blogs" to "news" Then here is where the bug would occur, Only … -
AWS EB CLI Django
I have successfully managed to deploy my django project on aws eb using eb cli through pycharm terminal local project on windows pc, however I would like to accesss the project via eb instance on aws console to edit some files individually instead of deploying the whole project each time. I connected to the EC2 instance of my project enviornment on the aws EC2 instance connect and brings up the elastic beantalk ec2 message however I'm unable to find my project files within this console. Is there a way to access my already deployed project with aws console, if so how? Thanks in advance -
Why are my django validators not importing?
I have a basic django project (mysite), with a single app: my_app. The app has this in models.py: from django.db import models from mysite.validators import global_file_validator from .validators import local_file_validator class Test(models.Model): file = models.FileField(validators=[global_file_validator, local_file_validator]) It's defining a single FileField that must pass 2 validators. One of the validators (global_file_validator) is more generic, so it's defined under mysite.validators, where multiple apps can use it. The other validator is specific to this app, so it's defined in this app, under my_app/validators/local_file_validator.py. As far as I can tell, everything should work, but when I try to do a ./manage.py makemigrations, I get this: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 214, in build_graph self.load_disk() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 116, in load_disk migration_module = import_module(migration_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, … -
Is it normal that manage.py runserver has better perfs than my gunicorn/nginx conf?
I have performance issues on my DRF API. The thing is that running manage.py runserver way better performance then my prod gunicorn/nginx server. I don't know if it's "normal" ? I didn't find a lot of resources to fully understand gunicorn/nginx to be able to realy optimize them correctly. I only found some medium articles like this one that talks mainly about threads and that didn't help me close that perf gap. I run : gunicorn --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/gunicorn/error.log --capture-output --log-level debug --timeout 12000 website.wsgi:application --workers 3 --threads 4 --reload & And I got this in my nginx : upstream django { server 127.0.0.1:8000; } limit_req_zone $binary_remote_addr zone=pretrainedlimit:50m rate=10r/s; server { listen 80; server_name api.ai-compare.com; # customize with your domain name client_max_body_size 20M; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; location / { proxy_pass http://django; } location /v1/pretrained/ { limit_req zone=pretrainedlimit burst=10; proxy_pass http://django; } } I test perfs with Apache Jmeter. Do you guys have good resource on the subjet ?