Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to manage local files with deployed Django app?
I have a Django app that is deployed on Heroku. The app aims to support auditability of documents that we have on our disk that is shared by few computer in our local network. Django app stores information such as: who has added the file, when it was created, what is the category of the file etc. Generally it helps us to find the file we need quickly and have some order. Is it possible for the Django app deployed on Heroku (or elsewhere) to upload/download files to our shared disk? We don't want to have physical files stored on the internet as they contain private information. But we want to have additional data about these files accessible from our Django app so that everybody can log in via website and have overview of all information of the files. We also want to be able to manage the files from the app (add new document, delete existing document). I was trying to set MEDIA_ROOT to our shared disk path but I think that's not possible because Django app deployed on Heroku will be looking inside of the system it is hosted on. Is it possible to manage files on shared … -
Django: forms.MultipleChoiceField Not Displayed
I am a beginner in Django/Python. Am having problem with djangos MultipleChoiceField in that it is not been displayed both in the loaded HTML in the browser and the page being displayed. The other aspects of the form such as my email field are been rendered successfully. forms.py class CustomSetForm(forms.Form): choice = () def __init__(self, qs, *args, **kwargs): super().__init__(*args, **kwargs) requirements = qs.required self.choice = list(requirements.split(',')) print(self.choice) email = forms.EmailField(label='', max_length=100, required=True, widget=forms.TextInput( attrs={'class': 'form-group form-control input-lg ', 'placeholder': 'Email'}), ) qualifications = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple, choices=choice) views.py def get_job_requirements(request, *args, **kwargs): selected_job_title = kwargs.get('job_title') obj_model = Author.objects.get(job_title=selected_job_title) form = CustomSetForm(obj_model) context = {'form': form} try: if request.method == "GET": return render(request, 'requirements/job_specs.html', context) if request.method == "POST": if form.is_valid(): email = form.cleaned_data.get('email') job_title_obj = Author.objects.get(job_title=selected_job_title) qualifications = form.cleaned_data.get('qualifications') applicant = Applicants.objects.create(email=email, job_title=job_title_obj, qualifications=qualifications) applicant.save() return JsonResponse({'created': True}) return render(request, 'requirements/job_specs.html', context) except Exception as e: print(e) return render(request, 'requirements/job_specs.html', context) My Html <form method="post" id="application-form"> {% csrf_token %} {{ form.email }} {{ form.qualifications.as_p }} <div class="bg-light row" > <div class="" id="btn-box"> <div class="col-md-12 d-grid gap-2 col-6 "> <button type="submit" class="btn btn-primary btn-lg">Save</button> </div> </div> </div> </form> HTML in browser <form method="post" id="application-form"> <input type="hidden" name="csrfmiddlewaretoken" value="og1mWWpCR6rwxOw19fhUp4jX4KfFqbmeczbTwO92zNYtXBoESiZbi5biugeOj8N0"> <input type="text" name="email" class="form-group … -
how to transfer pandas dataframe from django(backEnd) to tkinter(frontEnd)?
I am making tkinter program using django server. but I have trouble transper pandas dataframe that is calculated in django server. my django server @csrf_exempt def test(request): myColumn=['a', 'b'] myIndex = ['2020', '2021', '2022'] rows = [ [100, 120], [101, 121], [102, 122], ] result = pd.DataFrame( rows, columns=myColumn, index=myIndex ) print(result) return HttpResponse(result) # django print result a b 2020 100 120 2021 101 121 2022 102 122 my frontEnd tkinter def _calculation(self): url = "http://127.0.0.1:8000/test" response = requests.post(url) data = StringIO(str(response.content,'utf-8')) df=pd.read_csv(data) print(df) #tkinter print result Empty DataFrame Columns: [ab] Index: [] -
Difference between list() and get_queryset() in ModelViewSet - Django?
If i want to override the behaviour of list action of the viewset, which function do i have to override? I have the following viewset and model: class UsecaseViewSet(viewsets.ModelViewSet): serializer_class = UsecaseSerializer queryset = Usecase.objects.all() authentication_classes = (authentication.JWTAuthentication,) permission_classes = (permissions.DjangoModelPermissions,) class Usecase(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) ......... when list action is called, i would like to add few fields from another model. i want to filter by usecase_id and get run_time etc from this model. class UsecaseJobLogs(models.Model): id = models.BigAutoField(primary_key=True) date = models.DateField(auto_now=True) run_time = models.TimeField() job_id = models.IntegerField() usecase_id = models.IntegerField() -
How to runserver once in django and keep getting correct web test results?
I made a website with django that tests personal-color (input is a picture), and I have gathered a few test results to see if the web test results will be the same as my already tested data. However, everytime I run the test by > python manage.py runserver I get the correct result only the first time, and when I re-test with another input, I get wrong results. To get the correct result, I have to stop the server by Ctrl+C and then do python manage.py runserver again to get the right result with another input picture I want to test. Can anybody help me with this problem? I want to get the correct results from a multiple of pictures without having to runserver again everytime I want to test a picture. -
inlineformsetfactory jquery add value in table row
Below is my output and i want to add some data values in second line of table how can I get it from my below jscript. please help me out on this. [tableoutput][1] -
How to create an order with also seller as a foreign key to the orders table similar to customer field?
Here is some customization, I am trying to achieve. In creating rest API’s using DRF section, for the orders API, while creating orders we are getting the user id or creating one if it not exists from the customer object. Now, consider there is another model seller which has same foreign key relationship similar to customer field to the orders table. Now what to do in this situation to create an order? How to get the user id with both customer and seller in the serializer and what changes has to be done for the view? Whole orders api is the same, just I have added the sellers model with three fields sellername, phone and foreign key to user model. [models.py][1] [serializer.py][2] [views.py][3] As you can see when I only pass the customer object, I am getting the user id back so how to implement also for seller object -
News Display Plugin Formulation in Django and Python
Any thoughts on the best django plug ins for managing an external news library on a site and also cropping, and creating different images sizes for different styles, Weve custom built ours but since the images *thumbnails, large size and medium size should be internally cropped pre display and be adaptive for all devices am not getting a consistent result. Also amateur hour on this side but not all django projects on github contain consistent screenshots of the functioning and this is visual appearance is critical for this function. CSS Cropping tools are producing an inconsistent result and the cropping tools that i think hold the key to making sure our news always looks good. Links would be appreciated. -
RabbitMQ + Celery. RabbitMQ creates new process every 60 seconds
My goal is to create task that sends notification email when user's comment receives a reply. I'm using WSL Ubuntu, Django, Celery + RabbitMQ The problem is every 60 second RabbitMQ creates new '/usr/lib/erlang/erts-10.6.4/bin/epmd -daemon' process (hereinafter the PROCESS), without closing the previous one. As shown in logs I started RabbitMQ server at 12:05, first PROCESS started at 12:05, after that RabbitMQ creates new PROCESS every minute. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 338 0.0 0.0 16016 4420 tty1 S 12:05 0:00 sudo rabbitmq-server root 339 0.0 0.0 10656 1928 tty1 S 12:05 0:00 /bin/sh /usr/sbin/rabbitmq-server root 346 0.0 0.0 15116 2796 tty1 S 12:05 0:00 su rabbitmq -s /bin/sh -c /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 347 0.0 0.0 10656 1860 ? Ss 12:05 0:00 sh -c /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 348 0.0 0.0 10656 1904 ? S 12:05 0:00 /bin/sh /usr/lib/rabbitmq/bin/rabbitmq-server rabbitmq 455 0.0 0.0 14400 2248 ? S 12:05 0:00 /usr/lib/erlang/erts-10.6.4/bin/epmd -daemon rabbitmq 530 0.8 0.4 5345524 74892 ? Sl 12:05 0:11 /usr/lib/erlang/erts-10.6.4/bin/beam.smp -W w -A 128 -MBas ageffcbf -MHas ageffcbf -MBlmbcs 512 -MHlmbcs 512 -MMmcs 30 -P 1048576 -t 5000000 -stbt db -zdbbl 128000 -K true -B i -- -ro rabbitmq 575 0.0 0.0 14400 2212 … -
How to find intersection of regular and multilingual querysets in Django
I have two querysets: Regular Django queryset: <QuerySet [1160567, 1160906...]> Django Multilingual queryset: <MultilingualOrderQueryset [710330, 710326, 710325, ...]> I have tried: _.intersection(regular_qs, multilang_qs) But it gives me a programming error. Although both querysets were retrieved by appending values_list('id', flat=True) to their respective object managers, I assume they still contain their respective models that are not compatible. What is the best way to find common elements in these two querysets? One way would be to convert them to sets and then do regular python intersection, but I was wondering if there is a better/more efficient approach? -
InterfaceError from Dockerized Django to local MySql connection
Trying to connect local MySQL database from docker Django, unfortunately getting interface error don't know what's wrong. Host Machine Info: Macbook Pro M1 Mysql Database Version: Mysql 8 docker-compose.yml version: '3' services: django: build: ./project volumes: - ./project:/project ports: - "8081:8000" restart: unless-stopped nginx: image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./project/media:/usr/share/nginx/media - ./project/static:/usr/share/nginx/static ports: - "80:8080" restart: unless-stopped local_settings.py DATABASES = { 'default': { 'NAME': 'db_name', 'ENGINE': 'django.db.backends.mysql', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host.docker.internal', 'PORT': '33060', } } error traceback -
how to display form error if form fields are empty or invalid in rest_framework.by default the rest_framework points to the json endpoints
I have created a studentCreate Api view that accepts the post request. if the request is valid the form data is serialized and saved but if the form is invalid or empty it needs to redirected back to the form . But by default the form errors are redirected to the rest_framework json api. How can i achive this in rest_framework class StudentCreate(APIView): serializer_class=StudentSerializer def post(self,request): serializer=StudentSerializer(data=request.data) student=request.data if serializer.is_valid(): serializer.save() return redirect('student-list') return redirect('/',{"serializer":serializer,'message':"form fields are not valid"}) this is my form for creating new student instance <div class="container"> {% if message %} {{message}} {% endif %} <form action="{% url 'student-create' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name" placeholder="Enter name"> </div> <div class="form-group"> <label for="age">age</label> <input type="number" class="form-control" name="age" placeholder="age"> </div> <div class="form-group"> <label for="address">address</label> <input type="text" class="form-control" name="address" placeholder="address"> </div> <div class="form-group"> <label for="grade">grade</label> <input type="number" class="form-control" name="grade" placeholder="grade"> </div> <div class="form-group"> <label for="major">major</label> <input type="text" class="form-control" name="major" placeholder="major"> </div> <button type="submit" class="btn btn-primary">Submit</button> </div> the urlpattern for create urlpatterns = [ path("student/", StudentCreate.as_view(), name="student-create"), path("student-list/", StudentList.as_view(), name="student-list"), path("students-detail/<int:pk>/", StudentDetail.as_view(), name="student-detail"), ] -
django.db.utils.OperationalError: database is locked even only when there a two user using the app simultaneously
I know this is a common question but I want something different. Is it possible to resolve this error without changing the database type? I am using sqlite3 and when 2 users are using the app, this error comes. I think the error might be due to the connection not being closed for a user. Is there a way to close the cursor cursor.close() manually in django? -
Docker Compose Shared Named Volume Permissions Denied
The following docker-compose spins up containers for a Django application: version: '3.7' services: web: build: context: . dockerfile: Dockerfile.prod container_name: web volumes: - static_volume:/static - media_volume:/media ... nginx: container_name: nginx build: ./nginx_proxy restart: always volumes: - static_volume:/static - media_volume:/media ... volumes: media_volume: static_volume: The web container is built using the following Dockerfile: # pull official base image FROM python:3.8 ... # organise permissions RUN chown -R manager:manager /static RUN chmod -R 755 /static RUN chown -R manager:manager /media RUN chmod -R 755 /media RUN ls -la ... When the permissions are printed as web container is being built, it returns the following: Step 21/23 : RUN ls -la ---> Running in e61984edfbcb total 1760 drwxr-xr-x 1 manager:manager 4096 Jan 25 00:00 media drwxr-xr-x 1 manager:manager 4096 Jan 25 00:00 static Removing intermediate container e61984edfbcb As expected and set in the Dockerfile. BUT when the containers are spun up (docker-compose up) and I look inside the permissions of the web container, I find the following: docker exec -it web bash manager@c8762586f678:/$ ls -la total 1760 drwxrwxr-x 3 root:root 4096 Sep 22 11:12 media drwxr-xr-x 3 manager:manager 4096 Sep 22 11:12 static Why do the two named volumes have different permissions - … -
how do i get to show the repeating event details on all following dates in python django
Event Name : Guest Booking Event State date : 1-feb-2022 and event ends on 5-feb-2022. Contact person : ABC Contact number : 12345 When I create this event on 1st of feb and end date will select as 5th of feb, my challenge is, created event should display event name, event date, contact person name and contact number till 5th of feb automatically, without me creating same for 2nd of feb, 3rd of feb till 5th of feb manually. -
Getting Error while entering the date input in the Admin Database
#model.py class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) Date = models.DateTimeField(max_length=100) Hours=models.TimeField(Date,null=True) def __str__(self): return str(self.Date) Settings.py DATE_INPUT_FORMATS = ('%Y-%m-%d') While I entered the Date in the admin database it is showing as an undefined in the field and throwing an error as an "enter a valid date". I have changed the formats and entered the date manually in the Date field based on the format mentioned, but still error is throwing. Kindly help to resolve the issue. enter image description here -
How to set data in Vuejs Mounted for amcharts?
I build restful APIs based on Django. It gives me: { "id": 1, "date": "2021-08-22", "team_name": "Juventus", "home_away": "AWAY", "name": "Dybala", "number": 9, "age": 27, "shots": 3, "SCA": 4, "touches": 54, "passes": 35 }, Now I want to visualize this data as a Radar Chart with amCharts. From the example amCarts store data like this: var data = [{ "category": "Lithuania", # should be Shots in my case "value": 501 # 3 }, { "category": "Czechia", #SCA "value": 301 }, ... { "category": "Germany", # etc "value": 165 }, }] My front end is on Vue and I do not know how to set data in the format amCharts is asking. Can I use a loop inside the Mounted function? Or it's better to change the format of the API? Or should I change the Model of my Django app? -
Django NFT architecture
I am quite new in NFT, just learning thing but i am good at django. I want to build NFT marketplace, Can i develop it with django? The question is very ameture i know but i don't know how it works, can anyone suggest me is it possible to develop NFT with django and reactjs? I found some snippet on internet of django and nft: from django.db import models class NFTProject(models.Model): contract_address = models.CharField(max_length=100) contract_abi = models.TextField() name = models.CharField(max_length=50) # e.g BAYC number_of_nfts = models.PositiveIntegerField() def __str__(self): return self.name -
Saving list in django database
I have a question about saving a list in Django database. Let me explain my problem, is pretty complex so I hope you understand that. At the base, I have a list of values (called learning objectives) where each student will have a grade from 1 to 5. Now, the idea is that the teacher, to give the evaluation, will press a checkbox corresponding to each grade and the database will create some sort of record to store the student's evaluation. models.py GRADING_VALUE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) class Grading(models.Model): value = models.CharField(max_length=10, choices=GRADING_VALUE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.value class LearningObjective(models.Model): name = models.CharField(max_length=300) mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING) grading = models.ForeignKey( Grading, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.ForeignKey( Note, on_delete=models.DO_NOTHING, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class MissionEntry(models.Model): mission = models.ForeignKey(Mission, on_delete=models.DO_NOTHING) log_entry = models.ForeignKey(LogEntry, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.mission) + ' ' + str(self.log_entry) class LearningObjGradingNote(models.Model): learning_objective = models.ForeignKey( LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True) grade = models.ForeignKey( Grading, on_delete=models.DO_NOTHING, blank=True, null=True) note = models.ForeignKey( Note, on_delete=models.DO_NOTHING, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py … -
Image files not importing Using Django
Hello Guys, I have one query in Django HTML. I was calling an image from the model in the HTML But it is not reflecting The code is listed below the below is the Models class UserProfileInfo(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='users1') portfolio_site = models.URLField(blank=True) bio = models.CharField(max_length=2000) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username the below is the Views files class UserDetailView(DetailView): context_object_name = 'users_detail' model = models.UserProfileInfo template_name = 'blog/user_detail.html' the below is the Html File {% extends "blog/base.html" %} {% load static %} {% block content %} <div class="container"> <h1>Welcome</h1> <table> <thead> <th>User Name</th> <th>portfolio_site</th> <th>bio</th> <th>profile_pic</th> </thead> <tr> <td>{{ users_detail.user }}</td> <td>{{ users_detail.portfolio_site }}</td> <td>{{ users_detail.bio }}</td> <td><img src="media/{{ users_detail.profile_pic }}" width ="300" alt="">media/{{ users_detail.profile_pic }} </td> </tr> </table> <p></p> <p><img src="media/profile_pics/denny.jpg" alt="hiiii">ho</p> </div> {% endblock %} -
typehead to get the refreshed list of data from the database in python django
file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a_c/p_s/" + "?term=mobile&category=store", }); source.initialize(); $("#search-bar").typeahead(null, { name: "suggestion", displayKey: "search_text", source: source.ttAdapter(), }); }); urls.py path('a_c/p_s/<term>/<category>', views.product_search,name='product_search'), views.py def product_search(request, term, category): pass I have a category dropdown and an input field for search text. I have to get the suggestion list from the database based on the changed value of category dropdown and input search text value I'm using typeahead . I don't know whether i'm doing it right or not with typehead bloodhound. Please if anyone could help me with that. I'm getting an error of url not found in console. -
How to merge QuerySets from the same model
I want to combine (|) a series of QuerySets:all_english_text in a loop: tag_result = Tag.objects.get(id=all_tag[index]) all_english_text = tag_result.notes.all().values('english_text', 'id') by the following def: def list_by_tag_post(request): # get POST all_tag = request.POST.getlist('tag_list') for index in range(len(all_tag)): tag_result = Tag.objects.get(id=all_tag[index]) all_english_text = tag_result.notes.all().values('english_text', 'id') result = list(chain(*all_english_text)) # Merging method all_english_text = result # to template context = {'all_english_text': all_english_text, 'all_tag': all_tag} return render(request, 'list_by_tag.html', context) 3 methods were tried, they all didn't work: result = list(chain(*all_english_text)) # Merging method 1 result = chain(*all_english_text) # Merging method 2 result = all_english_text.union(*all_english_text))# Merging method 3 -
Downloading Image from URL - from AWS S3 on flutter and saving it to the gallery FLUTTER
So prior to switching to AWS S3. I was using Gallery saver (https://pub.dev/packages/gallery_saver) I switched to hosting media files on AWS S3 (with django as my back end) and was trying to download an image. I pass in the URL(signed URL) that points to the media file in my aws s3 bucket and now its not downloading the image and saving it to the gallery. this is what I was using before, no code has changed: await GallerySaver.saveImage(url); is there any other way to save images from a url link to an AWS S3 object to your gallery in flutter. Am I doing something wrong? The image it self loads perfectly in flutter using CachedNetworkImage so I know the URL works and when I click the url in the browser, I'm able to access/download the image. -
How to set user type in a customuser model when a new user registers
I have two models CustomUser and Manager_profile given below. There are 2 types of users a manager and a customer. There is a form to register as a manager. How can I set the is_manager field to True when a manager registers? I also have another question. How can I store the data from department field to the Manager_profile model? #Models class CustomUser(AbstractUser): is_manager = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return self.first_name class Manager_profile(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) department = models.CharField(max_length=100) def __str__(self): return self.department #Form from django.contrib.auth.forms import UserCreationForm from account.models import CustomUser from django import forms class ManagerCreateForm(UserCreationForm): department = forms.CharField() class Meta: model = CustomUser fields = ['username','first_name','last_name','department'] -
Question regarding HTML form action attribute
I have used Django to set up the backend of a web app and have an HTML form I am using as a signup page and was wondering if there's anything I need to add to the Forms' form action attribute. What I am trying to do is grab the data that the user has posted it and send it over to PGadmin database. Here is my html form for reference: <div> {% block content %} <form action="" method="post" name="Userinfo" id="Userinfo"> <label for="fname">First Name</label> {% csrf_token %} <input type="text" id="fname" name="firstname" placeholder="Your first name.."> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Your last name.."> <label for="DOB">Date Of Birth</label> <input type="text" id="DOB" name="DOB" placeholder="The Date you were born"> <label for="Email">Email Address</label> <input type="text" id="Email" name="Email" placeholder="Your email address"> <input type="submit" value="Submit"> </form> {% endblock %} </div> P.S this isn't all the whole file, just a snippet. Also here is the views.py file that I have, which makes any imputed data get processed as a POST request vs as a GET. Not sure if there is anything I need to add in order to make it send the data to PGadmin. class CommentForm(forms.Form): fname = forms.CharField(max_length=25) lname = forms.CharField(max_length=25) dob = forms.datefield() …