Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to downgrade GDAL to version 2.4?
I'm trying to push my django app on heroku and i keep getting this message error. An error occurred while installing gdal==3.1.2! Will try again. remote: Installing initially–failed dependencies… remote: Collecting gdal==3.1.2 ... and Traceback (most recent call last): remote: File "/tmp/pip-build-oj843jp_/gdal/setup.py", line 257, in get_gdal_config remote: return fetch_config(option) remote: File "/tmp/pip-build-oj843jp_/gdal/setup.py", line 154, in fetch_config remote: raise gdal_config_error(e) remote: gdal_config_error: [Errno 2] No such file or directory: 'gdal-config' remote: remote: Could not find gdal-config. Make sure you have installed the GDAL native library and development headers. I think this is happening because i updated the GDAL because of a previous error message and seems that django only support the version 2.4. i download the 2.4.3 version files and i can't find the command to install it. i tried pip install gdal==2.4.3 still not working. I can't get the proper steps to get the right version. Can anyone point me into the right direction? I'm using a mac catalina -
Cant read static file CSS in Django Project
Cant read static file CSS in Django Project my html file looks where is a mistake {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %} {% endblock %}</title> <link rel = "stylesheet" href="{% static '/css/bootstrap.min.css' %}"> <link rel = "stylesheet" href="{% static '/css/style.css' %}"> <script scr = '{% static 'js/bootstrap.min.js' %}'></script> </head> <body class="bg-blue"> <div class="container"> <div сlass="row"> <div class="col-lg-4 col-lg-4"> <br/> <br/> <br/> <div class="panel panel-body"> <div class="panel-body"> <h3 class="text-center text-uppercase"><b>{% block heading %}{% endblock %}</b></h3> <br/> {% block content %}{% endblock %} </div> </div> </div> </div> </div> </body> </html> settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'TarFoodApp', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] where is a mistake ? in what dir I have to put my static file , now its in project root if needed more code of another files please tell me . -
Retrieve Duplicate XML Tags Python
I have an xml file from an API and I'm trying to grab the data from the duplicate <_field> tags. As you can see there is multiple <_field> tags. Right now my code will just grab the first <_field> tag it sees. How do I get it to do a check through the <_field> tags for a certain value im looking for. For example in this xml file, I want dads phone number. What would be the best way in a if statement to accomplish this ? Thanks Sample XML <student> <_extension_data> <_table_extension> <recordFound>true</recordFound> <_field> <name>motherdayphone</name> <type>String</type> <value>732-555-5555</value> </_field> <_field> <name>fatherdayphone</name> <type>String</type> <value>347-555-1234</value> </_field> </student> Example of Code for student in soup.findAll('student'): #XML Values psid = student.find('id').text print('---->%s' %psid) try: #Gets Instance of Student psid_obj = Student.objects.get(studentpsid=psid) # If Mom Doesnt Exist Create if not StudentInformation.objects.filter(studentpsid=psid_obj,relation = 1): try: mother = student.find("contact").find("mother").text mom_cell = student.find("_extension_data").find("_table_extension").find("_field").find("value").text mom_name = student.find("_extension_data").find("_table_extension").find("_field").find("name").text if mom_name == "motherdayphone": print('---->%s' %mother) print('---->%s' %mom_name) print('---->%s' %mom_cell) print("No record of Mom for this student, creating record with phone number") m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = 1, guardian_cell = mom_cell) m.save() # If Dad Doesnt Exist Create if not StudentInformation.objects.filter(studentpsid=psid_obj,relation = 2): try: father = student.find("contact").find("father").text father_cell = student.find("_extension_data").find("_table_extension").find("_field").find("value").text … -
Unable to get recent timestamp using Django ORM
For a selected filter, I currently have 3 timestamps in my database and I want the recent timestamp using ORM. 1) datetime.datetime(2020, 7, 22, 17, 02, 15, 28661, tzinfo=<UTC>) 2) datetime.datetime(2020, 7, 22, 17, 23, 25, 28661, tzinfo=<UTC>) 3) datetime.datetime(2020, 7, 22, 17, 37, 31, 28661, tzinfo=<UTC>) I am using the following Django ORM command to get the latest time which is 3rd one (22nd july, 17, 37) but it gives me (22nd july, 17, 23) due to the order its stored in database table_name.objects.filter(id="id_name").values('timestamp').first()['timestamp'] Instead of using first() / last() is there any ORM command to get the latest time? Please suggest where am i doing wrong -
ImageField returning null when there is a value in the database: Django
I am trying to retrieve values from my database, but I am not getting the response I am looking for. My question is how do I get the value that is under Image in my database entry? Database entry: ID Name Image ----------------------------- 11 "example" "myimager.jpg" When I retrieve a list, I get this response for this entry: { "image": null, "name": "example" } Model: class Images(models.Model): name = models.CharField(max_length=255) image = models.ImageField() View: class GetImageViewSet(viewsets.ReadOnlyModelViewSet): """ This ViewSet automatically provides `list` and `detail` actions. """ queryset = Images.objects.all() serializer_class = ImageSerializer permission_classes = (IsAuthenticated,) Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Images fields = ['image', 'name', 'url'] -
How to resolve CSS background image not loading on a Django template
Hey so I am trying to inject a background image to my Django template however for some reason I do not know why it not loading I tried inline styling on the html(** ) tag but nothing I the tried to to make an external css file but still not working can you please show me what I can be possibly doing wrong here. ** Below is the code to my html tag that I want to put the background image to** <div class="hero-wrap js-fullheight" data-stellar-background-ratio="0.5"> <div class="overlay"></div> <div class="container"> <div class="row no-gutters slider-text js-fullheight align-items-center justify-content-start" data-scrollax-parent="true"> <div class="col-md-6 ftco-animate"> <h2 class="subheading">Leave the house cleaning chores to us</h2> <h1 class="mb-4">Let us do the dirty work, so you don't have to.</h1> <p><a href="#" class="btn btn-primary mr-md-4 py-2 px-4">Learn more <span class="ion-ios-arrow-forward"></span></a></p> </div> </div> </div> </div> And here below is the external css file that I made to test if it would work having an external stylesheet .hero-wrap js-fullheight{ background-image: url('static/images/bg_1.jpg'); } If possible can you teach me how I can make inline background-image on the html tags using Django templates -
DateField in django forms
I am trying to use a DateField input in my django form. As far as I can tell, I have been following the documentation well, but it fails validation every time. Here's the form class- class dForm(forms.Form): date = forms.DateField(input_formats = ["%d/%m/%Y",]) This is the views file- def index(request): if request.method == 'GET': form = dForm() return render(request, 'index.html', { 'form' : form }) else: data = dForm(request.GET) if data.is_valid(): return HttpResponse('ok') else: return HttpResponse('not ok') And this is the template- <!DOCTYPE html> <html> <body> <form method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> </body> </html> (This is just a trial project, there aren't any other views or forms in it.) I found this answer with the same issue- https://stackoverflow.com/questions/9410058/django-forms-datefield-fails-validation but the solution didn't work for me. -
What path should I give if i give uploads_to="upload_folder" in EncryptedFileField from django_encrypted_file_filed?
I have used Django_encrypted_filefield for storing my files. It works fine if I don't specify uploads_to, but if i do i get "Reverse for 'url_name' with keyword arguments '{'path': 'folder/sub_folder/file'}' not found. 1 pattern(s) tried: ['\^\(\?P(?P[^/]+)\+$']" It would be great if someone could help me with this. -
how can i connect pythonanywhere to mongodb knowing that i'm using django to backend?
I'm trying to deploy my django app to pythonanywhere.com the problem is that i couldn't connect my app on that server to my mongodb database i already changed the mongo_client host to mongo url by going on pythonanywhere to /home/myusername/.virtualenvs/Myenv/lib/python3.8/site-packages/pymongo/mongo_client.py i changed the host to : HOST = "mongodb+srv://<myUsername>:<password>@<myCluserName>.rkait.mongodb.net/<MyDBname>?retryWrites=true&w=majority" (of course i changed the <> fields) But i'm getting this error [Errno 111] Connection refused,myClusterName-shard-00-02.rkait.mongodb.net:27017: [Errno 111] Connection refused so is there any solution to make that connection with mongodb ? and if that is not possible please recommend me another hosting website that support django and mongodb for free. -
WinError 10060 A connection attempt failed
settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER ='ponnamanjaneyulu1@gmail.com' EMAIL_HOST_PASSWORD = '#########' EMAIL_POST = '587' above are the settings for the Django core mail module. from django.conf import settings from django.core.mail import EmailMultiAlternatives emailFrom = [settings.EMAIL_HOST_USER] emailTo ='ponnamnarasimha1@gmail.com' text_content = 'Your content here' email_subject = "Subject here" msg = EmailMultiAlternatives(email_subject, text_content, emailFrom, [emailTo], ) msg.send() return HttpResponse('We have sent a email verification please check your email') I am using its EmailMultiAlternatives to send emails to users. When I try to build the program with the Gmail SMTP it throws the following error 'Errno 10060 A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'. I am doing this in my sample project, somewhere else, or let me know where I am going wrong. ? please help me thanks in advance -
Django with two different auth backends?
I haven't found my specific case in the Django docs. Let me describe the base application first: A django project, which is highly attached to the frontend. React Frontend consumes most, if not all of the API endpoints. Furthermore, there is going to be an app, that has to consume the backend endpoints. Now, the way django handles sessions and authentication is fine for a web browser, but managing cookies etc on the phone, and storing them seems iffy. Django generates a CSRF-Token and a sessionId after logging in. The Problem with that is, that the login endpoint already sits behind CSRF. Meaning: In order to login via the app, I will have to request a CSRF token from a manually made endpoint, and then store it, and then i can proceed to login. I have created a middleware that just ignores CSRF, when a certain header is passed in the request. It is a workaround, and also works, but i would much rather have a token based auth. So my idea was to switch to said token-based authentication, but as I found out via the docs, this doesnt seem to be possible out of the box. I went ahead … -
django: username field in User model not validating
Let me get straight to the point... I have this Modal Form class UpdateProfile(forms.ModelForm): profile_image = forms.ImageField(required=False) name = forms.CharField(max_length=150) class Meta: model = Profile fields = ( 'bio', ) Snippet of my class based view: if form.is_valid(): user = request.user.profile.person.id # Obtain User an Profile objects about the user userObj = users.User.objects.get(pk=user) profileObj = Profile.objects.get(person=user) # Get cleaned_data values name = form.cleaned_data.get('name') ProfilePic = form.cleaned_data.get('profile_image') bio = form.cleaned_data.get('bio') # Save changes # Better to check if changes were even made. Because we don't wanna overwork the database userObj.username = name userObj.save() So the problem is when this block is run: userObj.username = name userObj.save() The validations for username are not run. There can be a space in that field and i wont receive any sort of validation error. I tried to see if maybe this was valid, so i went into my admin panal, put in a space in a random users username and received the following form error Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters. -
Django - Getting none value
I have three models contact,male and female.I could update the male and contact but whenever I update the female it gets none instead of updating.And that none starts to get updating whenever i update the newly added contacts.If you like to check the whole codes here they are: veiws.py https://pastebin.com/ybi3U63y models.py https://pastebin.com/9u1GS6AA forms.py https://pastebin.com/xdgAtAsK urls.py https://pastebin.com/2icFqSK2 -
django.core.exceptions.ImproperlyConfigured error when attempting to execute script
I am trying to execute a python script that creates a bunch of objects to be stored in the database. However, when trying to execute the scripts file, with python scripts.py I get the following error: Traceback (most recent call last): File "scripts.py", line 4, in <module> from django.contrib.auth.models import User, Group, Permission File "/project_vm/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/project_vm/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/project_vm/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/project_vm/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/project_vm/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/project_vm/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/project_vm/lib/python3.6/site-packages/django/conf/__init__.py", line 61, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I am not sure what this means, and the answers that I've found have only confused me so far. Am I executing the script incorrectly? Or is there some other issue related to settings, and if so how can I resolve it? I am wondering if maybe it has something to do with my imports in the scripts file, as the scripts file is within a … -
How do I use variables as selectors in HMTL/ Bootstrap4?
I'm trying to make a for loop to build an accordion in Bootstrap, but every time I click the button to expand/ collapse a card, every card expands/ collapses. I think this is due to a shared id across all cards, so I want to use the post title as the id selector for each card. Here is the code I currently have: {% for post in blog_posts %} <div id="accordion"> <div class="card"> <h3 class="card-header" id="header"> <button class="btn btn-info" data-toggle="collapse" data-target="#body" aria-expanded="false" aria-controls="post: "> {{ post.title }} <small><p>Posted by {{ post.author }} on {{ post.date_added|date:'D M d, Y H:i' }}</p></small> </button> </h3> <div id="body" class="collapse show" aria-labelledby="header" data-parent="#accordion"> <div class="card-body"> {{ post.text|linebreaks }} <small> <a class="text-dark" href="{% url 'blogs:edit_post' post.id %}"> edit post</a> </small> </div> </div> </div> {% empty %} <p>There are no posts to display.</p> {% endfor %} I've tried changing the h3 id to {{ post.title }}, but that doesn't seem to work. Any help is much appreciated. -
Django ordering by parant and chield null field
I need to create query with a parent and child fields sorting. For example i have a parent model EmailsSettings(models.Model): email = models.EmailField(max_length=254, blank=True, null=True) child field one class EmailSubject(models.Model): email_settings = models.ForeignKey('EmailsSettings', on_delete=models.CASCADE, related_name='subjects') email_subject = models.TextField(max_length=1024, blank=False) and another: # email bodies class EmailBody(models.Model): email_settings = models.ForeignKey('EmailsSettings', on_delete=models.CASCADE, related_name='bodies') email_body = models.TextField(max_length=1024, blank=True) I need to create ordering - at the first list must be EmailsSettings which has email and EmailSubject must has email_subject OR EmailBody must has email_body, then at the list i need to have EmailsSettings which has email without EmailSubject and EmailsSettings then i need to have EmailsSettings which has no email but has EmailSubject must has email_subject OR EmailBody must has email_body So i created a simple query EmailsSettings.objects.filter(Q(user=self.user) & Q(last_check_mail__gte=self.start_date) & Q(last_check_mail__lte=self.end_date))\ .order_by(F('email').desc(nulls_last=True)) witch ordering by EmailsSettings -> email. Haw i can add child fields to query for ordering? -
how to get the value of a {{variable}} of django template in javascript?
I'm gettig value of img from views.py now i want that when user click on the image, it should open in a modal 1)index.html image sections <!-- Card body --> <div class="card-body"> {% for val in data.list %} <img src="{{val.Img}}" class="img-thumbnail pop_img"> {% endfor %} </div> index.html modal section <div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <img src="" class="imagepreview" style="width: 100%;" > </div> </div> </div> </div> main.js $(function() { $('.pop_img').on('click', function() { var img = $(this).find('img').attr('src') console.log(img) -----------------but on console it prints : undefined $('.imagepreview').attr('src', $(this).find('img').attr('src')); $('#imagemodal').modal('show'); }); }); and while inspecting on elements it shows <img src(unknown)> inside modal -
Calling function with "if" inside a "for" loop in django not working
{% if "Anonymous" == i.verifiedUser %} doesnt seem to work despite i.verifiedUser being valid. I can write anything else where "i.verifiedUser" is, and it will still show the same. How can i fix this? <div class="comments"> {% for i in comment %} {% if "Anonymous" == i.verifiedUser %} <small>{{i.verifiedUser}}</small> {% else %} <small class="verifiedUser">{{i.verifiedUser}}</small> {% endif %} <p class="commentTimestamp">{{i.timestamp|timesince}} ago</p> <p>{{i.commentText|urlize|linebreaksbr}}</p> <hr> {% endfor %} </div> -
Is redirecting to the same function a problem in Django surveys?
In my survey I have a 'loop' in one function. Everything runs fine when only 1 person answers the survey. But when other people answer it simultaneously, then there are problems because they get redirected to the same function and somehow they all "share" the loop together. How is it possible to redirect people to the function so they dont interfere, meaning that the survey runs independently on every computer/for every respondent? Now, when one person answers the question on template home2, he gets redirected to RandomDCE where the next template, which will be shown to him, is determined randomly. With only 1 respondent it runs fine. If multiple people answer the survey simultaneously, then they get redirected to RandomDCE and interfere somehow so that the order is wrong (I think because respondent 2 caused a random shuffle again). Can I create a template or function "RandomDCE" which is available for one person only? I tried to do this somehow by adding "[user_id]" to every variable. [...] def RandomDCE(request): global count, C1, C2, C3, C4, C5, C6, C7, C8 # Randomize the order of Choice Sets for each respondent if request.session['count%d' % (user_id)] == 0: global number_list, number_list2, choiceblock number_list … -
Field level validation with request.user in Django rest framework
I want to implement a field validation in a DRF Serializer. class StarterPicsSerializer(serializers.ModelSerializer): class Meta: model = StarterPics fields = '__all__' def validate_restaurant_review_id(self, value): if not RestaurantReview.objects.filter(restaurant_review_id=value, review_author=self.request.user).exists(): raise serializers.ValidationError('Not your review') return value My issue I that I can't pass request into my validate_restaurant_review_id because it accepts only two fields. AttributeError: 'StarterPicsSerializer' object has no attribute 'request'` I there a way to pass my user.request into the validation function? -
Django REST nested router with marking extra actions for routing
Currently, I use drf-extensions library to register a nested router like this: parent_registry = router.register("parent", ParentViewSet) parent_registry.register( "childrent", ChildViewSet, basename="parent-child", parents_query_lookups=["parent_key"], ) and marking extra actions for routing like this: class ChildViewSet(NestedViewSetMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): # do some stuff @action(detail=True, methods=['patch']) def my_method(self, request, pk=None): child = self.get_object() pass but getting the following error: my_method() got an unexpected keyword argument 'parent_lookup_parent_key' Can someone help me with the solution, Please? I've tried but still haven't seen any success. Thanks. -
function lower(integer) does not exist Django ORM postgres
I am using these filter backends and after shifting from SQLIte to Postgres I am facing this issue **Error is following** ProgrammingError at /e/all function lower(integer) does not exist LINE 1: ...ws_zips_newszip"."deleted" IS NULL ORDER BY LOWER("new... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Code is : filter_backends = (filters.SearchFilter,CaseInsensitiveOrderingFilter,) class CaseInsensitiveOrderingFilter(OrderingFilter): def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: new_ordering = [] for field in ordering: if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) return queryset.order_by(*new_ordering) return queryset -
How can I set default image in property if image is not available for a product in media file(django)
I am learning django from youtube channel(Dennis Ivy).I want to set default image in property if image is not found for a product.Please help me. -
Django, how to set duration field to be the diffrence between two datetime fields
I have a Django model where I'd like to calculate a duration field based on the inputted data from two DateTime fields and store the difference between them in hours: minutes (I'm not even sure the duration field is the right choice here. This is what I got so far. class CarEventsData(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="events_of_cow") out = models.DateTimeField(null=True, help_text="When the cow went OUT TO Pasture.") _in = models.DateTimeField(null=True, help_text="When the cow got back IN FROM Pasture.") duration = models.DurationField() def save(self, *args, **kwargs): """ Should set duration field to total time between out and in data. """ self.duration = self.out - self._in super(CarEventsData, self).save(*args, **kwargs) -
Ordering by a field in reverse side foreign key in Django
I have the following models class Question(models.Model): content=models.TextField() ... class Answer(models.Model): created_at = models.DatetimeField(auto_add=True) authors = models.ForeignKey(User, ... ) content = models.TextField() question = models.ForeignKey(Question, ....) ... class meta: unique_together=('author','question') in the database I have a set of questions and answers. answers are linked to their authors. unique_together ensures the user can give an answer only once to a question. usr_1 Is a user instance that has answers to some questions that I can retrieve by: qst_qs=Question.objects.filter(answer__author=usr_1) I want to sort questions in qst_qs according to the created_at field in usr_1 answer in each question. Thanks in advance.