Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - upload a file to the cloud (Azure blob storage) with progress bar
I'm following this tutorial to add a progress bar when I'm uploading a file in Django, using ajax. When I'm uploading the file to a folder using the upload_to option everything works fine. But when I'm uploading the file to Azure using the storage option - It doesn't work. i.e. when this is my model: class UploadFile(models.Model): title = models.CharField(max_length=50) file=models.FileField(upload_to='files/media/pre') It works perfect, but when this is my model: from myAzure import AzureMediaStorage as AMS class UploadFile(models.Model): title = models.CharField(max_length=50) file = models.FileField(storage=AMS) It gets stuck and not progressing. (AMS is defined in myAzure.py by): from storages.backends.azure_storage import AzureStorage class AzureMediaStorage(AzureStorage): account_name = '<myAccountName>' account_key = '<myAccountKey>' azure_container = 'media' expiration_secs = None How can I make it work? -
Unable to push migrations to Heroku from Django
I am a student, going through a tutorial to build a website with Next.js and Django/Python. I have zero experience with this stuff and it's been a painful process so far. At this point in the tutorial, I have created a Heroku account and have deployed my Django project to Heroku through git and have also created the postgreSQL database. The next step, as the dude in the video says, is to migrate the data from django into the database. I've done the whole "py manage.py makemigrations" locally and then tried to push those files to Heroku as I've read in other threads, but that doesn't work. In the tutorial, the guy just runs: heroku run python manage.py makemigrations, and it works fine. This is what happens when I try it: I don't understand what to do...I've been Googling for the last hour or so and cannot find a solution...I appreciate anyone who can help me, I'm sure it's something stupid/simple, but I am not a programmer or developer, so I have no clue at this point... -
Hello, I have a question (first time doing this), how to do calculations in Django?
I have a question (first time doing this), how to do calculations in Django? I made a separate file with "class" in which I do mathematical calculations and I would like to save them to the database and display them on the page, for example converting degrees Celsius to degrees Fahrenheit, in a separate file I do the calculations now I need to import them in Django display them on the page, save them to the database and let the user do the calculations. Thank you for your help :D -
Mimic update_or_create with json fields and disregard elements not in model
I have this model: class SomeModel(models.Model): field_1 = models.CharField(max_length=200, blank=True, null=True) field_2 = models.CharField(max_length=200, blank=True, null=True) and this function: def upload_object_values(model, json_values, keys=None): model._base_manager.update_or_create( **{key: json_values[key] for key in keys}, defaults={key: value for key, value in json_values.items() if key not in keys} ) and call it like this: upload_object_values(SomeModel, { \ 'field_1': 'val', \ 'field_2': 'val_2'}, \ ['field_2']) this basically does: SomeModel.objects.update_or_create(field_2=val_2) SomeModel.field_1 = val SomeModel.save() So far it works properly. But It throws an error if there are fields in the keys not in the model. for example: upload_object_values(SomeModel, { \ 'field_1': 'val', \ 'field_2': 'val_2', \ 'field_not_in_model': 'val_3'}, \ ['field_2', 'field_not_in_model']) this does: SomeModel.objects.update_or_create(field_2=val_2, field_not_in_model=val_3) SomeModel.field_1 = val SomeModel.save() Is there a way to disregard this field? -
How can I fix to AttributeError: 'AnonymousUser' object has no attribute '_meta'
I am trying to extend User model using OneToOneField. forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') class EmployerForm(forms.ModelForm): class Meta: model = Employer fields = '__all__' views.py: def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) employer_form = EmployerForm(request.POST, instance=request.user.employer) if user_form.is_valid() and employer_form.is_valid(): user_form.save() employer_form.save() else: user_form = UserForm(instance=request.user) employer_form = EmployerForm(instance=request.user.employer) return render(request, 'employer.html', { 'user_form': user_form, 'employer_form': employer_form }) html: <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ employer_form.as_p }} <button type="submit">Save changes</button> </form> Is there any way to fix this error? ('AnonymousUser' object has no attribute '_meta') -
Do I need Django/Flask in order to use a python library with Vue.js?
I'd like to use a python library - i.e. openpyxl - in order to produce an Excel file (with live formulae and not just hardcoded values), based on data provided by a user on a web application. I'd like openpyxl to extract the states from Vuex. Does this necessitate the usage of Django/Flask, or is there another way to run a python library in a javascript environment? -
N+1 queries in SerializerMethodField
I have this view def get_queryset(self) -> QuerySet[Good]: .... qs = ( Good.objects.values('brand_id', 'brand__name') .annotate( .... ) .prefetch_related(Prefetch('history', StocksHistory.objects.filter(Q(**subquery_filter_args)))) .order_by('-total_sales') ) return qs and serializer class ExtendedBrandSerializer(serializers.ModelSerializer): ... history = serializers.SerializerMethodField() class Meta: model = Good fields = ( ... 'history', ) def get_history(self, good: dict) -> dict: .... return StocksHistorySerializer( StocksHistory.objects.extra(select={'day': 'date( snap_at )'}) .values('day') .filter(history_filter_query) .annotate( .... ), many=True, ).data Relation: StocksHistory (*) -> (1) Good. I have N+1 queries in SerializerMethodField. How can I fix it? Perhaps there is a way to move annotate from serializer to view? The bottom line is that I also need the history key in the response, which will contain a list of these child objects. -
django is there a send_mass_mail() limit?
So, im using the send_mass_mail() function from django.core.mail module. I want to know if there is any limiting in the amount of recipients, and mails. -
Django djoser jwt auth can you add fields to jwt token payload data?
I am using django with djoser and django rest framework simple jwt for authentication, can i add fields (for example: user role, user name) to the jwt payload data? -
Django Form initial value for image field
I have a user model with username, and an imagefield. And a django form with the same fields. When user wants to edit his profile i want to populate the existing values so user doesn't have to enter them all. I tried using initial = {"username": user.username, "image": user.image} form = Form(initial=initial) Then I render the form using form.as_p in a template. Username is okay but image doesn't show. Is there any way to do it? -
How can I fix this AttributeError?('AnonymousUser' object has no attribute '_meta')
I am trying to extend User model using OneToOneField. forms.py: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'first_name', 'last_name', 'password1', 'password2') class EmployerForm(forms.ModelForm): class Meta: model = Employer fields = '__all__' views.py: def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) employer_form = EmployerForm(request.POST, instance=request.user.employer) if user_form.is_valid() and employer_form.is_valid(): user_form.save() employer_form.save() else: user_form = UserForm(instance=request.user) employer_form = EmployerForm(instance=request.user.employer) return render(request, 'employer.html', { 'user_form': user_form, 'employer_form': employer_form }) html: <form method="post"> {% csrf_token %} {{ user_form.as_p }} {{ employer_form.as_p }} <button type="submit">Save changes</button> </form> this is the AttributeError: 'AnonymousUser' object has no attribute '_meta' How can I fix it? -
Django REST get "application/x-www-form-urlencoded" and return "application/xml"
I'm writing integration with payments gateway and I have problem with sending response to provider. They are sending request with data in "application/x-www-form-urlencoded" form and are expection. Thats their request headers: {'Content-Length': '917', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept': 'application/xml', 'User-Agent': 'Apache-HttpClient/4.5.13 (Java/11.0.15)', 'Accept-Encoding': 'gzip,deflate', 'Host': '89.xxxxxxxx', 'Via': '1.1 payxxxxxx (squid/3.5.20)', 'X-Forwarded-For': '10.xxxxxx', 'Cache-Control': 'max-age=259200', 'Connection': 'keep-alive'} I don't know how to use two renderer classes in django - one for taking request and one for responding. I was trying to add parser_classes = (XMLParser,) but then it shows me error 415 as response (Unsupported Media Type). Rn I'm getting 406 - (Not Acceptable) - {"detail":"Could not satisfy the request Accept header."} Payment gateway is sending POST request. My attempt for handling it was: class ITNView(APIView): #parser_classes = (XMLParser, JSONParser) def post(self, request): body = request.data['transaction'] #form-encoded print(body) print(request.headers) return Response(request.data, content_type="application/xml") but this doesn't work. Have you an idea how can I handle application/x-www-form-urlencoded as request data and respond with XML? -
Automatic add Users to another class after authorization and how to avoid issues after changing field's names of old data
I'm using standard django.contrib.auth.models User. And I have some registered users. I want to create a class Member: class Member(models.Model): id_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="ninja") And want to relate new users with the class Member automatically. I have several questions. How can I relate the classes automatically after authorization? How can I change a field from another class, like a class Goal, where I'm using now id_user, but after creating the new class Member I need to change the name of field like id_member. So old data have old name of field - id_user, but after changing I need to give the new name id_member. I have found a solution to avoid these two questions. Like in my pic: I leave everything as it is. I do not touch old data. There is no need to create automatic connections between User and Member classes. But I still have to manually add users to the Member class. And this double link, I doubt it. Of cource, I want to know the answers of all my questions. Please, if you don’t mind dispelling my doubts. -
Django POST Request: I always end up with an Error 400 and the provided data in the request doesn't get accepted
I have a django project with the following (relevant to this question) apps: Course, Category, User (Teacher) & SubCategory. Using the Django REST Framework, I am trying to override the perform_create() method, so that certain fields of the Course Model are already preoccupied when creating a new instance. I'd like the "teacher" field to be the current user, the "category" field to be the instance of the category, which is matched by the request data "category", etc. Now whenever I execute the code, I end up with a 400 Error and it says that "This field is requied" for the teacher, category, sub_category, etc. Please find the code below: Course Model class Course(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) premium_only = models.BooleanField(default=False) duration = models.IntegerField(default=0) level = models.CharField(max_length=100) # Relationships category = models.ForeignKey( to=Category, related_name='courses', on_delete=models.CASCADE) sub_category = models.ForeignKey( to=SubCategory, related_name='courses', on_delete=models.CASCADE) teacher = models.ForeignKey( to=User, related_name='courses', on_delete=models.CASCADE) marked_as_favorite_by = models.ManyToManyField( to=User, related_name='favorite_courses', blank=True, null=True, default=None) def __str__(self): return self.name Course Views class CreateCourseView(CreateAPIView): queryset = Course.objects.all() serializer_class = CourseSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): categories = Category.objects.all() sub_categories = SubCategory.objects.all() teacher = self.request.user category = categories.get(name=self.request.data['category']) sub_category = sub_categories.get( name=self.request.data['sub_category']) serializer.save(teacher=teacher, category=category, … -
Check Selected Fields in Django
I have a form with musicial instruments: class InstrumentForm(forms.ModelForm): instruments = forms.ModelMultipleChoiceField(queryset=Instrument.objects.all()) class Meta: model = Instrument fields = ('instruments', ) That takes all instruments from model. I need to somehow check selected instruments and save them to Profile Model: class Profile(models.Model): ... instrument = models.ManyToManyField(Instrument, related_name='instruments') def __str__(self): return f'{self.user.username} Profile' I also have a dummy html page with form, it works: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-outline-dark" type="submit">OK</button> </form> But I need to check all instruments that user has selected and save them to the user profile model, how can I do this? -
Not able to change the python version in runtime.txt
I want to deploy django app using heroku and I runned this in terminal ----> git push heroku master Following error I encountered Requested runtime (Python-3.10.4) is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app I'm using python version 3.10.5 which is compatible with the heroku stack. However, when I try to change the python version in runtime.txt file from python-3.10.4 to python-3.10.5. I;m not able to!!!! It says runtime.txt is only read only file! -
Best way to divide a template by sections? (multiple queried for loops?) (Django)
I have a model which lists projects - one of these fields records a projects' state as foreign key to a status model. I would like to have a view where the projects are listed, however are divided by status, for example. <h1 class="main_title">Projects</h1> <h2>Projects with a Status of 1<h2> {% for projects in projects %} <h3>> {{ projects.name_title_working }}</h3> <p>> {{ projects.fk_state }}</p> <p>> {{ projects.genre }} <p>> {{ projects.d_conceived }} {% endfor %} <h2>Projects with a Status of 2<h2> {for loop} <h2>Projects with a Status of 3<h2> {for loop} etc. How would i query at the template level like this, or would there need to be additional steps where the querying is done at a lower level? -
What's the difference returning a QuerySet or a list of it?
Suppose I have two models Book and User with a foreign key on Book. And in one of my API endpoints I return the following QuerySet: return User.objects.get(pk=user_id).posts.all() The result is correctly rendered on the browser. If I change the line to (using a list): return list(User.objects.get(pk=user_id).posts.all()) ...the output result is the same. Since QuerySet is lazy-load (being excecuted only when evaluated), my question is: What's the difference in terms of memory or performance between the two approachs? Or will return and list have the same effect (evaluating the QuerySet)? What's the best approach I should use? I read the docs but it wasn't very clear to me what happens when the QuerySet is returned or a list of it. Extra info: I'm using Ninja API based on FastAPI, but the question would be the same for context data of a django view. Thanks in advance! -
Django or Anvil Python. Which one should I learn?
I was just researching about web development in Python. Django is a well known framework for web apps in Python but recently came to know about anvil. It seemed quite easy because of drag and drop UI. Also seem new and can be a trending technology in future. I want to learn Anvil. Should it worth it? Or Django is better? Because right now most of the projects offered by companies require them to be in Django. Anvil seems reletively new and got less community. Please give some suggesstions. -
Django orm: How to annotate a model with a related relation traversing multiple table
Lets say i have this structure class lvlOne(models.Model): name = models.CharField(max_length=255) class lvlTwo(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(lvlOne, related_name="children") class lvlThree(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(lvlTwo) is there way to annotate instances of lvlOne with a Related Manger of lvlThree, am thinking something like this obj = lvlOne.objects.annotate(grandchildren = .... ).get() obj.children.all() # all related lvlTwo instances as expected from setting related_name obj.grandchildren.all() # all related lvlThree instances Couple things i tried Using postgres specific ArrayAGG I managed to get a similar result, but its still a list of id (or name etc) Not the actual objects. Using Prefetch() and FilteredRelation() seems to apply on immedate relation only, every time the lookup traverse to another Model, the prefetch does not happen. -
How to get a value from 1-1 table related to current user
How do i get a value points from one-to-one table that related to current user on a website. In short how to get current_user_points like a current_user_id in this code views.py current_user_points = userprofiles.points current_user_id = request.user.id models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=100) telegramID = models.CharField(max_length=9, blank=True) -
django ckeditor - call data from rich text editor
does anyone know if it is possible to call data from the richtext editor in the admin panel? My views.py looks like this: def post_detail(request, slug): posting = post.objects.get(slug=slug) try: if posting.slug == 'dividend_stocks_list': data = pd.DataFrame(stocks(request)) allData=[] for i in range(data.shape[0]): temp = data.iloc[i] allData.append(dict(temp)) context_posting = { 'title': posting.title, 'date': posting.date_added, 'intro': posting.intro, 'body': posting.body, 'data': allData } except: context_posting = { 'title': posting.title, 'date': posting.date_added, 'intro': posting.intro, 'body': posting.body, } return render(request, 'post_detail.html', context_posting) next is the html {% block content %} {% load humanize %} <h1 class="title">{{ title }}</h1> <small>Posted at {{ date }}</small> <br/> <br/> <hr/> <div>{{ intro | safe }}</div> <hr/> <div>{{ body | safe }}</div> {% endblock %} {% block js %} {% endblock %} I would like to type in the rich text editor blablabla {{ data | safe }} blablabla But till now I have not figured out how to do that. Do you have any idea? Thanks in advance. Beste regards Sandro -
Referencing external variables in Django data migrations
For models, we use apps.get_model() to make sure that the migration will use the right version of the model (as it was when the migration was defined). But how do we deal with "regular" variables (not models) imported from the codebase? Suppose I want to simply modify the value of a field with a variable that I've defined somewhere in the codebase. For example, I want to turn all normal users into admins. I stored user roles in an enum (UserRoles). One way to write the migration would be this: from django.db import migrations from user_roles import UserRoles def change_user_role(apps, schema_editor): User = apps.get_model('users', 'User') users = User.objects.filter(role=UserRoles.NORMAL_USER.value) for user in users: user.role = UserRoles.ADMIN.value User.objects.bulk_update(users, ["role"]) def revert_user_role_changes(apps, schema_editor): User = apps.get_model('users', 'User') users = User.objects.filter(role=UserRoles.ADMIN.value) for user in users: user.role = UserRoles.NORMAL_USER.value User.objects.bulk_update(users, ["role"]) class Migration(migrations.Migration): dependencies = [ ('users', '0015_auto_20220612_0824'), ] operations = [ migrations.RunPython(change_user_role, revert_user_role_changes) ] But now there are problems. If some day in the future I delete the UserRoles variable (because I change the implementation) this will break migrations. So I won't be able to re-run migrations locally to re-create a database from scratch. If I modify the variable (e.g. I change the order … -
Notification in django rest API
I want to make a notice in django that when you add a new entry to the database the admin I do everything in the Django Rest API -
Django KeyError: 'password'
I am trying to update my user profile. But at the 'if data['password'] != '':' line, it's showing a KeyError at 'password'. I am understanding the data I called at request.data doesn't contain 'password', which is not making any sense. Please help me out, someone. @api_view(['PUT']) @permission_classes([IsAuthenticated]) def updateUserProfile(request): user = request.user serializer = UserSerializerWithToken(user, many=False) data = request.data user.first_name = data['name'] user.username = data['email'] user.email = data['email'] if data['password'] != '': user.password = make_password(data['password']) user.save() return Response(serializer.data)