Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to apply one to many relationship in my situation?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view after login Models.py file(Student model is for item views.py Item database registered user for authentication -
how to split post value based on key in django
how to split my post value based on key and i will save to table this values My post data [('include_product_id[x_98342]', '2'), ('product_name[x_98342]', 'item_one'), ('product_qty[x_98342]', '5'), ('product_price[x_98342]', '1'), ('total_amount[x_98342]', '5'), ('include_product_id[x_647057]', '14'), ('product_name[x_647057]', 'item_two'), ('product_qty[x_647057]', '61'), ('product_price[x_647057]', '1'), ('total_amount[x_647057]', '61')] -
Deploying Django on Apache
I want to deploy django with anaconda project on Apache I name myapp as for both my project and anacond environment. My conf file lis like this. When accessing with browser , it stuck and nothing returns. There is no log in api_myapp_error.log and api_myapp_access.log curl api.myapp.net also stuck I am not even sure where stuck happens. So where to start??? <VirtualHost *:80> ServerName api.myapp.net ServerAdmin webmaster@localhost DocumentRoot "/var/www/html/myapp/current/" ErrorLog ${APACHE_LOG_DIR}/api_myapp_error.log CustomLog ${APACHE_LOG_DIR}/api_myapp_access.log combined <Directory /var/www/html/myapp/current/> <Files wsgi.py> Order allow,deny Allow from all </Files> Order allow,deny Allow from all </Directory> <Directory /var/www/html/myapp/current/static> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /var/www/html/myapp/current/myapp/wsgi.py Alias /static/ /var/www/html/myapp/current/static/ </VirtualHost> LoadModule wsgi_module /home/ubuntu/anaconda3/envs/myapp/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so WSGIDaemonProcess myapp user=ubuntu group=ubuntu python-path=/home/ubuntu/anaconda3/envs/myapp/lib/python3.7/site-packages WSGIPythonHome /home/ubuntu/anaconda3/envs/myapp/ WSGIPythonPath /var/www/html/myapp/current/ -
ModelName matching query does not exist. Problem working with loaddata
I am trying to use loaddata in Django to load a json file in my database. But I receive the following traceback when doing the same Traceback (most recent call last): File "D:\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__ rel_obj = self.field.get_cached_value(instance) File "D:\env\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache[cache_name] KeyError: 'loan_application' During handling of the above exception, another exception occurred: loan_tracker.models.DoesNotExist: Problem installing fixture 'C:\Users\Desktop\db_try2.json': LoanData matching query does not exist. There are similar problems that have been asked for the same but none of them work for my case loan_application is a foreign key to a different model here. I have used the following approach to address this problem . Checked the format of my json file that is accepted for loaddata. Checks out Used DISABLE TRIGGER ALL for any foreign key constraints that may cause this to happen. Used the loaddata --ignorenonexistent keyword to ignore fields and models that may have been removed. But nothing seems to work here. Would appreciate a new approach that could be applied to get this model to load in my DB. P.S : I cannot exclude this model as it will affect other models that are dependent on it. -
Django create model with relation using dynamic fields
I have a hard time coming up with a way to dynamically add fields to my form using jQuery. I have a Customer model which has a MtO relation with a Contacts model and a Reference model. After filling in the customer's info, there are 5 fields needed per contact. But the hard part is they can add up to 5 contacts, so I use Javascript to append the html needed to get more sets of 5 forms. But how do I actually make these fields work with Django? index.html: <div class="row g-1" id="contactRow"> <div class="col-md-5"> <select class="form-select mb-2" aria-label="Contact types"> <option style="font-weight:bold" value="" selected disabled>Type</option> {% for type in contact_types %} <option>{{ type.name }}</option> {% endfor %} </select> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_name }} <label for={{ form.contact_name.id_for_label }}> {{ form.contact_name.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_funct }} <label for={{ form.contact_funct.id_for_label }}> {{ form.contact_funct.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_email }} <label for={{ form.contact_email.id_for_label }}> {{ form.contact_email.label }} </label> </div> <div class="form-floating form-floating-group flex-grow-1 mb-2"> {{ form.contact_phone }} <label for={{ form.contact_phone.id_for_label }}> {{ form.contact_phone.label }} </label> </div> </div> main.js: $("#addContact").click(function () { let form_count = $('input[name*="extra_contact_*"]').length; let html = ''; … -
how the user model attach with the django request?
can anyone explain how the django User model getting attached with the request after the successful login. By the same can we attach some other models with django request. I know we can use cookies or sessions instead of this but i am curious about how this happening. Anyone know the answer please help. -
How to take only the 5 element of an array while using loop ijn Django? [closed]
I can not take the exact number of elements from an array while I am using a loop. Consider there are 10 elements in an array [1,2,3,4,5,6,7,8,9,10] and I need only the first five elements [1,2,3,4,5] I should reach them using for loop. These all are in Django. Please tell me if someone knows the answer. -
How to retrieve different type of data in django?
I created an attendance management system and I want to retrieve the different types of date from the table. Like, In my attendance table, there are different date but some date is repeated ex - for every date, there are number of users has attendance staff table. attendance table id = 1 id = 1 name = john staff_id = 1 date = 31.08.2021 id = 2 attendance = present name = harry id = 2 staff_id = 2 date = 31.08.2021 attendance = absent id = 3 staff_id = 1 date = 01.09.2021 attendance = present id = 4 staff_id = 2 date = 01.09.2021 attendance = present from the above table data I wanted to retrieve the only date without repetition so when we write code the answer will be 31.08.2021 01.09.2021 this is my template file {% for attendances in attendance %} <th>{{ attendances.date }}</th> // here i want to retrive 31.08.2021 and 01.09.2021 {% endfor %} This is my views file def index(request): staffs = staff.objects.all() attendances = attendance.objects.all() date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'date': date}) -
Logging out on django web app redirects to django admin logout page. What's going on?
I'm following a tutorial in the Python Crash Course book on creating a simple web page using Django. I've just created an app to log a user in and out on my page, using Django's default user authentication system. When I logout, Django is not redirecting to the template I've created to show that the user is logged out. Instead it redirects to the Django admin logout page. Here is my base urls.py file. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] Here is my 'users' app url.py file. from django.urls import path, include app_name = 'users' urlpatterns = [ # Include default auth URLs path('', include('django.contrib.auth.urls')), ] Here is my base.html template. <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> - <a href="{% url 'learning_logs:topics' %}">Topics</a> {% if user.is_authenticated %} Hello, {{ user.username }}. <a href="{% url 'users:logout' %}">Log out</a> {% else %} <a href="{% url 'users:login' %}">Log in</a> {% endif %} </p> Here is my logout.html template. {% extends "learning_logs/base.html" %} {% block content %} <p>You have been logged out. Thanks for stopping by!</p> {% endblock content %} Here are my installed apps in settings.py NSTALLED_APPS = [ … -
Dynamic particular field on a form in Django?
I have a form which has more than 10 fields. Now i want a particular field, lets say "requirements". This can be more than one requirement, i can deal with that using rich text editor as ask my user to input all the requirements as a ordered list. But for better user experience i am asking this ! I am gonna keep a button under "requirements" field, so that user can click on this button to get a new field. By this, i want all fields to be combined in a dict like requirements = {'field1','extrafield1'} and etc How to perform this ? I cant user formset ( as am just adding dynamic field not whole form ) How to deal this with django forms ? -
Value of select field from a django for loop in template and passing seledted field value via ajax to server side django
I have a static select option in my template within a customer orders for loop.. now i want to change status (select) via js and send the data back to django view. but how am i suposed to do that. i have tried in many ways but nothing seems to work -
Django create unique function index
With postgresql we can create unique function index: create unique index user_date_checkin on unique_user_date (user_id, (timezone('UTC'::text, create_time)::date)); But with Django 3.2: class UserCheckin(GeneralModel): id = models.BigAutoField(primary_key=True) user_id = models.BigIntegerField() create_time = models.DateTimeField() class Meta: indexes = [ models.Index("user_id", TruncDate("create_time"), name="user_date_checkin"), ] can only got such sql generation: create index user_date_checkin on test (user_id, (timezone('UTC'::text, create_time)::date)); And UniqueConstraint constraints = [ models.UniqueConstraint( fields=["user_id", TruncDate("create_time")], name="user_date"), ] got refers to the nonexistent field 'TruncDate(F(create_time)) error So how can I create unique index with function in Django 3.2? -
Git bash "Watching for file changes with StatReloader" stuck and never loads
I have setup a Django project on a virtual environment on my PC. When using the command python manage.py runserver 0.0.0.0:8000 Bit Bash stops doing anything and I have to end the program to start over. I have waited several minutes and when I end the session, a dialogue says: Processes are running in session: WPID PID COMMAND 14904 1534 c:\Users\mine\AppData\Loca Close anyway? I have looked at every related question to this and tried every solution but I cannot get this to work, on or off the virtual environment. -
Showing unreserved times in frontend of django booking app
Im trying to build a booking app with Django. this is my "Event model" in my model.py: user = models.ForeignKey(User,null=True, on_delete=models.SET_NULL) date = models.DateField(null=True) time = models.TimeField(null=True) end_time = models.TimeField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) #date: Date the user want to come #time: The time the user want to come. #end_time: the time that the owner guesses for ending the job that user want time for it. What i want to do?: I want to take that time the user want to come. and after this action, owner select the #end_time. (between these times Users cant reserve time...) Question: I need to show empty or unreserved times to user in template... if you have any idea or respones in both logical side and front side, please help me and type it for me. -
Updating a model when an object it references through a ManyToMany relation is deleted
I have a model, for instance class ModelA(models.Model): name = models.CharField() class ModelB(models.Model): last_modified_time = models.DateTimeField() as = models.ManyToManyField('ModelA') when I delete an instance of ModelA I would like to also update the last_modified_time field on all ModelB instances that referred to ModelA. I can use a predelete signal for this, i.e. def pre_delete_handler(sender=None, instance=None, *args, **kwargs): # update all using instance.modelbs... models.signals.pre_delete.connect(pre_delete_handler, sender=ModelA) but then every time a new model references it via a ManyToMany this bit of code needs to be updated which isn't the best from a maintenance point of view. I am looking for a way to enumerate all models that ModelA is referenced by so I can have a single update that covers all cases but can't figure out the best way to do this. What is the proper way to enumerate all objects that ModelA is related to? -
if there is not Error why its color dont changed?
this is my github, i dont know why even though there is not error the color of stule.css didnt ocuerr? https://github.com/Angelheartha/tera i dont know even though polls/templates/polls/index.html indicate polls/static/polls/style.css when i do python manage.py runserver and http://localhost:8000/polls/ i cant see that the colors changed to green i tried to test if there is error but there is not error so why the color didnt changed? -
How to add get_queryset function in apiview of Djnago rest framework?
I am using Django APIView to include all my CRUD operation in a single api endpoint. But later on I had to use filtering logic based on the query parameters that have been passed. Hence I found it to include in a get api of APIView and made a separate api using generic view, ListAPiview. Here is the view: class LeadsView(APIView): permission_classes = [IsAuthenticated] def get(self, request, pk=None, *args, **kwargs): id = pk if id is not None: abc = Lead.objects.get(id=id) serializer = LeadSerializer(abc) return serializer.data def post(self,request,*args,**kwargs): abc = LeadSerializer(data=request.data,many=True) if abc.is_valid(): abc.save() return Response(abc.data, status=status.HTTP_201_CREATED) return Response(abc._errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request,pk, *args, **kwargs): Now, I have to use filter class and also some custom filtering logic, I need to use get_queryset. Hence I have to create another api just for get method which I dont want. class LeadAPIView(ListAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Lead.objects.all().order_by('-date_created') serializer_class = LeadSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] pagination_class = CustomPagination # filterset_fields = [ 'email','first_name','last_name','phone'] filterset_class = LeadsFilter def get_queryset(self): source = self.request.GET.get("source", None) # lead_status = self.request.GET.get("lead_status", None) if source is not None: source_values = source.split(",") if lead_status is not None: lead_status_values= lead_status.split(",") return Lead.objects.filter(source__in=source_values,lead_status__in=lead_status_values) else: return Lead.objects.filter(source__in=source_values) elif lead_status is … -
how to update django table data?
I created attendance management system and i want that when user enter attendace , if attendance for that date already exist than it only update. How to update attendance field in attendance table if data is already exist of that date ? This is my views file def index(request): staffs = staff.objects.all() a = staff.objects. values_list('id', flat=True) attendances = attendance.objects.all() amounts = amount.objects.all() date = datetime.date.today() if request.method == "POST" : for i in a : print(i) stf = 'staff_id' + str(i) print(stf) atd = 'attendance' + str(i) print(atd) staff_id = request.POST.get(stf, None) attendances = request.POST.get(atd, None) date = datetime.date.today() ins = attendance(staff_id=staff_id, attendance=attendances, date=date) ins.save() return HttpResponseRedirect("/index") date = datetime.date.today() return render(request, "salary/index.html", {'staff': staffs, 'attendance': attendances, 'amount': amounts, 'date': date}) This is my template file where their is form <form action="/index" method="POST"> {% csrf_token %} {% for staffs in staff %} <input type="hidden" name="staff_id{{staffs.id}}" value="{{staffs.id}}"> <input type="hidden" name="attendance{{staffs.id}}" id='input_attendance{{staffs.id}}'> <tr> <td> {{staffs.id}} </td> <td> {{staffs.name}} </td> <td> <div class="btn-group"> {% for attendances in attendance %} {% if attendances.staff_id|add:0 == staffs.id|add:0 %} {% if attendances.attendance == 'present'%} {% if attendances.date == date %} <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id='present{{staffs.id}}'> Present </button> {% else %} <button type="button" … -
di_form's is_valid() not working properly
models.py class DeviceInterface(models.Model): MODULE_ID_CHOICES = ( ('TenGigabitEthernet','TenGigabitEthernet'), ('FortyGigabitEthernet','FortyGigabitEthernet'), ('GigabitEthernet','GigabitEthernet'), ('Ethernet','Ethernet'), ) moduletype = models.CharField(max_length = 50,choices = MODULE_ID_CHOICES) firstportid = models.CharField(max_length=50) lastportid = models.CharField(max_length=50) I2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.moduletype forms.py class DeviceInterfaceForm(ModelForm): class Meta: model= DeviceInterface fields= ['moduletype', 'firstportid', 'lastportid'] labels = { "moduletype":"Module Type", "firstportid": "First Port ID", "lastportid": "Last Port ID" } Part of views.py if di_form.is_valid(): deviceI=di_form.save(commit=False) print(deviceI) for instances in deviceI: instances.I2DKEY=new_device instances.save() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) else: print(deviceI.errors) I have the following codes above, few weeks ago it is working. But now its not working. When i submit my form, it somehow goes is_valid()=True. So meaning my text fields for this model can be empty and the form can still be saved somehow. PS: This webpage have a total of 3 different forms. So if this form's field are all empty, it saves the the other models instead. Can anyone explain to me what am i doing wrongly? -
How to change files name of django InMemoryUploadedFile before upload to S3 without models?
Environments Django==3.24 DRF==3.11 boto3==1.16 django-storages==1.10 I want to change files name before upload to s3 without saving in DB(model). I tried like this. # in Post request files = request.FILES.getlist('files') res = [] for file in files: random_car = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(8)) ext = file.name.split('.')[-1] file_name = f'{random_car}.{ext}' # -------- try start --------- # I want to change file name to file_name # This code throws an error. # FileNotFoundError: [Errno 2] No such file or directory: '8.jpeg' -> 'kVuepnuR.jpeg' os.rename(file.name, file_name) # -------- try end --------- file_path_within_bucket = os.path.join( file_directory_within_bucket, file.name ) default_storage.save(file_path_within_bucket, file) file_url = default_storage.url(file_path_within_bucket) res.append(file_url) How can I change the name if InMemoryUploadedFile? -
Django - Verify AWS Cognito token is valid before processing endpoint request
So I have this code below for checking a AWS Cognito token. I obviously don't want to add these 6 lines of code to every endpoint. How can I authenticate the AWS amplify token that comes with every request to ensure the user is properly logged in. Can I get the user's email from this token somehow? views.py def post(self, request): # 'Bearer z324weroko2iorjqoi=+3r3+3ij.2o2ij4=' token = request.META['HTTP_AUTHORIZATION'].split(' ')[1] print(token) # TODO this should be separated out to a login module try: res = jwt.decode_cognito_jwt(token) return Response(status=status.Http_200_OK) except: return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) -
TypeError: list indices must be integers or slices, not str in Django 3.0
While converting the csv file data in django models i am getting an issue def upload_timesheet(client, user1, csv_file): field_map_1 = { 'Date' : 'date', 'Client Name' : 'worked_on', 'Employee Name': 'user', 'Employee Number': 'employee_number', 'Start Time(HH:MM:SS)': 'start_time', 'End Time(HH:MM:SS)': 'end_time', 'Break Taken(HH:MM:SS/HH:MM)': 'breaktime', 'Assignment id': 'assignment', 'Rate': 'work_assign', } def get_values_remapped(row): return {field_map_1[key]: row[key].strip() for key in field_map_1} Here is my error traceback Traceback (most recent call last): File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 3011, in upload_timesheet remapped_row = get_values_remapped(row) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in get_values_remapped return {field_map_1[key]: row[key].strip() for key in field_map_1} File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in <dictcomp> return {field_map_1[key]: row[key].strip() for key in field_map_1} TypeError: list indices must be integers or slices, not str [2021-09-01 09:34:29,484: ERROR/ForkPoolWorker-1] list indices must be integers or slices, not str Traceback (most recent call last): File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 3011, in upload_timesheet remapped_row = get_values_remapped(row) File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in get_values_remapped return {field_map_1[key]: row[key].strip() for key in field_map_1} File "/home/harika/lightdegreerespos/mcam/server/mcam/crm/tasks.py", line 2977, in <dictcomp> return {field_map_1[key]: row[key].strip() for key in field_map_1} TypeError: list indices must be integers or slices, not str When trying to fetch the data of the uploaded csv file getting the following error in Django 3.0 to python 3.7 please help me to … -
How to print first 100 character in django?
I want to print first 100 character of string in django. {% if dt.faq_info|length < 100 %} {{dt.faq_info}} {% else %} {{dt.faq_info[:100]}} {% endif %} But I recieved TemplateSyntaxError Could not parse the remainder: '[:100]' from 'dt.faq_info[:100]' Is there any other way to do this? -
How to restore a dump database backup for a Django project with existing models and migrations?
Setting up a mysql database from an existing dump is very easy # open prompt cd into the directory where the dump is located # login to mysql create database mydb use mydb source mydb.sql And all is done! But the problem comes with Django. Django has troubles with existing schemes and data that have not been created from models and migration system. And in Django, everything must come from models and migrations. I perfectly know that I have this option python manage.py inspectdb > models.py But this is only suitable when creating a blank new Django project using existing database. What if I want to run an existing Django project to another machine and the Django project uses a database? The project already has existing models with some manage=false set, I cannot simply inspectdb it. And if I restore the database outside Django, the Django ORM will no longer recognize it. Then what is the correct way to restore a database from a database backup for a project with existing models and migrations? -
How to mark cloned form from inline as deleted so Django knows what to save and what not to save
views.py: def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) dd_form = DeviceDetailForm(request.POST) di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'),widgets={ 'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=1,max_num=3, can_delete=False) di_form=di_formset(request.POST) if device_frm.is_valid(): # Create and save the device # new_device here is the newly created Device object new_device = device_frm.save() if dd_form.is_valid(): # Create an unsaved instance of device detail deviceD = dd_form.save(commit=False) # Set the device we just created above as this device detail's device deviceD.DD2DKEY = new_device deviceD.save() if di_form.is_valid(): deviceI=di_form.save(commit=False) print(deviceI) for instances in deviceI: instances.I2DKEY=new_device instances.save() return render(request, 'interface/device_added.html',{'devices':Device.objects.all()}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) else: device_frm = DeviceForm() dd_form = DeviceDetailForm() di_formset = inlineformset_factory(Device, DeviceInterface, fields=('moduletype', 'firstportid', 'lastportid'), widgets={ 'firstportid':TextInput(attrs={'placeholder': 'e.g. TenGigabitEthernet1/0/1'}), 'lastportid':TextInput(attrs={'placeholder':'eg. TenGigabitEthernet1/0/48'})},extra=1, max_num=3, can_delete=False) di_form=di_formset(queryset = DeviceInterface.objects.none()) return render(request,'interface/device_add.html',{'form':device_frm, 'dd_form': dd_form, 'di_form':di_form}) HTML: {{di_form.management_form}} <div id = "rowAddition"> {% for form in di_form %} <div> <div class="row"> <div class="col-md-2"> <div class="form-group"> <label for="{{di_form.moduletype.id_for_label}}">Module Type<span class="text-danger">*</span></label> {{form.moduletype}} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="{{di_form.firstportid.id_for_label}}">First Port ID<span class="text-danger">*</span></label> {{form.firstportid}} </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="{{di_form.lastportid.id_for_label}}">Last Port ID <span class="text-danger">*</span></label> {{form.lastportid}} </div> </div> </div> </div> {%endfor%} <div id="empty-form" style="display: none;"> <div class="row"> <div class="col-md-2"> <div class="form-group"> <label …