Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.utils.datastructures.MultiValueDictKeyError: 'file'
Hey i got this function to save file into folder. @csrf_exempt def SaveFile(request): file=request.FILES['file'] file_name=default_storage.save(file.name,file) return JsonResponse(file_name,safe=False) Firstly it worked fine, i managed to upload image. But after few tries it stopped working showing the error like this: django.utils.datastructures.MultiValueDictKeyError: 'file' [22/Aug/2022 15:58:34] "POST /events/savefile HTTP/1.1" 500 72933 I upload it with postman, post method-body-form-data, no idea where is the problem. I read some posts about that, tried to add get after file=request.FILES['file'], but didnt worked. Any advice where could be the problem? -
Assign RBAC role to ManagedIdentity from python function
I have an azure python function which creates bunch of resources and after they are created, I need to assign some roles to Web App hosted on Azure so it can access those newly created resources and that web app use System Assigned Managed Identity. That Azure python function also use system assigned Managed Identity. If I will use code credential = ManagedIdentityCredential() this will return credentials for my azure python function. How can I get to Managed Identity of the Web App in my azure function so I can start assigning some roles? I know I should use AuthorizationManagementClient but it need credential token and in case of system assigned managed identity, there are no parameters for ManagedIdentityCredential() so I can't point to that Web App. -
Getting an error App 'org' doesn't have a 'Topic' model when running tests in django app
I have the below function in the migrations file to add initial data to db: def add_topics(apps, schema_editor): topic_model = apps.get_model('org', 'Topic') for topic in TOPICS: topic_model.objects.get_or_create(name=topic['name'], display_name=topic['display_name']) However running tests is giving an error, in get_model LookupError: App 'org' doesn't have a 'ContextualSubTopic' model. App 'org' doesn't have a 'Topic' model. -
Best way to get the model object that has a DateTime field closest in DateTime to current DateTime
I want to make an efficient ORM query that returns the model object in which the objects datetime is the closest to the current datetime. So if the current datetime is 22/08/2022 15:00 and I have objects with datetimes of object1.datetime == 22/08/2022 15:30 and object2.datetime == 22/08/2022 15:45 I want to be able to query the DB for the object with the closest datetime which would be the object1 object. So basically I want to find the object that is closest, in the future, to the current datetime. The only solutions I've been able to think of are inefficient and involve looping and comparing multiple objects by adding them to lists etc. dt = datetime.datetime.now() objs = Model.objects.all() for obj in objs: if obj.dateTime //etc... Obviously this isn't a good solution because it's going to loop through my whole model database. How can I make this query in the most efficient way? -
What is the use of token return after login or registration from django-rest-knox?
Hy there, I work on project where I used django-rest-knox for token authentication. I have doubt that 1.How token be used that has return while registering and login. ( when i pass token in postman as like, in header section Authentication Token abcjdkkfjjrhehrjlajn@kfjdk ) this doesnot work 2.when i call logout and logoutall endpoint it say, { "detail": "Authentication credentials were not provided." } even though i pass all correct credentials. Here is the code that i follow, in setting.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( 'knox.auth.TokenAuthentication', "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication",)} REST_AUTH_TOKEN_MODEL = 'knox.models.AuthToken' REST_AUTH_TOKEN_CREATOR = 'users.authentication.create_knox_token' REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'users.serializers.CustomUserSerializer', 'TOKEN_SERIALIZER': 'users.serializers.KnoxSerializer' } in urls.py path('auth/register/',KnoxRegisterView.as_view(),name='register'), path('auth/login/',KnoxLoginView.as_view(),name='login'), path('api/auth/logout/',knox_view.LogoutView.as_view(),name='knox_login'), path('api/auth/logoutall/',knox_view.LogoutAllView.as_view(),name='knox_alllogin'), in authentication.py from knox.models import AuthToken def create_knox_token(token_model, user, serializer): token = AuthToken.objects.create(user=user) return token in serializers.py class KnoxSerializer(serializers.Serializer): """ Serializer for Knox authentication. """ token=serializers.CharField() user = CustomUserDetailsSettingsSerializer() in views.py class KnoxRegisterView(RegisterView): def get_response_data(self, user): return KnoxSerializer({'user': user, 'token': self.token}).data def perform_create(self, serializer): user = serializer.save(self.request) self.token = create_knox_token(None, user, None) complete_signup(self.request._request, user, allauth_settings.EMAIL_VERIFICATION, None) return user class KnoxLoginView(LoginView): def get_response(self): serializer_class = self.get_response_serializer() data = { 'user': self.user, 'token': self.token } serializer = serializer_class(instance=data, context={'request': self.request}) return Response(serializer.data, status=200) -
How to automatically replace a word with another?
I am currently using Django 4.0 and trying to find a way to transform the following: [year] to the current year. It needs to be automatically replaced every time [year] is found. Be it from the admin panel, from CKEDITOR, or comments, etc. I can find ways to do this when [year] is hardcoded, but I don't know how to make it work when I am posting a blog post from Django Admin, for example. To also add, I have tried using JS to transform the [year] tag to the current year. The problem with this is that it doesn't work on the page title or for search engines. They will still index the page with [year] instead of 2022, for example. Using JS works well for people, but not from a SEO perspective. Your help would be appreciated! Thanks. -
Django query if / else?
I'm building a website that displays photo albums. For that I have the following Models. class Medium(models.Model): pass class MediaSet(models.Model): media = models.ManyToManyField("Medium", related_name="sets", through="SetContent", through_fields=('set', 'medium'),) class SetContent(models.Model): is_cover = models.BooleanField(default=None, null=True) set = models.ForeignKey("MediaSet", on_delete=models.CASCADE, related_name="set_content") medium = models.ForeignKey("Medium", on_delete=models.CASCADE, related_name="set_contents") Every MediaSet(=Album) might have a cover. If it doesn't I will just use the first image in there. Now I'm trying to optimize the DB by reducing queries. I'm working on the MediaSetListView which lists MediaSets. Is it possible at the Query level to annotate or Prefetch() a cover (one Medium) depending on whether is_cover exists or not? In other words: Get a list of all mediasets and have every mediaset have a cover that is either the Medium marked as "is_cover" in SetContent or else the first Medium in SetContent. Currently I have this logic in the model, but that leads to tons of queries which I don't want. Thanks for your help. -
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)