Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django- createview with url parameter redirects to the same view without parameter in url and shows error
I have created a view with a generic view createview, to this view I pass a parameter by url, I have a form, but after clicking on the submit button it is redirected to the same url without parameter and shows error, I have tried to see if the form is invalid using "form_invalid" but it doesn't go there, it doesn't go to "form_valid" either and the "get_success_url" doesn't work, I don't know what's wrong. enter image description here url.py app_name = 'gestionAsignacion' urlpatterns = [ path('asignacionContact/<int:pk>',AsignacionCreateView.as_view(), name='asignacion_contact'), path('detalle/asignacion/<int:pk>',descargarAsignacion.as_view(), name='descargar_asignacion'), path('asignacionGeneral/',asignacionGeneral.as_view(), name='asignacion_general'), ] view.py class AsignacionCreateView(CreateView): model=AsignacionContact form_class=AsignacionForm template_name='gestionAsignacion/asignacion_contact.html' # success_url = reverse_lazy('gestionAsignacion:asignacion_general') def get_initial(self): # call super if needed return {'idasignacion_general': self.kwargs['pk']} def form_valid(self, form): print('hola form_valid') isvalid = super().form_valid(form) return isvalid def form_invalid(self, form): print ("form is invalid") return super().form_invalid(form) def get_success_url(self): return HttpResponseRedirect(reverse('gestionAsignacion:asignacion_general')) def get_context_data(self, **kwargs): # Llame primero a la implementación base para obtener un contexto context = super().get_context_data(**kwargs) # Agregar un QuerySet de todos los libros context['asig_general'] = AsignacionGeneral.objects.get(id=self.kwargs['pk']) context['object_list'] = AsignacionContact.objects.filter(idasignacion_general=self.kwargs['pk']) return context model.py class AsignacionContact(models.Model): id = models.IntegerField(primary_key=True) idasignacion_general = models.ForeignKey('AsignacionGeneral', models.DO_NOTHING, db_column='idasignacion_general') nombre_asignacion = models.CharField(max_length=100, blank=True, null=True) fecha_inicio = models.DateField(blank=True, null=True) fecha_fin = models.DateField(blank=True, null=True) observacion = models.CharField(max_length=255, blank=True, null=True) def __str__(self): … -
Django AWS S3 EB Max file upload
Hope everyone is well. When I upload a file greater than FILE_UPLOAD_MAX_MEMORY_SIZE I don't get any error it just gives me "This site can’t be reached". I have post conditions to check if the file is above this size and return an error message if it is, works in local using S3 but does not work on EB. Does anyone know why this is a problem on EB and not in local? If you need any further information please let me know. if 'document_file' in request.FILES: megabytes = 2621440 file = request.FILES['document_file'] if file.size > megabytes: raise Exception(f"{file.name}, cannot upload as the file is greater than 2.5mb") Thanks in advance, Thomas -
How do you display model attribute in a table within am html file?
I have a project and a task model and I want to make a table in a detail html that displays the tasks in the project. I've tried doing <table> <tr> <th>Name</th> <th>Assignee</th> <th>Start Date</th> <th>Due Date</th> <th>Is compeleted</th> </tr> <tr> <td>{{ task.name }} </td> <td>{{ task.assignee }}</td> <td>{{ task.start_date }}</td> <td>{{ task.due_date }}</td> <td>{{ task.is_completed }}</d> </tr> </table> but it just shows the table headers and not its content here is my task model from django.db import models from django.conf import settings from django.urls import reverse # Create your models here. class Task(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( "projects.Project", related_name="tasks", on_delete=models.CASCADE, ) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="tasks", on_delete=models.SET_NULL, ) def __str__(self): return self.name def get_absolute_url(self): return reverse("show_my_tasks") -
where puting ForeignKey in django?
one of the questions that came to my mind is that in a many-to-one relationship in Django, where should the foreign key be located? I mean, it should be in many or in part one? For example, we have two classes, post and comment: in this case, where should the ForeignKey be located in the comment or post class? post model : class post(models.model): created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ManyToManyField("PostCategory", blank=True) caption = models.CharField(max_length=2000) comment model : class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'), on_delete=models.CASCADE) text = models.TextField() Now here is the comment field where the foreign key should be defined? -
'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name When using PasswordResetConfirmView
I learned tutorial Django was 3.0.0 and I am with 4.0.1 now. I try to use that module but it not working . I can see the below alert when I am trying to reset my password. Error : Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. My urls.py is given below from django.conf.urls import url from django.urls import path, reverse_lazy from Core import views from django.contrib.auth.views import PasswordChangeView, PasswordResetView, PasswordChangeDoneView, PasswordResetConfirmView from .forms import MyChangePasswordForm,MyPasswordResetForm app_name ='Core' urlpatterns = [ path('',views.home, name='home'), path('signup/',views.SignupView.as_view(),name='signup'), path('login/',views.LoginView.as_view(),name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), path('change-password/', PasswordChangeView.as_view(template_name ='Core/change-password.html',form_class=MyChangePasswordForm, success_url = reverse_lazy('Core:password_change_done')), name='change-password'), path('password-change-done/', PasswordChangeDoneView.as_view(template_name ='Core/password_change_done.html'), name='password_change_done'), path('reset-password/',PasswordResetView.as_view(template_name = 'Core/password-reset.html',form_class=MyPasswordResetForm),name='reset-password'), path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmView.as_view(success_url=reverse_lazy('Core:password_reset_confirm')),name='password_reset_confirm'), -
Send additional data to form initialisation
So I'm creating a form object using request.POST data, but want to initialise additional fields using other values. This is what i tried, it isn't working: #forms.py class InputForm3(forms.Form): url = forms.URLField(required=True) db = forms.CharField(required=False) wks = forms.CharField(required=True, initial="Sheet1") table = forms.CharField(required=False, initial="test_table") def __init__(self, wks, *args, **kwargs): self.wks=wks super().__init__(*args, **kwargs) self.cleaned_data = None def clean(self): self.cleaned_data = super().clean() print("FORM3 cleaned_data : ", self.cleaned_data) #views.py form3=InputForm3(wks="Sheet1", data= request.POST) if form3.is_valid: #remaining code #output FORM3 cleaned_data : {'url': 'https://randomurl.com', 'db': 'testdb', 'table': ''} the fields 'url' and 'db' are present directly in request.POST, HOW DO I INITIALISE THE OTHER FIELDS PLEASE HELP! -
How to configure my media url in settings.py using AWS S3
This is currently my configuration for static and media files. This works fine locally, however now, I'm trying to host them using S3. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This is also my initial S3 configuration: AWS_ACCESS_KEY_ID = '*******' AWS_SECRET_ACCESS_KEY = '*************' AWS_STORAGE_BUCKET_NAME = '*******' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Note: I'm also currently hosting my website on heroku. -
Django-Rest-Framework: Endpoint Using a Related Field ID in the URL
I have a MarketHistoryListing model that looks like the following: class MarketHistoryListing(auto_prefetch.Model): player_profile = auto_prefetch.ForeignKey(PlayerProfile, on_delete=models.SET_NULL, null=True) sales_minute = models.DecimalField( max_digits=1000, decimal_places=2, null=True) I'd like to setup an endpoint where I can get all of the MarketHistoryListing objects that below to a specific player_profile. Something like /api/market-history/<player_profile._id> I setup what I think is the correct way to do the view - but i'm not 100% sure. class MarketHistoryListingView(viewsets.ModelViewSet): serializer_class = MarketHistoryListingSerializer queryset = MarketHistoryListing.objects.all() pagination_class = LargeResultsSetPagination def get_queryset(self): return MarketHistoryListing.objects.filter(player_profile=self.kwargs['user_inventory_pk']) However, I really don't know how to do the URL. I'm assuming it will be something similar tot he following, but i'm not sure how to pass int he dynamic player profile ID. market_history_router = routers.NestedSimpleRouter( router, r'market-hitory', lookup='user_inventory' ) market_history_router.register( <player_id>, views.MarketHistoryListingView, basename=<player_id> ) Appreciate any help! -
How do properly make an if statement in html
Im supposed to write an if statement in a detail.html template that states "if project has tasks" display a table otherwise display "no tasks in project. I've tried {% if task in project %} {% if task in projects_list %} {% if tasks in project %} "displays table" {% else %} <p>no tasks for this project</p> {% endif %} here is my task model class Task(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( "projects.Project", related_name="tasks", on_delete=models.CASCADE, ) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, related_name="tasks", on_delete=models.SET_NULL, ) def __str__(self): return self.name def get_absolute_url(self): return reverse("show_my_tasks") here is the view for projects class ProjectListView(LoginRequiredMixin, ListView): model = Project template_name = "projects/list.html" context_object_name = "projects_list" -
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!