Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formset with request.post not initializing correctly
I am having an issue using formsets and request.POST. Whenever I initialize the formset without request.POST it works as intended, but will not send the data through as the form is never valid. If I include request.POST (as I have done on all my other forms in the view) the formset doesn't seem to initialize correctly. No data gets through, I can't see any form fields, and I get a html warning saying: (Hidden field TOTAL_FORMS) This field is required. (Hidden field INITIAL_FORMS) This field is required. Here is a very simplified version of what I am doing in my project. This is bare minimum and the project itself is much more involved. But this should be the heart of the problem I am having. The intent of this very basic form is that my formset would have 3 forms, each one initialized with a letter, 'a', then 'b', then 'c'. views.py def MyView(request): my_formset = formset_factory(my_form) my_list = ['a', 'b', 'c'] if request.method == 'POST': my_formset = formset(request.POST, initial=[{'field1':x} for x in my_list]) #If I remove 'request.POST' then the form initializes correctly, but will never pass .is_valid() if my_formset.is_valid(): print('valid') else: print('invalid') else: my_formset = formset(initial=[{'field1':x} for x in … -
python manage.py runserver in cmd
(hafi) C:\Users\User\Desktop\hafi>python manage.py runserver C:\Users\User\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\User\Desktop\hafi\manage.py': [Errno 2] No such file or directory -
Does python web frameworks like Flask/Django have a build process?
I have recently started learning CI/CD concepts. In the tutorials, they used a react website to show the build stage. I was wondering do we have a build phase for applications developed using frameworks like Django/flask? For these applications, we generally run a single command to start the application directly from source code like: python manage.py runserver python app.py Also, in general, is to possible (and okay?) for a web application not to have a build phase? Any knowledge here would be helpful. Thanks in advance! -
Django test fails to run migrations
I'm trying to run a test script, following this django doc (which is the version being used here). It quickly fails with a long stack. I've selected what's the possible culprit. File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 185, in migrate add_sistema_entidade_e_orgao_composicao(apps, sistema) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 16, in add_sistema_entidade_e_orgao_composicao user = get_user(apps) File "/home/user11/app-master/app/colegiados/migrations/0002_auto_20200128_1646.py", line 7, in get_user return User.objects.filter( File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 318, in __getitem__ return qs._result_cache[0] IndexError: list index out of range As a workaround, I modified django's query.py if qs._result_cache: return qs._result_cache[0] else: return "" Which worked, until the next error: File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/user11/app-master/app/core/migrations/0016_auto_20201120_0934.py", line 106, in migrate sistema = Sistema.objects.get(nom_alias=sistema) File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user11/app-master/en/lib/python3.8/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( __fake__.DoesNotExist: Sistema matching query does not exist. Now I'm stuck. The test_database gets created with all the tables up to these migrations' errors, with the vast majority lacking any data. Among those that are empty is the table that this last error seems to refer to. Note that I'm not the developer, I had no hand in creating the DB being used nor any of the migrations. … -
In Django, how do I add a join table relation to an existing model?
I'm using Python 3.9 and Django 3.2. I have these models. The second is a join table for the first class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') class CoopAddressTags(models.Model): # Retain referencing coop & address, but set "is_public" relation to NULL coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) is_public = models.BooleanField(default=True, null=False) I would like to actually reference the join table in my first model, so I added address_tags = models.ManyToManyField('CoopAddressTags') like so class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) types = models.ManyToManyField(CoopType, blank=False) address_tags = models.ManyToManyField('CoopAddressTags') addresses = models.ManyToManyField(Address, through='CoopAddressTags') but I'm getting this error when I run a script to generate migraitons $ python manage.py makemigrations directory SystemCheckError: System check identified some issues: ERRORS: directory.Coop.address_tags: (fields.E303) Reverse query name for 'directory.Coop.address_tags' clashes with field name 'directory.CoopAddressTags.coop'. HINT: Rename field 'directory.CoopAddressTags.coop', or add/change a related_name argument to the definition for field 'directory.Coop.address_tags'. I'm not clear what this means or how to resolve it. The goal is that when I have a "Coop" object, I can reference its addresses and whether or not those addresses are public. -
DRF request after authentication lost data
Hi i have problem about authentication in drf. Generally when I set default permission class to IsAuthenticated,request is getting authenticated but my data from post request get lost. I changed SessionAuthentication to delete function enforce_csrf #custom_auth from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return #settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'config.custom_auth.CsrfExemptSessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } #views.py @api_view(["GET", "POST"]) def give_user_teams(request): print(request.user) print(request.auth) print(request.data) current_user = User.objects.get(pk=int(request.data['user_id'])) selected_teams = current_user.teams.all() serializer = TeamSerializer(selected_teams, many=True) return Response(data=serializer.data) If i set default permission to AllowAny, after request in postman these 3 prints from the view, look like this: #with allow any: AnonymousUser None {'headers': {'Authorization': 'Token 4a1e2a6a0ee4e004f3f867910dacbc35c85bd494'}, 'user_id': 25} #with is authenticated: testuser 4a1e2a6a0ee4e004f3f867910dacbc35c85bd494 {} Is there something I'm missing? -
Get files from Aw3 and append them in a .zip in Django
I would like to download some files from Aw3 in a .zip, with all these files. I am using django==2.2.1 with boto3 library, last version. I am trying to get the files one by one, convert them with json.dump and insert them in a .zip file with generate_zip function. Not resolve nothing, I mean, it not resolve any error and it not response the .zip or something in console that I would see. Probably the .zip was not created, but I do not know because, like I told before, it not response nothing. My code is: for id_file in files: BUCKET_NAME="xxxx" BUCKET_FILE_NAME='folder/'+id_file+'/'+category+"/"+name_file s3 = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY_ID,aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,region_name='eu-west-2') s3_response_object=s3.get_object(Bucket=BUCKET_NAME,Key=BUCKET_FILE_NAME) s3_response_object['Body'] = s3_response_object['Body'].read().decode("ISO-8859-1") s3_response_object['Key'] = settings.AWS_ACCESS_KEY_ID+'/'+settings.AWS_SECRET_ACCESS_KEY location = s3.get_bucket_location(Bucket=BUCKET_NAME)['LocationConstraint'] url = "https://s3-%s.amazonaws.com/%s/%s" % (location, BUCKET_NAME, BUCKET_FILE_NAME) s3_response_object['URL'] = url file_data = json.dumps(s3_response_object, default = myconverter) resultFiles.append(file_data) full_zip_in_memory = generate_zip(resultFiles) response = HttpResponse(full_zip_in_memory, content_type='application/x-zip') response['Content-Disposition'] = 'attachment; filename="files.zip"' return response La función generate_zip def generate_zip(files): mem_zip = BytesIO() with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf: for f in files: zf.writestr(f[0], f[1]) return mem_zip.getvalue() -
Cannot add extra styles to django-ckeditor
django-ekeditor packages comes with highlight.js library for code snippets and that library comes with some pre-installed styles. As I prefer seti-ui style, I download it from highlightjs.org. Inside the downloaded package is seti-ui.min.css file and I copy it to \venv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\codesnippet\lib\highlight\styles where all other styles are and then set this in my settings.py: 'codeSnippet_theme': 'seti-ui' # based on the name of css file And it doesn't work. The editor shows the code snippet but without any style. I've tried several other pre-installed themes like monokai and foundation and they work fine. Then I noticed that seti-ui.min.css is inside a subfolder base16 in the package I downloaded from highlightjs.org, so I tried \venv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\codesnippet\lib\highlight\styles\base16 too but didn't work either. So what is the correct method to add it? -
Django/Python - update html after update with radiobutton
I have a Django app with an email box. Users can send the email by hand or let it be done automatically. To change the setting: either manual or automatic, I have creates a view to change the settings. To show the user what the current setting is, I prechecked the radio button. It looks like this: My problem is, that when the button "Update" is clicked, it does change the settings, but not the frontend for the user. So the user does not see that it is changed. So the page should be refreshed or something with the new settings, but I don't know how.. This is the code that I have now: .html <div class="form-group"> <label class="form-label">Send Emails:</label> <p></p> <input type="radio" name="update_type" value="manual" {% if view.manualSetting %}checked {%endif%}> Manual {% if view.manualSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <input type="radio" name="update_type" value="auto" {% if view.autoSetting %}checked {%endif%}> Automated {% if view.autoSetting is 1 %} ( Current setting ) {% else %} {% endif %}</input> <p></p> <button type="submit" class="btn btn-primary">Update</button> </div> views.py class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} model = AutoSendMail.objects.get(id=1) autoSetting = int(model.auto == … -
Separate array to small array by count [duplicate]
I have array like this [1,4,2,3,4,14,2,5,1,2,3,14,1,3] Now I want to separate this to small 3 arrays( last might be 1 or 2 array) [[1,4,2],[3,4,14],[2,5,1],[2,3,14],[1,3]] I think I can do this such as ,but obviously it's not clear and clean. Is there any more easy way to do this? total = [] item = [] for cnt,a in enumerate(original_arr): item.append(a) if len(item) == 3: total.append(item) item = [] total.append(item) -
Bad Request error when trying to refresh Django login access token
Trying to refresh the access token I receive from Django every few seconds, however I am getting the error message Request Method: POST Status Code: 400 Bad Request I am sending my refresh token to this endpoint: "http://127.0.0.1:8000/api/token/refresh/" This is my urls.py: from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView, TokenVerifyView) router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('', include(router.urls)), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), # path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('api/register', RegisterApi.as_view()), ] This is how I am sending my refresh token: let updateToken = async ()=> { try { let response = await axios.post('http://127.0.0.1:8000/api/token/refresh/',JSON.stringify(authTokens.refresh)) //update state with token setAuthTokens(authTokens => ({ ...response.data })) //update user state const decoded = jwt_decode(response.data.access) setUser(user => ({ ...decoded })) //store tokens in localStorage //we stringify because we can only store strings in localStorage localStorage.setItem('authTokens',JSON.stringify(response.data)) } catch(err) { //if fail, something is wrong with refresh token console.log(err.response) } } This is the error I am getting: config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: refresh: ['This field is required.'] [[Prototype]]: Object headers: content-length: "39" content-type: "application/json" [[Prototype]]: Object request: XMLHttpRequest onabort: ƒ handleAbort() onerror: ƒ handleError() onload: null onloadend: ƒ onloadend() onloadstart: null … -
( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct
This is how it is structured The code inside apps.py of accounts folder file is from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = "apps.accounts" The code inside Settings is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite.apps.accounts', ] I tried changing 'mysite.apps.accounts', to 'mysite.apps.AccountsConfig', and changing name = "apps.accounts" to name = "accounts" I am new to Django and was following How to make a website with Python and Django - MODELS AND MIGRATIONS (E04) tutorial. Around 16:17 is where my error comes up when I enter python manage.py makemigrate to the vscode terminal The error is ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Cannot import 'apps.accounts'. Check that 'mysite.apps.accounts.apps.AccountsConfig.name' is correct. Someone please help me. -
I can't make migrations between two models in Django
I have a problem with my migrations, it turns out that when I try to do python manage.py migrate I get a series of errors but the one that surprises me the most is the one from heroku: django.db.utils.IntegrityError: insert or update on table "carros_carro" violates foreign key constraint "carros_carro_cliente_id_3c6fe221_fk_Clientes_clientes_id" DETAIL: Key (cliente_id)=(1) is not present in table "Clientes_clientes" So my problem is between those two models, the bad thing is that I already replaced those models that were in my previous folders and the error continues to appear. clientes/models.py class Clientes(models.Model): tipo = models.CharField(max_length=200) TITLE = ( ('Mrs.', 'Mrs.'), ('Miss', 'Miss'), ('Mr.', 'Mr.'), ) corporacion=models.CharField(max_length=200,blank=True) titulo = models.CharField(max_length=200, choices=TITLE,default='Mr.') nombre = models.CharField(max_length=200, blank=True) apellido = models.CharField(max_length=200,blank=True) telefono = models.IntegerField(blank=True, null=True) tel = models.IntegerField(blank=True, null=True) fax = models.IntegerField(blank=True, null=True) correo = models.EmailField(max_length=200,blank=True, null=True) website=models.URLField(max_length=200,blank=True, null=True) social_media=models.CharField(max_length=200,blank=True, null=True) social_media2=models.CharField(max_length=200,blank=True, null=True) social_media3=models.CharField(max_length=200,blank=True, null=True) contacto_alternativo=models.CharField(max_length=200,blank=True, null=True) contacto_alternativo2 = models.CharField(max_length=200,blank=True, null=True) contacto_alternativo3 = models.CharField(max_length=200,blank=True, null=True) pais = models.CharField(max_length=200,blank=True, null=True) direccion=models.CharField(max_length=200,blank=True, null=True) ciudad=models.CharField(max_length=255,blank=True, null=True) estado=models.CharField(max_length=255,blank=True, null=True) zip=models.CharField(max_length=255,blank=True, null=True) fecha_registro = models.DateTimeField(default=datetime.now,blank=True, null=True) def __str__(self): return f'{self.nombre} {self.apellido}' carros/models.py class Carro(models.Model): placas=models.CharField(max_length=255, blank=True,null=True) tipo=models.CharField(max_length=255, blank=True,null=True) marca=models.CharField(max_length=255, blank=True,null=True) modelo=models.CharField(max_length=255, blank=True,null=True) año=models.IntegerField() vin=models.CharField(max_length=255, blank=True,null=True) color=models.CharField(max_length=255, blank=True,null=True) motor=models.CharField(max_length=255, blank=True,null=True) agente_seguros=models.CharField(max_length=255, blank=True,null=True) compañia_seguros=models.CharField(max_length=255, blank=True,null=True) no_politica=models.CharField(max_length=255,blank=True,null=True) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(blank=True, … -
how to render unseen notification from models using channels in django
Actually i wanted to render unseen notification into the templates from models.py using channels models.py class Notify(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.TextField(max_length=500) seen = models.BooleanField(default=False) def save(self,*args,**kwargs): channel_layer = get_channel_layer() notification_object = Notify.objects.filter(seen=False).count() data = {'count': notification_object ,'notification':self.message} async_to_sync(channel_layer.group_send)( 'notification_consumer_group', { 'type':'send_notification', 'value':json.dumps(data) }) super(Notify,self).save(*args,**kwargs) and if notification once seen then remove from notification icon . -
is there a way to integrate pixela (calendar graph) into a website through html? like what github has?
is there a way to integrate PIXELA (calendar graph) into a website through html? like what github has? the one with the contributions section. Thanks in advance! ( API docs for pixela https://docs.pixe.la/ ) -
DRF AssertionError: Expected a `time`, but got a `datetime`
I have a model: class Inspection(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name='vendor_inspections') inspection_date = models.DateField(default=date.today) inspection_time = models.TimeField(default=timezone.now) ... class Meta: unique_together = (('vendor', 'inspection_date'),) serializer: class InspectionSerializer(serializers.ModelSerializer): class Meta: model = Inspection fields = ['vendor', 'inspection_date', 'inspection_time'] and modelviewset: class InspectionModelViewSet(viewsets.ModelViewSet): serializer_class = InspectionSerializer queryset = Inspection.objects.all() I want to change data and time fields with PUT/PATCH requests or set their values manually on instance creating if it's needed, otherwise, current date & time should be saved. When I send POST request with or without inspection_time in payload I get this error: AssertionError: Expected a `time`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly. This error isn't raised if I remove inspection_time from fields in serializer Meta class. I've implemented serializer field validation method just to understand what's going on: def validate_inspection_time(self, inspection_time): raise Exception(inspection_time) Aforementioned AssertionError is raised before validate_inspection_time. Although the listed an inspection instance is saved in DB. what the problem could be? Thank you. -
Django behind NGINX reverse proxy and AWS Application Load Balancer doesn't get HTTPS forwarded from client in HTTP_X_FORWARDED_PROTO
I'm running Django on Gunicorn behind a NGINX reverse proxy, and an AWS Application Load Balancer. The ALB has 2 listeners. The HTTPS listener forwards to a Target Group in port 80, and the HTTP listener redirects to HTTPS. The ALB thus connects with an AWS ECS Cluster, which runs a task with 2 containers: one for the Django app, and another for the NGINX that acts as a reverse proxy for the Django app. Here's the configuration for the NGINX reverse proxy: upstream django { server web:8000; } server { listen 80; listen [::]:80; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_ssl_server_name on; proxy_redirect off; } } This configuration ensures that whenever the client tries to hit the website app using an HTTP request, he gets redirected to HTTPS. And everything works fine with one exception. In Django, when I run request.is_secure() I'm getting False instead of True as expected. If I run request.build_absolute_uri(), I get http://mywebsite.com and not https://mywebsite.com as expected. I already tried adding the following lines to settings.py: USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') as explained in the documentation, but it doesn't … -
How to get additional context without repeating database queries?
I want to provide extra context in my serializer in get_serializer_context. Currently I'm having to repeat the database queries that the serializer is performing by itself anyway in order to do so. Is there a way around this, to access the data that's already been queried? class MyView(generics.ListCreateAPIView): def get_serializer_context(self): context = super().get_serializer_context() # Is this somewhere I can get to it? data = self.paginate_queryset(self.filter_queryset(self.queryset)) context["extra_stuff"] = get_extra_stuff_for(data) return context -
How to fix Heroku Openai Django Deployment Error?
When deploying a new Heroku App Using a Django Docker Enviorment Inside my requirments.txt I have openai==0.11.0 When doing git push heroku master During Build I get this Error Building wheel for pandas (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for pandas (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [1803 lines of output] gcc: fatal error: cannot execute 'cc1plus': execvp: No such file or directory compilation terminated. error: command '/usr/bin/gcc' failed with exit code 1 [end of output] Building wheel for numpy (pyproject.toml): finished with status 'error' error: subprocess-exited-with-error × Building wheel for numpy (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [251 lines of output] RuntimeError: Broken toolchain: cannot link a simple C++ program. note: A compiler with support for C++11 language features is required. [end of output] Any help really appreciated. Thank You -
Django admin.TabularInline import csv function
The following code is an inline class, how to make it support the import and export functions of django-import-export。 class DataSourceTableFieldline(admin.TabularInline): # resource_class = DataSourceTableFieldForm model = DataSourceTableField list_display = ( 'column_name_cn', 'column_name_en', 'column_type', 'column_length', 'ordinal_position', 'column_is_pk') extra = 0 class DataSourceTableAdmin(admin.ModelAdmin): inlines = [DataSourceTableFieldline] list_display = ['table_name_zh', 'table_name_en', 'table_logical_name', 'table_code', 'table_sort_id'] search_fields = ['table_name_zh', 'table_name_en'] list_display_links = ['table_name_en'] -
"detail": "JSON parse error - Extra data: line 1 column 9 (char 8)" in django rest framework post request
Here is my view @api_view(["POST"]) def afficher_donnees_instantanees(request): if request.method == "POST": print(request.data) deveui = request.data["deveui"] donnees = Historique.objects.filter(infos_signal__machine=deveui, infos_signal__jour=datetime.today()).order_by("-id").first() serializer = HistoriqueSerializer(donnees) return Response(serializer.data) else: return Response({"echec": "echec"}) serializer.py class HistoriqueSerializer(serializers.ModelSerializer): class Meta: model = Historique fields = '__all__' I want to display data from my Historique model in response to a POST request, but I get the message "JSON parse error - Extra data: line 1 column 9 (char 8)". Knowing that the response code is 400. Where can this error come from please? -
Django can't get the correct url path to media file
I have a problem when I try to show the media files pictures from my database Django keeps renaming '/media/' to '/dashboard/' in the requests to my media files here is the model:` class PetPhoto(models.Model): photo = models.ImageField( upload_to='photos/', blank=True ) tagged_pets = models.ManyToManyField( Pet, ) description = models.TextField( null=True, blank=True, ) publish_date = models.DateTimeField( auto_now_add=True, ) likes = models.IntegerField( default=0, ) Here is the view class CreatePetPhotoView(auth_mixin.LoginRequiredMixin, views.CreateView): model = PetPhoto template_name = 'web/photo_create.html' fields = ('photo', 'description', 'tagged_pets') success_url = reverse_lazy('dashboard') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) ` Here is settings.py MEDIA_ROOT = BASE_DIR / 'mediafiles' MEDIA_URL = '/media/' Here is the urls.py file from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('petstagram.web.urls')), path('accounts/', include('petstagram.accounts.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django admin form multi validation
admin.py class UserControlAdmin(ExportActionMixin, admin.ModelAdmin): form = UserControlModelForm fields = ('user', 'team', 'position') forms.py class UserControlModelForm(forms.ModelForm): def clean_position(self): position = self.cleaned_data['position'].id if not isinstance(self.cleaned_data['team'], type(None)): team = self.cleaned_data['team'].id ... if p['company_group'] != t['company_group']: raise ValidationError('...') return self.cleaned_data['position'] def clean_team(self): if isinstance(self.cleaned_data['team'], type(None)): position = self.cleaned_data['position'].id if position < 4: ... raise ValidationError('...') return self.cleaned_data['team'] I get error KeyError at /admin/information/user/add/ 'position'. I found a problem that, inside clean_team doesn't have position value because position stands behind team in admin fields. How can I fix that? Is it possible to check after getting all parameters? In post request still have position parametr. -
Django multi project user management
I want to learn is there a way to keep django multi project and authenticate/authorize them with one project? For example: I have Project-B and Project-C with different operation fields like hotel automation and gas station. Both of them are my products and I want to manage them by keep licences and users in one place, in other words different project, Project-A. In Project-B and Project-C has it's own apps and apps' models so I don't want to merge them in one project, I want to keep them separate. But I want authorize/authenticate users from one place Project-A. So Project-A will be used only for management. I am planning to use OAuth toolkit for it, but in the first place I have another problem. Project-B and Project-C's apps' models have foreign key fields and many to many fields that defined in Project-A like customer itself. Authentication can be solved Rest Framework and OAuth2 I think but I don't have a solution for this problem. Can you help me out? Thanks in advance. -
Django access related items in template
Please help me I’m stuck in understanding how Django ORM works. Here is my very simple models: class Department(models.Model): title = models.CharField(max_length=50) class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.PROTECT) I want a template that looks like: Department 1 Employee 1 Employee 2 Department 2 Employee 3 Employee 4 But I can’t figure out what I should do in my view and(or) template