Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is the "with" template nest-able in Django 2.2, and 3.2? HOw do I do that and work with forloop.counter as well?
I am referring to https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#with for Django 2.2 and https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#with for 3.2 Can i use them this way? {% with thStyle="font-size: 1.4em;text-align: left;background-color: #A7C942;color: #fff;border: 1px solid #98bf21;padding: 5px 7px 4px 7px;" tdStyle="font-size: 1.2em;border: 1px solid #98bf21;padding: 3px 7px 2px 7px;" alttdStyle = "font-size: 1.2em;border: 1px solid #98bf21;padding: 3px 7px 2px 7px; background-color: #EAF2D3;" %} .... {% for key, value in some_list.items %} {% with style = tdStyle # when forloop.counter|divisible:2 else it's alttdStyle %} .... {% endwith %} {% endfor %} {% endwith %} My plan is taht i need to use different td style depending whether the counter is divisible by 2 or not. This is my logic. not confident if correct. -
How do I build a server for an Android app?
How do I go about connecting my app to a server? I've literally no idea I have an application which is connected to firebase for Google sign in. Now I need to make a server to facilitate connection between people (kinda like messaging) My question is where do I write the code for backend? I have a bit of experience with Django so I reckon I can use Django for building the server but how can I go about connecting it to my application? Sorry if I'm not making sense. Guidance is appreciated. Links would be helpful. -
How to implement refresh token in django-oauth-toolkit? I'm able to get access_token but the refresh token isn't coming with it
I'm using django-oauth-toolkit with djangorestframework where our partner user will register their application and get application credentials (client id and client secret) which then used to get access token that can be used further to get our server resources. Upto now I'm able to convert those form based application registration process and other apis through rest. But while I hit for access_token only access token with expire are coming as response. Refresh token also supposed to come along the access token but it's not. What I'm missing here... Below is the sample api response for access_token And the oauth2 settings -
Gunicorn --max-requests configuration: Would the periodic workers restart kill the tasks(process) running inside it?
I have been facing memory leaks in my Django application and for some reason, I am not able to get rid of them. Here I wanted to try with Gunicorn --max-requests config to restart the gunicorn workers periodically to release the memory. I had a few concerns here before taking it to production, Would this periodic restart kill any process running inside it? Or would it wait for the worker to be idle before restarting it? I was assuming the basic philosophy will be wait it to be idle before restarting it. but I did not find documents backing this up. Any insights on this will be helpful. -
Django / Django Rest Framework ModelViewSet: __init__() takes 1 positional argument but 2 were given
I'm trying to create a custom "list" under OptionViewSet but It's giving me an error. class OptionViewSet(viewsets.ModelViewSet): serializer_class = OptionSerializer queryset = Option.objects.all() def list(self, request): queryset = Option.objects.all() serializer = OptionSerializer(queryset, many=True) return Response(serializer.data) Error __init__() takes 1 positional argument but 2 were given This works fine: class OptionViewSet(viewsets.ModelViewSet): serializer_class = OptionSerializer queryset = Option.objects.all() urls.py path('api/shipping/', include((shipping_routes.urls, 'shipping'), namespace='shipping')), routes.py routes.register(r'option', OptionViewSet, basename='option') -
TypeError: 'module' object is not iterable under nginx+uwsgi+django+centos7 Never seen before
I have an annoying problem thest days.There are errors from uwsgi.log in the project I am creating: Traceback (most recent call last): File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner Traceback (most recent call last): File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/urls/resolvers.py", line 409, in url_patterns response = get_response(request) File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/core/handlers/base.py", line 172, in _get_response Traceback (most recent call last): iter(patterns) File "/root/Envs/magicmall2/lib/python3.6/site-packages/django/urls/resolvers.py", line 409, in url_patterns TypeError: 'module' object is not iterable django.core.exceptions.ImproperlyConfigured: The included URLconf 'magic_mall.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. the project is running fine on my windows laptop.but couldn't work properly while i am deploying on server. uwsgi.ini nginx.conf -
Django app with MS Azure SAML SSO using MSAL
I have an application created using Django that uses MSAL library to authenticate with Azure AD. As I understand, MSAL uses OAuth and so far the authentication/authorization works great. Is there a way to implement authentication using SAML instead of OAuth. I came across pysaml2 library but doesn't have sufficient documentation to integrate with Azure AD. Can someone please share your thoughts. -
Django Formset Order on Template Render after Errors
I have a formset that adds new forms by javascript in diferent order in the page. someones in the bigining and others in the end. But when i save, the errors are shows in order of form-n form-n+1, etc. no in the order that i put in the hiddenfield form-N-ORDER. how i cant show in template ordered forms by the form-N-ORDER? because in the view, i cant use: for form in formset.ordered_forms: but ordered_forms not work in template. -
Pycharm unresolved references with Django
This is my 5th day learning Django. I've got a Django project working in a virtual environment using Pycharm. The problem I have is, Pycharm can't reference certain imports when they are actually working in Django without any issues. I've selected the right interpretor for the project but Pycharm cannot connect the imports with the .py files in the Django project. The selected interpretor does have Django for the virtual environment but it still doesn't work. Below are the screenshots: import works in Django but Pycharm cannot resolve reference with the correct interpretor -
Page not found (404) on django router
I have the below router router.register(r'get-customers/<int:number>', GetCustomersViewSet, basename='get-customers') when i visit http://127.0.0.1:9090/get-customers/20 I am getting the above error i am not sure what can be the problem. But when i change the router to router.register(r'get-customers', GetCustomersViewSet, basename='get-customers') and visit http://127.0.0.1:9090/get-customers It works perfectly -
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?