Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IntegrityError at /admin/api/user/6/change/ FOREIGN KEY constraint failed
I am developing a website on django. When I am trying to delete a user via admin panel i get an error. I can change e.g. staff status (while still getting an error, but changes are getting apllied) The code is below: models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): emailSpam = models.BooleanField(default=True) email = models.EmailField('email', unique=True) first_name = None last_name = None confirmedEmail = models.BooleanField(default=False) REQUIRED_FIELDS = ["emailSpam"] forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ('email',) class CustomUserChangeForm(UserChangeForm): class Meta: model = User fields = ('email',) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import User class Admin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = User list_display = ('email', 'is_staff', 'is_active',) list_filter = ('email', 'is_staff', 'is_active',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2', 'is_staff', 'is_active')} ), ) search_fields = ('email',) ordering = ('email',) admin.site.register(User, Admin) -
How hide image path in django?
Is it possible to hide the path to the image so that it is not visible in the element expect? I dont want to allow user know where is my images are a storing. How i can hide this in django? -
Django Forms does not submit radiobutton value and does not showing any output in terminal as well
This is HTML Code. <form action = "." method = "post"> <div class="form_data"> {% csrf_token %} <br><br> {{form.myfield}} <br><br> <input type="submit" value="Submit" class="btn btn-success" /> </div> </form> This is forms.py code class TestForm(forms.ModelForm): class Meta: model = TestModel fields = "__all__" widgets = {'myfield': forms.RadioSelect()} This is models.py code class TestModel(models.Model): git_Id = models.CharField(max_length=200) git_Response = models.CharField(max_length=200) is_approved = models.IntegerField() MY_CHOICES = ( ('opt0', 'Approved'), ('opt1', 'Not Approved'), ) myfield = models.CharField(max_length=10, choices=MY_CHOICES, default="N/A") views.py code def test(request): if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): print("Form is Valid") selected = form.cleaned_data['myfield'] print(selected) if selected == 'opt0': from config import request_id as r rq = r["request_id"] print(rq) s = sql() query = f"""update request_form_mymodel set is_approved=1 where request_id = '{rq}' """ print(query) s.update_query(query) else: pass else: form = TestForm() return render(request, 'test.html', {'form': form}) I am not getting any output, if i try to submit after selecting radio button then it does not working and not printing any variables values in terminal as well and form is not submitted. What I want - I want to getting form is submitted and if radiobutton is selected opt0 then s.update() is called. -
Pyton django urlpatterns , url like localhost:8000/auth/?code=Rdsraj4v7BGNhH2
Pyton django urlpatterns , url like http://localhost:8000/auth/?code=Rdsraj4v7BGNhH2 How send value"Rdsraj4v7BGNhH2" from url to views url= localhost:8000/auth/?code=Rdsraj4v7BGNhH2 ` urlpatterns = [ path('?????', views.auth, name ='auth'), ] ` expectations : from url send value to views -
On admin django choose one element in a list and have same result in the inline
If we consider that "client" is a dropdown list, would it be possible to reflect the choice made in StatusAdmin in my StatusTextInline class in order to have only one client associated please? Or to check if the two clients are the same before saving? class StatusTextInline(admin.TabularInline): model = StatusText extra = 0 list_display = ( "id", "client", "label" ) @admin.register(Status) class StatusAdmin(admin.ModelAdmin): list_display = ( "id", "client" ) inlines = [ StatusTextInline, ] Knowing that client is a list, if I choose client 1 in StatusAdmin, then I will automatically have client 1 in my StatusTextInline. -
How to add field in django admin non related to model?
I want to add a checkbox in Django Admin that is not related to a field in my model. Depending on the value of the checkbox, I want to do some extra actions. class DeviceAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): #if checkbox: # do_extra_actions() super(DeviceAdmin, self).save_model(request, obj, form, change) How to add this checkbox in the django admin form for my model Device and get the value in save_model function ? -
['“test” value must be either True, False, or None.']
I am trying to create a register API but it returns a error: views.py class RegisterAPI(APIView): permission_classes = () authentication_classes = () def post(self, request, *args, **kwargs): serializer = RegisterSerializer(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) user = serializer.save() print(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) Models.py class CustomUser(AbstractBaseUser): username = models.CharField (max_length= 200) first_name = models.CharField (max_length = 300) last_name = models.CharField (max_length = 300) email = models.EmailField (max_length=255,unique=True) password_f = models.CharField (max_length=100,) profile_pic = models.ImageField (upload_to = r'Computerizer/static/Oauth/media') sub_to_newsletter = models.BooleanField(default=True) own_pc = models.BooleanField(default=False) active = models.BooleanField(default=True,null=True) #can login staff = models.BooleanField(default=False,null=True) #staff user not superuser admin = models.BooleanField(default=False,null=True) #admin / superuser USERNAME_FIELD = 'email' #username #email and password is requierd by default REQUIRED_FIELDS = [] #python manage.py createsuperuser objects = CustomUserManager() def __str__(self): return self.email def get_first_name(self): return self.email def get_last_name(self): return self.email def has_perm(self,perm,obj=None): return True def has_module_perms(self,app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active def get_absolute_url(request): return reverse('') Serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id','username','first_name','last_name','email','password_f','sub_to_newsletter','own_pc') class RegisterSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'username','first_name','last_name', 'email', 'password_f','sub_to_newsletter','own_pc') def create(self, validated_data): user = CustomUser.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password_f']) return user the error is: ['“test” value … -
Listing Kafka clusters and brokers with Python
I try to develop a Kafka GUI on Django. I can list topics of brokers, partitions and clients using kafka-python. Is a programmatic way to retrieve list of clusters and brokers? I can save clusters and related brokers as database tables as an alternative. -
How to put other model classes belonging (linked) to a main model class. And how to write this in Views.py. (This is Not FK)
I have a main model, called "Employees", and I need to link to it another 16 model classes (Employees Additional Data, Employees Observations, etc) in the same app. What would be the best way to write these classes in models.py? Could be like that? class Employees(models.Model): class Meta: db_table = "employees" #fields #fields class EmployeesObs(models.Model): class Meta: db_table = "employeesobs" #fields #fields class EmployeesAdditionalData(models.Model): class Meta: db_table = "employeesaditional" #fields #fields Now, in this views.py i need: Explaining this in the template, I need to have these other tabs (Employees Additional Data, Employees Observations, etc) in the employee register, as in the image: Now how do I write this in views.py? I'm using Class Based Views. Can someone help me by giving me an example of code, function or documentation? Part of code in CBV: class AddEmployeesView(SuccessMessageMixin, CreateView): model = Employees form_class = EmployeesForm template_name = '../templates/employees/form_employees.html' success_url = reverse_lazy('list_Employees') success_message = "Employees %(EmployeesNome)s Added!" class EditEmployeesView(SuccessMessageMixin, UpdateView): model = Employees form_class = EmployeesForm template_name = '../templates/employees/form_employees.html' success_url = reverse_lazy('list_Employees') success_message = "Employees %(EmployeesNome)s Edited!" I tried to put the other model names in the "model" part of the CBV, but I got errors. -
Access Multiple PDF Files with Django Rest Framework and REACT frontend
I am trying to access the uploaded files from my Django-rest-Framework which I uploaded with my React Frontend. The Upload is in my opinion const fetchDocuments = async () => { return await axios.get(`${URLS.courses}${params.courseId}/documents/`, { headers: { authorization: `Bearer ${getAuthenticationTokens().access}`, }, }); }; CourseDocument: class CourseDocument(models.Model): title = models.CharField(max_length=30, default='') document = models.FileField(upload_to='courses') course = models.ForeignKey(to='Course', on_delete=models.SET_NULL, null=True) To my DRF endpoint: @action(methods=['GET', 'POST'], detail=True, url_path='documents', permission_classes=EMPLOYEE_PERMISSION) def course_documents(self, request, *args, **kwargs): """ Returns the attached documents of the given course """ if request.method == 'GET': qs = CourseDocument.objects.filter(course_id=kwargs['pk']) fs = FileSystemStorage() filename = qs.first().document.path if fs.exists(filename): with fs.open(filename) as pdf: response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return response else: print("NOT FOUND") if request.method == 'POST': serializer = CourseDocumentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=200) else: return Response(data=serializer.errors, status=400) return Response(status=200) I tried it so far with the FileSystemStorage to send it in an HTTP Response with content type application/pdf. This did work, but only for one single PDF File. I want to avoid to pass the pdf as a link to my backend because of security reasons. How can I achieve sending multiple pdf files to my frontend? -
responseType blog in django unit tests
How to add responseType blob while making a post request with django_test unit tests, below is my test code snippet : from django.test import TestCase def test_export_business_plan(self): """Test export business plan.""" data = { 'location_creation': 'berlin', 'date_creation': datetime.now().strftime('%Y-%m-%d'), 'company_name': 'Captiq', 'email_address': 'test@captiq.com', 'phone_number': '0704594180', 'street': 'Berlin Katherinenstrasse', 'house_number': '17b', 'additional': 'test', 'post_code': '43567', 'city': 'Frankfurt', 'sub_title': 'test' } response = self.client.post( reverse( 'api:financing:business_plan-export', kwargs={'pk': self.loan_application.pk}), data) print('**********==', response.data) print('**********==', dir(response)) self.assertEqual(response.status_code, 200) -
Django filter relation model mutiple fields at the sime time
I have a problem to filter following condition: class Plan(models.Model): name = models.CharField(max_length=50) class PlanAttribute(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name="attributes") key = models.CharField(max_length=50) value = models.CharField(max_length=50) I want to filter Plan with attr key="key1" and value="value1" at the same time Plan.objects.filter(attributes__key="key1", attributes__value="value1") is not what I want Please help me to filter like this cases -
Add Field Update
With the help of a button, I developed a code that allows the area I want to be added as the button is pressed, and this code works without any problems. When I reopen the form to update it, the data comes in as I added and I save it again, then when I enter the updated form, the data is lost. So I'm giving an example, I pressed the button 3 times and 3 fields came to enter, I filled in 3 of them and saved, then when I enter to update, it appears in 3 data. When I exit the update screen and enter that form again, only the most recently added data appears from the 3 data. models.py class Records(models.Model): username = models.CharField(max_length=1000, verbose_name='Ad Soyad',null=True,blank=True) date = models.CharField(max_length=1000,null=True,blank=True) hours = models.CharField(max_length=1000,blank=True,null=True) tel = models.CharField(max_length=1000,verbose_name='Telefon Numarası',null=True,blank=True) tcNo = models.CharField(max_length=1000, verbose_name='TC Numarası',null=True,blank=True) adress = models.CharField(max_length = 1000,verbose_name='Adres/Köy',null=True,blank=True) kurum = models.CharField(max_length=1000,verbose_name='Kurum',null=True,blank=True) diagnosis = models.CharField(max_length=1000, verbose_name='Tanı',null=True,blank=True) intervention = models.CharField(max_length=1000, verbose_name='Müdahale', null=True,blank=True) # medications = models.CharField(max_length=1000, verbose_name='İlaçlar', null=True,blank=True) conclusion = models.CharField(max_length = 1000,verbose_name='Sonuç',null=True,blank=True) doctor = models.CharField(max_length=1000, verbose_name='Doktor',null=True,blank=True) record_one_measurement = models.CharField(max_length=1000, verbose_name='1.Ölçüm',null=True,blank=True) record_one_blood_pressure = models.CharField(max_length=1000, verbose_name='1.Tansiyon',null=True,blank=True) record_one_pulse = models.CharField(max_length=1000, verbose_name='1.Nabız',null=True,blank=True) record_one_spo2 = models.CharField(max_length=1000, verbose_name='1.SPO2',null=True,blank=True) record_one_respirations_min = models.CharField(max_length=1000, verbose_name='1.Solunum/DK',null=True,blank=True) record_one_fire = models.CharField(max_length=1000, verbose_name='1.Ateş',null=True,blank=True) record_second_measurement … -
Auto list fields from many-to-many model
I've created a model of analysis types and then i created a table that groups several analysis to one group: class AnalysisType(models.Model): a_name = models.CharField(max_length=16,primary_key=True) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # analysis_group = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) def __str__(self): return f"{self.a_name} - {self.a_measur}" class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" I want to have an option to multiple add values via admin panel (I.E. i chose Analysis type then below appear fields to fill) class PatientGroupAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) # amalysis_data = ??? def __str__(self): return f"{self.patient}: {self.analysis_date} - {self.analysis_type} - {self.analysis_data}" enter image description here Tried to use amalysis_data = analysis.type.objects.all() and etc. but that's the wrong way i guess .. :( -
Automatically Move data to archive table if date is older
I have a gallery model in my models.py. I want to automatically move the data to another table called as Archive if created date is more than 30 days. This is my models.py class Gallery(models.Model): id= models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') video = models.FileField(upload_to='videos/', validators=[FileExtensionValidator( ['mp4', 'mov', 'mkv'] )]) tag = models.CharField(max_length=100) classes = models.ForeignKey(Classes, null=True, blank=True, on_delete=models.CASCADE) level = models.ForeignKey(Level, null=True, blank=True, on_delete=models.CASCADE) uploded_date = models.DateTimeField(auto_now_add=True) class Archive(models.Model): id= models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') video = models.FileField(upload_to='videos/', validators=[FileExtensionValidator( ['mp4', 'mov', 'mkv'] )]) tag = models.CharField(max_length=100) classes = models.ForeignKey(Classes, null=True, blank=True, on_delete=models.CASCADE) level = models.ForeignKey(Level, null=True, blank=True, on_delete=models.CASCADE) uploded_date = models.DateTimeField(auto_now_add=True) I have thought of creating signals and sending signals to Archive like this. I have already defined the signal. def date_is_old(self): if self.uploded_date > (datetime.datetime.now()-timedelta(days=15)): date_is_old.send(self.__class__) But this method seems to be ineffective as it only sends signal at time of creation of new record. I need the function to always check and If creation is past 30 days automatically move data to Archive. Is there some way to handle this? I am really out of option tried modifying create method and save methods on table "Gallery". -
Django app not being served via nginx on ubuntu 22.04
I have attempted twice to deploy a django app on ubuntu 22.04 and serve it using nginx but it doesn't work. The guide I am using has worked on previous versions of ubuntu. Upon completion of the guide, I get an 502 gateway error. While inspecting the log errors, I get this error. 4286#4286: using inherited sockets from "6;7;" The closest I have come to answer is this this question but the developer is working with php. -
Django image storing in db
there is a question how best to store images in Django? On stackoverflow, I read that it is better to store them in the file system and serve them Apache, how true is this? And also there is a question, is it possible to hide the path to the image so that it is not visible in the element expect? How i can hide this? -
How to access a specific user's model data as admin?
I'm creating a simple model form that is only available to staff. It has a user selection dropdown list populated by models.py user = models.ForeignKey(User, on_delete=models.CASCADE). On submit I need my view to look up the selected user from the form and return the data in the models for that user (from the built-in Django database). How would I go about doing this? I have searched here and the recommended articles, but they all appear to be for accessing a model as the logged-in user. Here is a screenshot of the form and my code: models.py class GetData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class DataRequestForm(forms.ModelForm): class Meta: model = GetData fields = ['user'] Views.py @login_required def data_form(request): if request.user.is_staff == True: if request.method == 'POST': form = DataRequestForm(request.POST) if form.is_valid(): user = request.POST["user"] print("Form is Valid") print(user) # How to access that user's model data here? -
Django project doesn't allow to work with personal modules
I created a django project and a folder with some helpers to handle firestore stuff. When I try to import the helpers it says that the 'helpers' is not a module. Am I missing something about django ? ANy tip? I'd like to import my helpers in some personalized mixins which will be used in certains views. -
NoReverseMatch at /invoicing/search/
In my localhost i have this error when i search something, for exemple number of invoicing, and at Web site server i have "Server Error (500)", for the same problem, can you help me to fixed this . enter image description here We have the supplier and the invoice, each supplier have 1 and more invoice, whem i go search the supplier for invoicing, i have this error "NoReverseMatch at /invoicing/search/ Reverse for 'profilePage' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['accounts/profile/(?P[0-9]+)$']" -
Unable to get current user inside django rest serializer
I'm unable to get current user inside serializer. I have passed context but still i get error like "user": [ "This field is required." ] #Serializer.py class AddressSerializer(ModelSerializer): class Meta: model = Address fields = "__all__" def create(self, validated_data): request = self.context["request"] validated_data["user"] = request.user return super().create(validated_data) #Views.py class AddAddress(APIView): permission_classes = [IsAuthenticated] def post(self, request): print(request.user) serializer = AddressSerializer(data=request.data, context={"request":request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, 200) return Response(serializer.errors) #Models.py class Address(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) full_name = models.CharField(max_length=35) email = models.EmailField(max_length=100) phone = models.BigIntegerField() address_line_1 = models.TextField(max_length=500) address_line_2 = models.TextField(max_length=500) zip_code = models.IntegerField() city = models.CharField(max_length=20) state = models.CharField(max_length=15) country = models.CharField(max_length=15) class Meta: verbose_name_plural = "Address" def __str__(self): return self.full_name I exactly don't know the problem behind this -
Django - set timezone in a django-admin command
I have a django-admin command which is handling message sending to different users in different countries. Each user should get the message at the same date - according to their local timezone. For example: a user in Paris should get a message every Monday at 10 am (Paris time), and a user in NY should get a message every Monday at 10 am (NY time). What happens is that they both get the message at Monday 10 am GMT. I can't use the user's browser local timezone, because its a script running independently in my server. Instead, I want to send the message according to a TZ stored in my DB for each users preferences. How can I send the message according to each user's TZ in my "handle" function? I was trying to use the "django.utils.timezone.activate" but I am not really sure how to make it work -
Chained task or dependent task using celery and django
I am using celery for scheduled task management in my django app. using "app.conf.beat_schedule" i can schedule task successfully. But one of my task depends on another scheduled task and accepts params returend from it. In that case I am facing problem, seracing through internet I became confused and nothing found workable for me. I tried the following and it shows: " Scheduler: Sending due task chained (celery_task_1)" Inside celery.py import os from celery import Celery, group os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'chained': { 'task': 'celery_task_1', 'schedule': 5.0, 'args': (), 'options': { 'queue': 'default', 'link': signature( 'celery_task_2', args=(), kwargs={}, queue='default' ) } } } -
Add minimal parameters to logs including user ip address, user ID and time(in django)
Can anyone guide me in this? Add minimal parameters to logs including user ip address, user ID and time (in Django) -
Permission Denied for nginx django deployement on aws nginx (13: Permission denied)
I have the same issue. When i run the (sudo -u www-data stat /home) it gives error. you don`t have permission to execute this command. Although i have given the admin privileges from root user.