Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
REACT: using a functional component in a class-defined class modal
I have a problem which I cannot solve: I started a ReactJS project and used the class definition for all components. Now I would like to add the following tool to my webapp: DragandDropApp. This tools uses the functional definition and now I need help on how to implement this / add this componenent to a modal, which was defined as a class. Is it in general possible to do that? If yes, could you help me on how to return/ render the component, so that I can add it to my app? Thank you very much in advance! Best, Simon -
How to display text in HTML from an array?
I have a project that I am working on. I call my Django API and I get a ManyToMany array back as seen below. [ {"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"} ] What is the best way to display the below in HTML as: Money Django Test Instead of [ {"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"} ] I am trying to pass the above into an HTML element and display on the frontend. Any and all help is appreciated! -
Django model form this field is required
I am new to Django. Trying to add data to database using ModelForm. But getting an error "This field is required.." My model: class Docstest(models.Model): uploader =models.ForeignKey("auth.User",blank=False,null=False,on_delete=models.CASCADE) nameOfApplicant = models.CharField(max_length=50,blank=False) serviceRequestedName= models.ForeignKey(ServicesOffered,on_delete=models.CASCADE,blank=False,null=False) nameOfDocument = models.ForeignKey(DocumentsRequired,on_delete=models.CASCADE,blank=False,null=False) documentFile = models.FileField(upload_to='documents/%M', blank = False, null = False) def __str__(self): return str(self.nameOfDocument)+str(self.uploader) forms.py class MyForm(forms.ModelForm): class Meta: model = Docstest fields = ["uploader", "nameOfApplicant","serviceRequestedName","nameOfDocument","documentFile",] labels = {"uploader":"uploader", "nameOfApplicant":"nameOfApplicant","serviceRequestedName":"serviceRequestedName","nameOfDocument":"nameOfDocument","documentFile":"documentFile",} my html {% extends 'base.html' %} {% block columncard %} <div class="container"> <form method="POST"> <fieldset> <legend>Form</legend> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </fieldset> </form> </div> {% endblock %} There is a error "This field is required". Data not saved in Database. Help. -
403 error trying to access main site - Django Apache Ubuntu
I am learning Django and have been trying to follow the tutorial here: https://www.youtube.com/watch?v=Sa_kQheCnds&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=14 This is a Python Django application which should run on Apache engine on Ubuntu on a Linode Server. However I can't get the production to work. When I was on the step of running the app on Django server via 0.0.0.0:8000 port it worked, when I got to the point where according to video everything should work, via HTTP 80 port, it gives me 403 error saying "You don't have permission to access this resource" I have looked through some similar posts, but they have not helped to solve my problem or I did not understand how should I apply the solution. How can I check what causes this problem? What parts of code can I provide to help to solve it? -
How to solve dependency conflicts in requirements.txt file in Django deployment
I am trying to deploy my Django app on GCP using google appengine. First I deployed the app after testing on localhost by following this documentation by Google appengine. deployed the app using gcloud app deploy But there is some issue and the server is not running showing the error as 502 Bad Gateway Then I checked the logs and then realized that I forgot to upload the requiremts.txt file. the uploaded file and tried to deploy the app again. But got an error as ERROR: Cannot install -r requirements.txt (line 19), -r requirements.txt (line 21), -r requirements.txt (line 27) and grpcio==1.48.1 because these package versions have conflicting dependencies. Here is some dependency conflict between modules Gcloud suggested a documentation https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts to solve this but I'm not getting it actually how to solve the conflict of modules in requirements.txt Here is the requirements.txt file APScheduler==3.6.3 asgiref==3.5.2 backports.zoneinfo==0.2.1 beautifulsoup4==4.11.1 cachetools==4.2.2 certifi==2022.6.15 charset-normalizer==2.1.1 dill==0.3.5.1 Django==4.0.6 django-environ==0.9.0 django-social-share==2.3.0 environ==1.0 google==3.0.0 google-api-core==2.10.0 google-auth==2.11.0 google-cloud-secret-manager==2.12.4 google-cloud-speech==2.15.1 googleapis-common-protos==1.56.4 grpc-google-iam-v1==0.12.4 grpcio==1.48.1 grpcio-status==1.48.1 idna==3.3 Pillow==9.2.0 proto-plus==1.22.1 protobuf==4.21.5 psycopg2==2.9.3 pulumi==3.39.3 pyasn1==0.4.8 pyasn1-modules==0.2.8 pytz==2022.2.1 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0 requests==2.28.1 rsa==4.9 semver==2.13.0 six==1.16.0 soupsieve==2.3.2.post1 sqlparse==0.4.2 tornado==6.2 tzdata==2022.1 tzlocal==4.2 urllib3==1.26.12 And an error log Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build … -
How to pass a dict to a unit test using parameterized?
I have a list of dicts: MY_LIST = [ { 'key1': {'a': 1, 'b':2 } }, { 'key2': {'a': 1, 'b':2 } } ] How do I pass the dict to a django unit test using parameterized? E.g. @parameterized.expand(MY_LIST): def test_mytest(self, dict_item): print(dict_item.items()) Results in AttributeError: 'str' object has no attribute 'items' because the dict is being converted to a string. -
Django ImageFiled thumbnail from video
I need to make a thumbnail from a video and save it to Django's ImageField. I already have the working code which saves the thumbnail to a specified folder but what I want is to redirect the output of FFmpeg directly to Imagefield (or to a in memory uploaded file and then to Imagefield) This is my current code: def clean(self): file = self.files['file'] output_thumb = os.path.join(settings.MEDIA_ROOT, 'post/videos/thumbs', file.name) video_input_path = file.temporary_file_path() subprocess.call( ['ffmpeg', '-i', video_input_path, '-ss', '00:00:01', '-vf', 'scale=200:220', '-vframes', '1', output_thumb]) self.instance.video = self.files['file'] self.instance.video_thumb = output_thumb I'd like to do it so that I wouldn't need to specify the folder to save the thumb in (output_thumb in the code) and for Django to save it automatically using the upload_to='post/videos/thumbs option in the model definition Please point me in the right direction of how to do this. -
Django filter queryset for each item
I cant think of a good logic myself so I hope that somebody could help me out. The goal is this: I have a date which a user can enter, a from_date, prognosis_hour, to_date and default_hour. I need to filter from the employee_set each employer who has a from_date with his prognosis_hour within the range of the date which a user enters, to sum it with other employee hours, the twist is, when there are employees without from_date with prognosis_hours, then default_hour should be used. Now I have this @property def prognosis(self): mylist = [] for e in self.employee_set.exclude(prognosis_hours__isnull=True, from_date__isnull=True): for i in self.employee_set.filter(from_date__gte=self.entered_date, to_date__lte=self.entered_date): e.default_hours mylist.append(i.prognosis_hours) mylist.append(e.default_hours) return mylist right now it filter everybody within the entered date and append it to the list, showing default and prognosis hours, but ignores everybody else with default hours In the end it should just sum all default and prognosis hours together when prognosis hours are within range of the date today or the entered date from user I know that the sum is missing and that I can append it together etc. it is copied from my debugging process class work(models.Model): entered_date = DateField() @property def prognosis(self): mylist = [] for … -
convert django to nextjs mongoose
I need convert this django code to mongoose nextjs BonusRefill.objects.values('user').order_by('user').annotate(total_price=Sum('amount')).order_by('total_price').last() i tried this but not working BonusRefill.find().sort('user') -
Django - Using month from datetime in model filter
I have a model called Watch with a datefield called date and I want to only show the objects from that model that have the same month as the current month. I tried: Watch.objects.filter(date.month=now.month).order_by('-day') But this appeared not to be possible. How can I achieve this? -
Model infos not showing up on HTML page Django
I am trying to create an educational website using Django, so when I am trying to render {{ profile.institution }} or {{ profile.grade }} or {{ profile.user.username }} they are not being rendered.I don't know why they aren't. Can anyone help me solve this? My models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.CharField(max_length = 100) grade = models.CharField(max_length=100, choices= YEAR_IN_SCHOOL_CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' My views.py: class User_Profile(LoginRequiredMixin, ListView): model = Profile template_name = 'class/profile.html' context_object_name = 'profile' def get_queryset(self): return Profile.objects.filter(user=self.request.user) My html: {% extends "class/base.html" %} {% load crispy_forms_tags %} {% block content %} <br> <div class="row d-flex justify-content-center"> <h1 style="color: #f5a425">Hello {{ user.username }}</h1> </div> <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-7"> <div class="card p-3 py-4"> <div class="text-center"> <i class='fas fa-user-alt' style='font-size:36px'></i> <!-- <img src="" width="100" class="rounded-circle"> --> </div> <div class="text-center mt-3"> <span class="bg-secondary p-1 px-4 rounded text-white">Pro</span> <h5 class="mt-2 mb-0">{{ profile.user.username }}</h5> <span>{{ profile.institution }}</span> <span>{{ profile.grade }} Grade</span> <div class="px-4 mt-1"> <p class="fonts">{{ profile.bio }}</p> </div> <div class="buttons"> <button class="btn btn-outline-primary px-4">Message</button> <button class="btn btn-primary px-4 ms-3">Contact</button> </div> </div> </div> </div> </div> </div> {% endblock content %} -
Как добавить элементы по кнопке вместо прокрутки?
у меня есть такой код для бесконечной прокрутки masonry с фото и пагинация на django. Я хочу чтобы по нажатии на кнопку добавлялись элементы в masonry вместо прокрутки до конца блока. В основном я находил вариант загружать все элементы masonry, а потом по кнопке делать их видимыми, но мне такой способ не нравится, ведь фото может быть бесконечно много. translation via google translator. I have this code for infinite scrolling masonry with photos and pagination on django. I want the button to add elements to masonry instead of scrolling to the end of the block. Basically, I found an option to load all the masonry elements, and then click on the button to make them visible, but I don't like this method, because there can be infinitely many photos. jQuery(window).on('load', function(){ var container = $('#gallery'); container.imagesLoaded(function () { container.masonry({ itemSelector: '.item-masonry', percentPosition: true, transitionDuration: '0', }); var infinity = new Waypoint.Infinite({ element: $('.infinite-container')[0], container: 'auto', items: '.infinite-item', more: '.infinite-more-link', offset: 'bottom-in-view', loadingClass: 'infinite-loading', onBeforePageLoad: function() { }, onAfterPageLoad: function() { container.masonry('reloadItems'); // $(container).masonry('layout') container.imagesLoaded().progress( function() { container.masonry('layout'); }); } }); }); }); class IndexImg(ListView): model = ImageFile template_name = 'images.html' context_object_name = 'images' paginate_by = 15 -
Django POST request is empty
Running Django 4.1.1. Having this code below in template. By clicking a button it sends a data to delete apropriate marker. <form method="POST"> {% csrf_token %} <ol> {% for marker in markers %} <li> {{ marker }} - <button class="button btn-primary" id="delete" value="{{ marker.pk }}" type="submit">Delete</button> </li> {% endfor %} </ol> </form> In views.py def user_markers(request): markers = Marker.objects.filter(owner_id=request.user.id).select_related() if request.method == "POST": print(request.POST.get("delete")) # gives me None marker = Marker.objects.get(pk=request.POST.get("delete")) marker.delete() context = { "markers": markers, } return render(request, "hub/markers.html", context) The problem is that request.POST.get("delete") is empty. POST data has only 'csrfmiddlewaretoken' Do I miss something? -
How to execute multiple sql queries in django.db with execute - SET PREPARE EXECUTE
How can I execute this statement in django.db SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when field_key = ''', field_key, ''' then field_value end) ', field_key ) ) INTO @sql FROM Meeting; SET @sql = CONCAT('SELECT Meeting_id, ', @sql, ' FROM Meeting GROUP BY Meeting_id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; with connection.cursor() as cursor: cursor.execute(query) rows = cursor.fetchall() I try to execute the sql as a string but it returns no results, apparently django's .execute() can only execute one configuration at a time. -
Djoser logout from Vue Frontend
Currently using Vue as my frontend and Django as backend API. Trying to have user logged out when clicking on logout button. Not sure what is all needed in order to log user out. When I click on the logout button, nothing is happening and just pushing to /logout route where I have the router linked to the file. When I click the logout button, user is still logged in. Not worried about the routing, but more concerned about actually being able to log out. Login export default { name: 'Login', data () { return { username: '', password: '', errors: [] } }, methods: { submitForm(e) { axios.defaults.headers.common["Authorization"] = "" localStorage.removeItem("token") const formData = { username: this.username, password: this.password } axios .post("/api/v1/token/login/", formData) .then(response => { const token = response.data.auth_token this.$store.commit('setToken', token) axios.defaults.headers.common["Authorization"] = "Token " + token localStorage.setItem("token", token) this.$router.push('/project-dashboard') }) .catch(error => { if (error.response) { for (const property in error.response.data) { this.errors.push(`${property}: ${error.response.data[property]}`) } console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } } Logout export default { name: 'Logout', data () { return { username: '', password: '', errors: [] } }, methods: { onclick(e) { axios.defaults.headers.common["Authorization"] = "" … -
Failed to load resource: the server responded with a status of 500 (Internal Server Error) server cannot be a server error
When I run it in visual, it works, but when I deploy it to the server, the part with the url is https://domain/finance/ error $.ajax({ url: 'http://127.0.0.1:8000/finance/', beforeSend : function(jqXHR, settings) { jqXHR.setRequestHeader("x-csrftoken", '{{ csrf_token }}'); }, data: data, processData: false, method: 'POST', contentType: false, enctype: 'multipart/form-data', success: function ( qayidanData ) { if( qayidanData == "True"){ $('.requiredS2, .requiredS1').each(function () { $(this).val(''); }); $('#step2').hide(); $('#step1').show(); Swal.fire('You have successfully registered'); } } }); jquery-3.6.0.min.js:2 XHR failed loading: POST "https://turbohub.ca/finance/". send @ jquery-3.6.0.min.js:2 ajax @ jquery-3.6.0.min.js:2 (anonymous) @ (index):433 dispatch @ jquery-3.6.0.min.js:2 v.handle @ jquery-3.6.0.min.js: -
Import "django.core.management" could not be resolved from source
Import "django.core.management" could not be resolved from source I am getting this error not able to clear it enter image description here -
How to search text inside a database in Django
I have to search using a collection of words in a database. The sequence of the words doesn't matter. For example: `"How to build a computer" is a string in the database. I should be able to get this result by just putting in the string "build computer". Currently, I am using a sqlite3 database with Django. I tried solving the problem by splitting the words in the query and then looping through the database to check if the word was in the records of the database. The more words of the query are in the record, the higher the ranking of that particular record in the database. But my approach involves splitting each record in the database, and then search all of the records using every word in my search query. Is there any way to optimise my algorithm? -
Django annotate with other model attributes based on a common field
I have a User model, class User(AbstractBaseUser): id = models.IntegerField(primary_key=True) email = models.EmailField(unique=True) I have another model named Company. The Company model has a reference to User model via an Integer field. class Company(models.Model): user_id = models.IntegerField(db_index=True) name = models.CharField(max_length=100) size = models.IntegerField(default=1) I wanted to extract the company information along with user information. basically I want a user object dictionary like this {'id':1, 'email':'abc@gmail.com','name':'foobar.co','size':400} I want to annotate the user objects with name and size. As of now, I tried in the serializer's to_representation method. However, for millions of users this is super slow. class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField(read_only=True) def to_representation(self, instance): response = super(UserSerializer, self).to_representation(instance) company = Company.objects.filter(user_id=instance.id) if company.exists(): company = company.first() response['name'] = company.name response['size'] = company.size return response How can I achieve this annotation in the query itself. -
Consuming External API Using Django Generic CBVs
If I want to consume an external API within a generic class based view in Django, can I add a method to the generic view including a get request? I need to pass parameters from the data model in the request payload in order to illicit a response, and I fundamentally do not understand how to do this. I was hoping someone could point me in the direction of a tutorial or something to help me out, as I have done hours of searching and I cannot find anything that is within an existing CBV. Thanks! -
Django static files troubleshooting for production
BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INSTALLED_APPS has 'django.contrib.staticfiles' This is how they're called in HTML <img src="{% static 'capabilities-2.jpg' %}" class="img-fluid"> Displayed in my console: [10/Sep/2022 17:39:50] "GET /css/index_styles.css HTTP/1.1" 404 179 [10/Sep/2022 17:39:50] "GET /js/scripts.js HTTP/1.1" 404 179 [10/Sep/2022 17:39:51] "GET /static/index/images/capabilities-2.jpg HTTP/1.1" 404 179 [10/Sep/2022 17:39:51] "GET /assets/favicon.ico HTTP/1.1" 404 179 Trying to transition from Dev to Production. I had the images working in development. If I inspect the images (or lack of images) within a browser, the path is as follows: Should be noted that I can't even see them when inspecting the source. I tried adjusting the paths /static/capabilities-2.jpg to /static/index/images/capabilities-2.jpg as it is in my project but that still didn't work. I'm running on Linode, Ubuntu 22.04. I like a lot about Django, but static files are being a huge PIMA. -
How do I make a user balance in django?
I want to make a user balance. And I want to make sure that the user, before buying something, first replenishes this balance through the payment system and only then makes purchases. And also, so that when making a purchase, part of the funds went to the seller, and part went to the service. How can this be implemented since I'm new to django? -
When trying to pass in a post it is not working
<html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> </body> </html> class Post(CreateView): fields = ("title","about","itempicture") template_name = "post.html" model = models.Listing I can't seem to figure out why is is not working my html and views connect perfectly put when try to send in a post request it does not work I would happy if someone could help me out -
What is the best way to search in multiple fields in django?
I have the following model in my models.py, and I want to search based on its three fields. class Profile(models.Model): username = models.CharField(max_length=128, null=False, blank=False, unique=True) password = models.CharField(max_length=128, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) lastname = models.CharField(max_length=50, null=True, blank=True) parent = models.ForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) There are also three separate inputs for entering the text, one for name, one for last name, and one for username. The user should at least fill in one input, or if the input string was a part of main string, the main string should be returned. This is my API, but it does not return anything, and the result list is always empty. def search_users(request): if request.method == 'GET': try: to_be_searched_username = request.GET.get("username", None) to_be_searched_name = request.GET.get("name", None) to_be_searched_lastname = request.GET.get("lastname", None) supervisor_username = request.headers['Authorization'] supervisor = Profile.objects.get(username=supervisor_username) if not((to_be_searched_name or to_be_searched_lastname) or to_be_searched_username): return Response({"message": "Enter a search term"}, status=status.HTTP_204_NO_CONTENT) else: results = supervisor.children.filter( username__icontains=to_be_searched_username and to_be_searched_username is not None ).filter( name__icontains=to_be_searched_name and to_be_searched_name is not None ).filter( lastname__icontains=to_be_searched_lastname and to_be_searched_lastname is not None ) return Response({'results': results}, status=status.HTTP_200_OK) except: return Response({"message": "خطا در دریافت اطلاعات"}, status=status.HTTP_400_BAD_REQUEST) I will be grateful for any help or advice. -
what is a function inside a function in django/python
I wanna know, what is main idea function inside a function in djanggo?, something like this example. def partition_by_mod(base): def func(n): return n % base return staticmethod(func) when I call this function like this test = partition_by_mod(8), so I'm wondering where the "n" comes from. thank you ~