Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python, Django: Test Custom Command with Mock
I have a very basic custom management command inside my django-application: management-command: from django.core.management import BaseComman class Command(BaseCommand): help = 'Just do some stuff here...' def handle(self, *args, **kwargs): # Let's pretend I'm doing something really important here!? pass test_managements.py: import django.core.management from django.core.management import call_command from django.test import TestCase from unittest import mock class TestCommands(TestCase): def test_do_something(self): with mock.patch.object(django.core.management, 'module') as mock_management: call_command('do_something', [], {}) mock_management.assert_called_once() I'm starting new with mocking inside my django-application and found some piece of code in another post here. I've tried to modify it to my use, but whenever I'm trying to run a test, it's saying that django.core.management doesn't have a module. Unfortunately there is no explanation what module stands for. The idea is to check, if the management-command gets called one single time. Does anyone has an idea or maybe did it for himself and can help me out. Unfortunately there are only a few code examples out there for mocking inside django. Thanks and have a great day! -
Django inject data after base.html
I have a base.html file which is a side bar menu. like this: <body> <div class="wrapper"> <nav id="sidebar"> <div class="sidebar-header"> <h3>Welcome!</h3> </div> <ul class="list-unstyled components"> <li class="active"> <a href="#list">List</a> </li> <li> <a href="#">Item 1</a> </li> <li> <a href="#">Item 2</a> </li> </ul> </nav> </div> </body> I also have a text file that I want to show the content. So I configured my view like this: def list(request): f = open('textFile.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} print(file_content) return render(request, "list.html", context) The destination HTML file which is going to show the data is like this: {% extends 'base.html' %} {{ file_content }} The problem is, the text file data is now showing up. and if I remove {% extends 'base.html' %} them the text file data shows up, but I lose the side bar. How can I resolve this issue? -
What could cause django's FilteredSelectMultiple right half not to display 'initial' values after page reload (Ctrl R)?
I was under the impression that if I do something like this: self.fields["xxx"].initial = termin.getXxx.all() then the widget's right half will display the value of termin.getXxx.all() And it is true, almost always. Except if I reload the page using 'Ctrl R' because then I get the right half completely empty, even though self.fields["xxx"].initial does contain the required value. What is so special about 'Ctrl R' that breaks the widget? Below the widget's code: xxx = forms.ModelMultipleChoiceField( queryset=Person.objects.none(), widget=OurFilteredSelectMultiple("XXX", is_stacked=False), required=False, ) class OurFilteredSelectMultiple(FilteredSelectMultiple): class Media: js = ( "/jsi18n/", "/static/core/admin/js/our_filtered_multi_select_widget.js", ) css = {"all": ("/static/core/admin/css/our_filtered_multi_select_widget.css",)} def render(self, name, value, attrs, renderer): """! Adding the id of the field to an hidden input. @detail These widgets HTML-elements get their id based on the id of the field. In order to use it in JS we set up this hidden parameter and get the value inside js. """ identifier = "multiple_select_id" ret = super().render(name, value, attrs, renderer) ret += f'<input type="hidden" id="{identifier}" value="{attrs.get("id")}">' return mark_safe(ret) -
Admin site for custom user model and extended user model
My Django app needs custom user model and some additional fields so I have defined them as below: Custom User Model and Manager (defined in an app called users): class CustomUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self._create_user(email, password, **extra_fields) class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email Extra model field (defined in an app called api): class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateField(auto_now_add=True) The Admin Site (defined in users app): class CustomerInline(admin.StackedInline): model = Customer readonly_fields = ('created',) @admin.register(CustomUser) class CustomUserAdmin(UserAdmin): inlines = (CustomerInline,) list_display = ('email', 'is_active', 'is_staff', 'is_superuser') list_filter = ('email', 'is_active', 'is_staff', 'is_superuser') fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ( ('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions', ) }, ), ) add_fieldsets = ( ( None, { 'classes': ('wide',), 'fields': ( 'email', 'password1', 'password2', 'is_active', 'is_staff', 'is_superuser', ), }, ), ) search_fields = ('email',) ordering = ('email',) … -
AttributeError: 'CharField' object has no attribute 'is_hidden'
i am building a form with django, and i am getting this error: 'CharField' object has no attribute 'is_hidden' but the charField actually it has the attribute, as you can see: veiws.py def update_profile(request,id): profile=Profile.objects.get(user=id) context={'profile':profile, } form = ProfileForm(request.POST or None,instance=profile) if form.is_valid(): form.save() return redirect("update_profile",id) context={'update_profile':update_profile,'form':form, } return render(request,'registration/profile.html',context) forms.py class ProfileForm(ModelForm): class Meta: model=Profile fields=('fullname','bio','profile_pic','phone_number','gender','country','address','facebook_url','instagram_url','twitter_url','linkedin_url','skype_url') widgets={ 'fullname': forms.CharField(max_length=150), 'bio':forms.Textarea(), 'profile_pic':forms.FileInput(), 'phone_number':forms.CharField(max_length=20), 'gender': forms.Select(), 'country': forms.Select(), 'address': forms.CharField(max_length=150), 'facebook_url': forms.CharField(max_length=150), 'instagram_url': forms.CharField(max_length=150), 'twitter_url': forms.CharField(max_length=150), 'linkedin_url': forms.CharField(max_length=150), 'skype_url': forms.CharField(max_length=150), } models.py class Profile(models.Model): user=models.OneToOneField(User,null=True,on_delete=models.CASCADE ,unique=True) fullname= models.CharField(max_length=150,null=True,blank=True) bio =models.TextField(null=True,blank=True) profile_pic=models.ImageField(null=True,blank=True,upload_to="images/profile/",default='static/images/profile/default-profile.jpg') phone_number=models.CharField(max_length=20,null=True,blank=True) gender= models.CharField(max_length=10,choices=GENDER,null=True,blank=True) country= models.CharField(max_length=25,choices=COUNTIERS,null=True,blank=True) address= models.CharField(max_length=150,null=True,blank=True) facebook_url= models.CharField(max_length=150,null=True,blank=True) instagram_url= models.CharField(max_length=150,null=True,blank=True) twitter_url= models.CharField(max_length=150,null=True,blank=True) linkedin_url= models.CharField(max_length=150,null=True,blank=True) skype_url= models.CharField(max_length=150,null=True,blank=True) def __str__(self): return str(self.user) Error: if self.max_length is not None and not widget.is_hidden: AttributeError: 'CharField' object has no attribute 'is_hidden' anyone can help me? Thank you!. -
Django: how to run function after changing m2m model
I have a m2m relation between two models Plot and Station. The m2m field is declared inside the Station model. When a user create/update a station or a plot, I want to run a 'download' function to create some config files (which will be used from another program) using data from the database. I added this function in the save and delete methods. But it did not work when the m2m field is changed. It seems the 'download' function is called before the m2m field is saved. I have found that adding a receiver to check m2m_changed on Station model, solves this problem (even if it means running the function twice). My issue now is that when a user delete a plot, the station will be updated in the database as expected, but I can not figure out how to run the 'download' function on the station after this has been done. stations/models.py class Station(models.Model): name = CICharField( max_length=50, unique=True, error_messages={ "unique": _("That name already exists."), }, ) ... # list of plots available for the station plots = models.ManyToManyField( Plot, blank=True, related_name="stations", ) ... def save(self, *args, **kwargs): """ """ super().save(*args, **kwargs) from .util import download_station download_station() def delete(self, … -
Not working autocomplete django rest framework in visual studio code
I have been looking for a solution for a very long time. Decided to post this so as not to lose this solution. -
Celery : different server for producer and consumer with Django
We are using Django with Celery for async task like this @app.task def my_task: # -- code here -- We want a dedicated separate server to consume this tasks. same CODE is used on consumer and producer side(All server) -
size date not saving in cartitem model but the product is saving.. Any solution how to save the size data also?
views.py def add_to_cart(request, pk): variant = request.GET.get('variant') product = Product.objects.get(pk =pk) user = request.user cart , _ = Cart.objects.get_or_create(user = user, is_paid = False) cart_item = CartItem.objects.create(cart = cart , product = product ,) if variant: variant = request.GET.get('variant') size_variant = SizeVariant.objects.get(size_name = variant) color_variant = ColorVariant.objects.get(color_name = variant) cart_item.color_variant = color_variant cart_item.size_variant = size_variant cart_item.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) models.py class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) color_variant = models.ForeignKey(ColorVariant, on_delete=models.CASCADE,null=True, blank=True) size_variant = models.ForeignKey(SizeVariant, on_delete=models.CASCADE ,null=True, blank=True) quantity = models.PositiveIntegerField(default=0) coupon = models.ForeignKey(Coupon, on_delete=models.SET_NULL, null=True, blank=True) [22/Aug/2022 16:17:38] "GET /account/add_to_cart/1/?variant= HTTP/1.1" 302 0 XXX 16049.0 -
django annotate - issue with counting nested items in the template
I have a list of checkboxes and labels for business challanges. I'd like to apply categories for each business challange but I am struggling to count number of business challange in each category. This is what I have: models.py class BusinessChallangeCategory(models.Model): title = models.CharField(max_length=300) class BusinessChallange(models.Model): title = models.CharField(max_length=300) category = models.ForeignKey(BusinessChallangeCategory, on_delete=models.CASCADE, related_name='category_business_challange') class Product(models.Model): title = models.CharField(max_length=300) business_challange = models.ManyToManyField(BusinessChallange, related_name='business_challange_product') views.py class ManualSearch(ListView): template_name = 'test.html' model = Product queryset = Product.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(ManualSearch, self).get_context_data(**kwargs) business_challange = BusinessChallangeCategory.objects.annotate(business_challange_count=Count('category_business_challange__business_challange_product')) context['business_challange'] = business_challange return context test.html <div class="filter-container" id="business-challange-list"> <strong class="f-12">Business challanges</strong><br> {% for bc_category in business_challange %} <div class="fw-bold f-12">{{bc_category.title}}</div> {% for bc in bc_category.category_business_challange.all %} <div class="form-check d-flex business-challange-item"> <input class="form-check-input" type="checkbox" value="{{bc.title}}" id="{{bc.title}}" data-filter="business_challange"> <label class="form-check-label ps-2" for="{{bc.title}}"> {{bc.title}} </label> <span class="ms-auto ps-2 text-muted f-12">{{bc.business_challange_count}}</span> #count is not working, it doesn't appear at all </div> {% endfor %} {% endfor %} </div> Any advice on what I am doing wrong and how to calculate properly each business challange in each category will be appreciated -
Django updateview a _set from a model
I have a detail view from django.shortcuts import get_object_or_404 class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = User template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def ansicht(request, pk): user = get_object_or_404(User, pk=pk) return render(request, 'SCHUK/Ansicht.html', context={'user': user}) class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' so far so amezin. My genius idea is to view user data by their username. all my models are bound to the user model class SchulverzeichnisTabelle(models.Model): Benutzer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) Konto = models.IntegerField(blank=True, null=True) S_Form = models.CharField(max_length=20, blank=True, null=True) Schulname = models.CharField(max_length=150, blank=True, null=True) etc but now I have a problems CRUD the user data as staff user. It works but it redirects the staff not the right view class SVAVerwaltung(LoginRequiredMixin, UpdateView): model = SchulverzeichnisTabelle fields = ['Konto', 'S_Form', 'Schulname', 'SAB', 'GL', 'Zuege', 'Teilstandort', 'IH', 'SSt_OGS', 'OGS_Grp', 'VK', 'Z_SW', 'Z_besG', 'U_Ausf', 'U_Org', 'Schulleitung_Vorname', 'Schulleitung_Nachname', 'Lehrer_FK', 'GL_Lehrer_FK'] template_name = 'SCHUK/SVAVerwaltung.html' context_object_name = 'SVAVerwaltung' def get_absolute_url(self): return reverse('Ansicht', args=[str(self.id)]) My goal is to have to user groups, normal and staff. normal view their own data and can only edit it, while staff can view user data and CRUD it not only edit. Is it somehow possible to get the detailview url to reverse … -
Using a class function as a variable in Django
I have this models.py file in my Django project from django.db import models from django.urls import reverse from django.utils.timezone import now class Campaign(models.Model): class Meta: db_table = 'campaign' campaign_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, default='') topic = models.CharField(max_length=255, default='') sender = models.CharField(max_length=255, default='') start_date = models.DateTimeField(default=now) is_active = models.BooleanField(default=False) draft = models.BooleanField(default=True) content = models.TextField(default='') footer = models.CharField(max_length=255, default='') unsubscribe_message = models.CharField(max_length=255, default='') @property def get_completion_percent(self): return 70 And I'm trying to use the get_completion_percent function in my views.py as a filter right here def finished_ads_view(request): queryset = Campaign.objects.filter(get_completion_percent=100) context = { 'object_list': queryset, } return render(request, 'campaigns_in_progress.html', context) But the error I'm getting is this: FieldError at /finished_campaigns/ Cannot resolve keyword 'get_completion_percent' into field. Choices are: campaign_id, content, draft, footer, is_active, name, sender, start_date, topic, unsubscribe_message Can anyone help me make this work? -
How to implement an Asynchronus function in synchrounous function
I'm creating an app, and I want my synchronous Django view function to execute an asynchronous function that saves a large number of database items. I'm doing that because I want my Django view to quickly carry out the process while some complicated things are going in the background, preventing the user from seeing the loading screen. However, it is not operating as I had anticipated. Here is my code Views.py from django.shortcuts import render import pandas as pd from .models import Visit from .task import saving_csv_in_database from .form import * import asyncio def upload_files(request): form = UploadFileForm(request.POST or None, request.FILES or None) if form.is_valid(): csvfile = request.FILES['file_name'] try: data = pd.read_csv(csvfile) except FileNotFoundError: return render(request, 'error.html') arr = data.to_dict('records') context = {'d': arr} asyncio.run(saving_csv_in_database(arr)) return render(request, 'upload.html', context) return render(request, 'record.html', {'form': form}) task.py from .models import * async def saving_csv_in_database(arr): patient_instances = [] for record in arr: patient_instance = Visit( patient=Patients.objects.create( medical_record=record['mr_number'], first_name=record['first_name'], last_name=record['last_name'], date_of_birth=record['dob'] ), date=record['date'], reason=record['reason'] ) patient_instances.append(patient_instance) Visit.objects.bulk_create(patient_instances) y= print("Hi I have entered the entries in database") return y Please let me know what's wrong, and how I can do it. -
Django for loop doesn't display
I'm running into the issue of displaying the button within for-loop tag. When I remove tags {% for user in users %} from send_friend.html, the button is displayed, when I add it again, it's gone. models.py class Friend_Request(models.Model): from_user = models.ForeignKey( User, related_name='from_user', on_delete=models.CASCADE) to_user = models.ForeignKey( User, related_name='to_user', on_delete=models.CASCADE) views.py def send_friend_request(request, pk): from_user = request.user to_user = User.objects.get(id=pk) friend_request, created = Friend_Request.objects.get_or_create( from_user=from_user, to_user=to_user) if created: return HttpResponse('friend request sent') else: return HttpResponse('friend request already sent') send_friend.html <ul> {% for user in allusers %} <h1> {% if not user.is_superuser %} <p></p> {% if user not in request.user.friends.all and user != request.user %} <a href="/send-friend-request/{{user.id}}" class="btn btn--main btn--pill" >Send Friend Requst</a> {% elif user in request.user.friends.all %} <p>You are friends!</p> {% endif %} <p></p> {% endif %} </h1> {% endfor %} </ul> -
How to run shell script on azure web app while running django app?
I want to run a shell script on the azure web hosting server while hosting the Django project my Django view contains a subprocess module code to run the shell script but I don't know which shell is used by my server bash or something else and I am unable to run that shell script. So How do I run a shell script in the azure web hosting server or any other web hosting server? I tried using python import subprocess sp = subprocess.Popen(['echo $0'], stdout=subprocess.PIPE) # or sp = subprocess.Popen(['echo', '$0'], stdout=subprocess.PIPE) # or sp = subprocess.Popen(['echo $0'], stdout=subprocess.PIPE, shell=True) # or sp = sp = subprocess.Popen(['echo', '$0'], stdout=subprocess.PIPE, shell=True) x=sp.communicate() # send response to me or print(x) to know which bash is used by my hosting server but get nothing. -
How can I enforce inheritance in my Django models? [closed]
In my Django app, I have an abstract model called MyModel that has e.g. created_at and updated_at fields. I want all the models in my project to subclass MyModel rather than using django.db.models.Model directly. We have several developers on our app, so I want to use some sort of linter or CI check to enforce that this happens. Is there a flake8 plugin, or something similar, I can use to enforce this inheritance? -
ImageField django
I have a problem with the image uploading from form (when i upload image from admin panel it works). Image just dont uploading, without any feedback and log. Help me pls My view.py: def class_article_create(request, URLcodenumber): print(URLcodenumber) if request.method == 'POST': model = Article() form = ArticleForm( request.POST, instance=model ) print(request.method) new_article = form.save(commit=False) new_article.codenumber = Classes.objects.filter( codenumber=URLcodenumber )[0] new_article.pub_date = date.today() print(new_article.id) if form.is_valid(): new_article.save() return HttpResponseRedirect(f'/class/{URLcodenumber}') return render( request, 'blogpage\\create_article.html', { 'clsName': f'Параллель {URLcodenumber}', 'codenumber': URLcodenumber, 'form': ArticleForm() } ) My models.py: class Article(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) headline = models.CharField( max_length=50, default='Нет заголовка' ) text = models.TextField( max_length=600, ) image = models.ImageField( upload_to='images/', blank=True ) pub_date = models.DateField() codenumber = models.ForeignKey( 'Classes', on_delete=models.CASCADE ) create_article.html {% extends "blogpage\layout\base.html" %} {% load static %} {% block title %} Добавление ответа {% endblock title %} {% block nav %} <div class="classname-div"> <p class="cls-name" align="center">{{clsName}}</p> </div> <a href='{% url "classpage_articles_preview" URLcodenumber=codenumber %}'> <button class="btn-to-page">Перейти к ответам</button> </a> {% endblock nav %} {% block content %} <form method="post" class="model-form" enctype="multipart/form-data"> {% csrf_token %} {{form.headline}} {{form.text}} {{form.image}} <button class="model-form-submit" type="submit"> Добавить </button> </form> {% endblock content %} early, there wasnt the enctype="multipart/form-data", and the problem was same media root … -
How to save/create thousands of records to postgres using queryset in Django?
I want to store thousands of records in the '''Student''' table which has '''id_s2_users''' foreign key field. I tried without having foreign key it works smooth but when I added fk constraint it becomes very very slow and took more than 20mins to store 500 records and same without fk took only few seconds. models - Below models are from different apps ./users/models.py class Users(models.Model): id = models.IntegerField(primary_key=True) cts = models.DateTimeField(blank=True, null=True) uts = models.DateTimeField(blank=True, null=True) id_states = models.ForeignKey(States, models.DO_NOTHING, db_column='id_states', blank=True, null=True) id_user_type = models.ForeignKey(UserType, models.DO_NOTHING, db_column='id_user_type') firstname = models.TextField(blank=True, null=True) lastname = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'users' ./student/models.py class Student(models.Model): id = models.BigAutoField(primary_key=True) cts = models.DateTimeField() uts = models.DateTimeField() id_users = models.ForeignKey('users.Users', models.DO_NOTHING, db_column='id_users') num_subjects = models.IntegerField() num_teachers = models.IntegerField() class Meta: managed = False db_table = 'students' bulk_create() method - def saveCounts(cumulative_counts: pd.DataFrame, model: django.db.models.base.ModelBase) -> None: records = cumulative_counts.to_dict('records') model_instances = [model( cts=timezone.now(), uts=timezone.now(), id_users=Users.objects.get( id=record['id_users']), num_subjects=record['num_subjects'], num_teachers=record['num_teachers'], ) for record in records] model.objects.bulk_create(model_instances) -
TypeError: ForeignKey(<class 'itertools.product'>) is invalid [closed]
I am new in Python / Django. I am unable to run any commands and the terminal produces the same error every time. I want to create a migration and write in terminal python manage.py makemigrations but it didn't work. how can I solve this problem my model looks like this from itertools import product from tkinter import CASCADE from django.db import models class Promotion(models.Model): desciption = models.CharField(max_length=255) discount = models.FloatField() class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey(product, on_delete=models.SET_NULL, null=True,related_name='+') class Product (models.Model): title = models.CharField(max_length=255) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Customer (models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE,'Bronze', MEMBERSHIP_SILVER, 'Silver', MEMBERSHIP_GOLD, 'Gold') ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) membership = models.CharField(max_length=1,choices=MEMBERSHIP_CHOICES,default=MEMBERSHIP_BRONZE) class Order(models.Model): PENDING = 'P' COMPLETE = 'C' FAILED = 'F' PAYMENT_CHOICES = [ (PENDING, 'Pending', COMPLETE, 'Complete', FAILED, 'Failed') ] payment_status = models.CharField(max_length=1,choices=PAYMENT_CHOICES) placed_at = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey(Customer,on_delete=models.PROTECT) class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) customer = models.OneToOneField(Customer,on_delete=models.CASCADE,primary_key=True) class OrderItem(models.Model): order = models.ForeignKey(Order,on_delete=models.PROTECT) product = models.ForeignKey(Product,on_delete=models.PROTECT) quantity = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=6,decimal_places=2) when I … -
Extend django-invitations + django-allauth account adapter
I'm using django-allauth and django-invitations. Following django-allauth's docs, I have created a custom adapter so I can override the get_signup_redirect_url method from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): # custom redirects here And then in my settings file I have ACCOUNT_ADAPTER = 'accounts.adapter.MyAccountAdapter' I'm also using django-invitations, whose docs say that for integrating with allauth, I need to set ACCOUNT_ADAPTER = 'invitations.models.InvitationsAdapter' This obviously causes a problem because then I'm no longer using my custom adapter. How can I integrate django-allauth and django-invitations while also overriding the adapter get_login_redirect_url method? -
Django-postgres-extra package ENGIN error (table Partitioning)
i have two large tables in my database that change every day at 6AM , and I want to archive the most recent month , i decided to use table partitioning to store every day's data in partition , i installed django-postgres-extra and i'm getting this error when i run the server note that : i have two databases one for users , and the other one 'prev' for my app the tables that I want to archive are in prev I'm using the extension PostGis on 'prev' can you help me please ? here is my settings.py : > DATABASES = { > 'default':{ > }, > 'prev': { > 'ENGINE':'psqlextra.backend', > 'NAME': '[database_name]', > 'USER': '[username]', > 'PASSWORD': '[Password]', > 'HOST': 'localhost', > }, > 'users': { > 'ENGINE': 'django.db.backends.postgresql', > 'NAME':'[database_name]', > 'USER': '[username]', > 'PASSWORD': '[Password]', > 'HOST': '127.0.0.1', > } } POSTGRES_EXTRA_DB_BACKEND_BASE = 'django.contrib.db.backends.postgis' DATABASE_ROUTERS=['user.router.AuthRouter' ,'prevision.router.PrevRouter'] error : $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/user/Bureau/vig/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/user/Bureau/vig/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in … -
Can't check if a model field is true or false in Django template
I'm fairly new to Django and I want to create a photo gallery website to show some photos. I want to check in my template whether the image has field is_wide or is_tall set to True so it could be displayed differently, but for some reason I couldn't do that with {% if image.is_tall == True %}. I tried setting it to 1 instead of True but it didn't work. My template.html: <div class="photo-grid"> {% for i in image|dictsort:'pub_date' %} {% if image.is_tall == True %} <div class="card card-tall" style="background-image:url('{{i.image.url}}')"> {{i.title}} </div> {% elif image.is_wide == True %} <div class="card card-wide" style="background-image:url('{{i.image.url}}')"> {{i.title}} </div> {% else %} <div class="card" style="background-image:url('{{i.image.url}}')"> {{i.title}} </div> {% endif %} {% endfor %} </div> models.py: class Image(models.Model): title = models.CharField(max_length=300) image = models.ImageField(null=True, blank=True, upload_to='images/') pub_date = models.DateTimeField('Date published', default=timezone.now) is_tall = models.BooleanField('Is it tall', null=False) is_wide = models.BooleanField('Is it wide', null=False) views.py: def gallery(request): image = Image.objects.all() return render (request, 'photo_app/gallery.html', context={'image': image}) -
Django template system to generate runnable programs
I'm considering using Django template system for a pretty peculiar use case and I'm looking for some guidance. I have an app which allows users to solve programming problems by submitting a code solution. The app allows users to write programs in several languages, including Python, JS/TS, and C. Each problem is associated with a suite of test cases meant to verify the correctness of the submitted solution. My app combines the user code and the test cases' code into a program that is run by a sandboxed environment. Right now, the way the submitted code and the test cases are combined is hard-coded and looks roughly like this: def get_testcase_execution_block( testcase: ExerciseTestCase, execution_results_list_identifier: str ) -> str: results_dict = get_random_identifier() exception_identifier = get_random_identifier() return ( f"try:\n" + f" {testcase.code}\n" + f" {results_dict} = {{'passed': True, 'id': {testcase.pk}}}\n" + f"except Exception as {exception_identifier}:\n" + f" ex_type, ex_value, ex_traceback = sys.exc_info()\n" + f" trace_back = traceback.extract_tb(ex_traceback)\n" + f" stack_trace = list()\n" + f" for trace in trace_back:\n" + f' stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))\n' + f" {results_dict} = {{'passed': False, 'id': {testcase.pk}, 'error': ex_type.__name__ + ': ' + … -
How to ORM filter a query with parameter list exactly?
I have a query filter query_1 = Model.objects.filter(param = param) I need to filter this list to another ORM and return true or flase only if all the data in the query_1 is in the second query. Like, query_2 = AnotherModel.objects.filter(field__in=query_1) return True only if all the objects in the query_1 list is in the query_2. -
Non ORM Backend in Django
I'm working with a database that I can't alter, it doesn't have PK or FK which makes it difficult to interact with it using ORM Backend in Django. So I want to know if non ORM Backend in Django offers the same flexibility? Here is an example using ORM backend : <div class="table-responsive"> <table id="table_devis" class="table table-hover "> <thead class="table-dark"> <tr> <th scope="col">Referance</th> <th scope="col">Date de creation</th> <th scope="col">Date d'expiration</th> <th scope="col">Client</th> <th scope="col">Total</th> <th scope="col">Commercial</th> </tr> </thead> <tbody> {% for dev in devis %} <tr> <th scope="row"><a href="{% url 'view_devis' dev.pk %}">DV{{dev.id }}</a></th> <td>{{ dev.date_ecriture }}</td> <td>{{ dev.date_expiration }}</td> <td>{{dev.client.nom}}</td> <td>{{ dev.total}} DH</td> <td>{{ dev.commercial.first_name}}</td> </tr> {% endfor %} </tbody> </table> </div> Can I do something similar using non ORM backend in Django???