Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please help I cannot import django
enter image description here]1 pls tell me what I gotta do to fix this error -
Firewall restricting Django Server
I am running django server on my local ip (192.168.86.122:8000) but the windows firewall seems to block the connection. Any suggestion would be really helpful. -
Django queryset values list with annotated count of distinct related values
I have models Software and Domain described loosely as: class Software(models.Model) id = models.BigInteger(primary_key=True, db_index=True, null=False) company = models.ForeignKey('Company') domain = models.ForeignKey('Domain') type = models.CharField(null=False) vendor = models.CharField(null=False) name = models.CharField(null=False) class Domain(models.Model): id = models.BigInteger(primary_key=True, db_index=True, null=False) type = models.CharField() importance = models.DecimalField(max_digits=11, decimal_places=10, null=False) And I get a Software queryset with: qs = Software.objects.filter(company=c).order_by('vendor') The desired result should have an aggregated Domain importance with total count for each unique Software, i.e. [ { 'type': 'type_1', \ 'vendor': 'ajwr', | - unique together 'name': 'nginx', / 'domains': { 'total_count': 4, 'importance_counts': [0.1: 1, 0.5: 2, 0.9: 1] }, }, { ... }, ] I'm lost at trying to aggregate the importances separately. I annotate the original queryset with qs.annotate(importance=F('domain__importance')) and can get unique non-domain values with just a .order_by('name').values('type', 'vendor', 'name').distinct() but have no clue how to go forward from here. Do I need a subquery to do the importance aggregation? Would getting a separate queryset just for the related Domains make this easier (using some form of id__in with the Software qs)? Faster is better -
django login using email instead of username passing email but its checking username
I am unable to login with email but I am able to do it with username. How do I login with email instead of username. This is my html page : I tried to pass email instead of username but unable to login This is my views.py file: When i try to authenticate by change username to email, it is printing "invalid login details supplied!" This is forms.py: -
Django: "python manage.py runserver" not working
I am getting an error File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax when running python mange.py runserver error image from ubuntu terminal -
How to Host Python, Django, PostgreSQL Application on IIS 10
Hope Everyone will be fit and fine. I am trying to host my Django application on windows 2016 server IIS server. I had used Python, Django, pipenv as virtual environment and PostgreSQL as Database. I had tried almost tried everything available on the internet but till now I am not successful. maybe I have not got the perfect tutorials or find the correct one to host the Django Application. Please help me host the Django Application on IIS 10. I will be really grateful for the help Thanks in Advance. Regards Sachin -
Trying to edit post: Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/edit/(?P<pk>[0-9]+)$']
I am trying to be able to edit the question with an tag which references my edit_post function in my views.py. I think the issue is because I haven't passed in the context into the right view for it to be displayed but I am not sure how to fix it. Getting this error - Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['users/(?P[^/]+)/edit/(?P[0-9]+)$'] Views.py @login_required(login_url='sign_in') def dashboard(request, *args, **kwargs): username = request.user.username filtered_questions = Question.objects.filter(user_id=username) context = { 'filtered_questions': filtered_questions, } return render(request, 'users/dashboard.html', context) def edit_post(request, pk): question = Question.objects.get(pk=pk) if rerquest.method == 'POST': form = QuestionForm(request.POST, instance=question) if form.is_valid(): form.save() question.user = request.user return redirect('/') else: form = QuestionForm(instance=question) else: form = QuestionForm(instance=question) context = { 'form': form, 'question': question, } return render(request, 'users/edit_question.html', context) Urls.py urlpatterns = [ path('<username>', views.dashboard, name='dashboard'), path('<username>/upload', views.upload, name='upload'), path('<username>/edit/<int:pk>', views.edit_post, name='edit') ] Template with the edit question button <a href="{% url 'edit' question.pk %}"> -
Download link or View link to a file
i have a list of document from my models, one of the fields is a path to the url. how can i make a button such that when i click it, it opens the file. I have tried some methods but it didn't work well Thanks This is the html {% for document in document_lists_doc %} <tr> <th>{{forloop.counter}}</th> <th>{{document.date}}</th> <th>{{document.name}}</th> <th>{{document.url}}</th> <th>{{document.memo}}</th> </tr> {% endfor %} This is the Model class PurchaseOrderDocument(models.Model): po_number = models.ForeignKey(PurchaseOrder, on_delete=models.SET_NULL, null=True) date = models.DateField() name = models.CharField(max_length=100) url = models.FileField(upload_to='static/files/', null=True, max_length=500) memo = models.CharField(max_length=200) def __str__(self): return self.name kindly check the image, i will like that path to be a link to open the file when clicked -
Django Rest Framework - Fill model field with previous entry value
I'm starting to build a REST API with Django for studies proposes and I kinda encounter an obstacle to me. I have a model like class ExampleModel(models.Model): name = models.CharField(max_length = 36) class_type = models.CharField(max_length = 10) timestamp = models.PositiveIntegerField() last_timestamp = models.PositiveIntegerField() and a serializer with: class ExampleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ExampleModel fields = '__all__' read_only_fields = ['timestamp', 'last_timestamp'] def create(self, validated_data, **kwargs): validated_data['timestamp'] = int(datetime.timestamp(datetime.now())) #validated_data['last_timestamp'] = ... return ExampleModel.objects.create(**validated_data) I would like to fill the "last_timestamp" field with the "timestamp" value of the last entry that matches with the "class_type" of the current one. Using the psycopg2 lib a simple solution could be: last_entry_query = 'SELECT max(id) FROM example_table WHERE class_type = %s' % current_type get_timestamp = 'SELECT timestamp FROM example_table WHERE id = (%s)' % last_entry_query cur.execute(get_timestamp) try: ts = cur.fetchone()[0] except: ts = 0 and use the "ts" value to add to the next entry, I'm kinda new with the Django and DRF, but I assume that is a proper way to do that correctly or at least more pythonic, if anyone could help it would be amazing. -
How to get OTP token for an existing user in django using django-two-factor-auth
I am writing selenium tests for django. I want to login a user with OTP through UI using selenium. After login , I get the setup page where I am supposed to enter a 6 digit token generated by google authenticator. django-two-factor-auth stores a secret key per user in table otp_totp_totpdevice . I assume google authenticator is supposed to use this key to generate the token. Following is what I have tried so far: it generates a wrong token. import hmac, base64, struct, hashlib, time def get_hotp_token(secret, intervals_no): key=base64.b64decode(secret,validate=True) msg = struct.pack(">Q", intervals_no) h = hmac.new(key, msg, hashlib.sha1).digest() o = h[19] & 15 h = (struct.unpack(">I", h[o:o + 4])[0] & 0x7fffffff) % 1000000 return h def get_totp_token(secret): return get_hotp_token(secret, intervals_no=int(time.time()) // 30) -
How can I get the image to show in the img container, using Django template tags?
So I am at the last couple details of my portfolio website, and everything has gone relatively smoothly. I have not had an issue with images before, but this time I am using a {% for loop %} to iterate over the code for the card and I just have the variable template tags that create a new object every time I add something new in the django admin interface. I feel like there is some small detail I am just completely missing, because I had it working at one point, but then decided to do the iteration instead of hard-coding it in, and it just won't show up. Another pair of eyes would be nice. This is the section of my index.html: {% block content %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Jordan Miracle</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/static/portfolio/style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <body> <div class="jumbotron text-center ui-datepicker-next-hover" style="margin-bottom:0"> <div class="align-center"> <img src="{% static 'portfolio/mylogo.png' %}" id="img-bastet" class="img-fluid" alt="Jordan and Bastet"> </div> <h1><p style="font-family: 'Ubuntu Mono', Monospaced, monospace; font-size: medium;">Developer and Aspirant Data Scientist</p> </div> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <a class="navbar-brand" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" … -
Docker-Compose with neo4j and Django runs into connection error
I'm trying to run my Django application with Neo4j using the django_neomodel plugin but for some reason it seems like my docker compose file may be set up incorrectly: version: '3' services: db: image: postgres # Change to dynamic creds creation this is fine for local deployment for now environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres neo4j: image: neo4j restart: unless-stopped ports: - 7474:7474 - 7687:7687 volumes: - ./conf:/conf - ./data:/data - ./import:/import - ./logs:/logs - ./plugins:/plugins environment: # Raise memory limits - NEO4J_dbms_memory_pagecache_size=1G - NEO4J_dbms.memory.heap.initial_size=1G - NEO4J_dbms_memory_heap_max__size=1G - encrypted=False web: environment: - DB=POSTGRES build: . image: stupidfatcat/herlocksholmes command: python herlocksholmes/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "127.0.0.1:8000:8000" depends_on: - db - neo4j But whenever I run python manage.py install_labels I run into: File "/usr/local/lib/python3.8/site-packages/neobolt/direct.py", line 843, in _connect raise ServiceUnavailable("Failed to establish connection to {!r} (reason {})".format(resolved_address, error)) neobolt.exceptions.ServiceUnavailable: Failed to establish connection to ('::1', 7687, 0, 0) (reason [Errno 99] Cannot assign requested address) So it seems like my web container can't reach the neo4j container. What am I doing wrong? -
ModelForm has no attribute fields in Django Forms
I am trying to set the initial value of my choice field dynamically in my views, however, I face an error: AttributeError: type object 'CourseForm' has no attribute 'fields' My form is: class CourseForm(forms.ModelForm): course_code = forms.CharField( label='', max_length=20, min_length=5, required=True, validators=[alphanumeric_v2], widget=forms.TextInput( attrs={ "placeholder": "Course Code", "class": "form-control" } ) ) course_university = forms.ChoiceField( label='', required=True, choices = UNIVERSITY_CHOICES, widget=MySelect( attrs={ "class":"form-control" } ), ) class Meta: model = Course fields=('course_code','course_university',) And inside my views.py: form = CourseForm() form.fields['course_university'].initial = (request.user.university,request.user.university) How can I set the initial value of the Choice field dynamically inside my views? -
Id is required Formset editing Django
I'm trying to edit my values for 2 formsets. I'm using a inline formset in one of the forms. I can create data just fine, but updating is not working. What can be wrong? Here is my code. models.py class Projeto(models.Model): nome_projeto = models.CharField('Nome do Projeto', max_length=200) def __str__(self): return self.nome_projeto class Colaboradores(models.Model): projeto = models.ForeignKey(Projeto, on_delete=models.CASCADE, related_name='colaboradores') colaborador_projeto = models.CharField(max_length=200, blank=True) def __str__(self): return self.colaborador_proje forms.py from django import forms from .models import Projeto, Colaboradores class PostForm(forms.ModelForm): class Meta: model = Projeto fields = '__all__' nome_projeto = forms.CharField(label='Nome do Projeto:', required=True, widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) views.py def editar_projeto(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = PostForm(instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(instance=projeto_editar) context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = PostForm(instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(request.POST, instance=projeto_editar) if form.is_valid() and form_colab.is_valid(): projeto_editado = form.save() form_colab.instance = … -
Failure of Two forms to work in django template
form template please help me out I have tried three different methods to make sure my two forms submit on a page but i keep getting unbound error, i don't know why thats happening. kindly help, thanks these are my views -
How to extend django admin site template into custom view?
I have created a custom admin view as shows in below picture. It’s name is Duplicate Person Model. I followed this link which has steps, https://learnbatta.com/blog/how-to-add-custom-views-to-django-admin-91/ When I click on it it looks like this. I have added only a label and input box. What I am expecting is it should carry the same design as admin site. But I am not sure how do I implement it. There are different links on page however not sure which one is correct. Please advise. -
Failed to import the Cloud Firestore library for Python - Django Visual Studio
I am trying to use firebase in my python django project. This is on a windows machine using visual studio. I get the error "Failed to import the Cloud Firestore library for Python" when I try to import it: import firebase_admin from firebase_admin import firestore I have tried everything I can find through google including: Manually installing grpcio Downgrading protobuff to various versions. This one actually just ends up with a different error depending on which version of protobuff I go with. Uninstalling and re-installing google-cloud-store and all other dependencies Re-installing and upgrading pip And several other minor things over the course of the day that I can't recall. I am at a dead end after a full day of bashing my head against this. Any other solutions or even a direction to look in? Here is installed packages list: CacheControl 0.12.6 cachetools 4.1.1 certifi 2020.6.20 cffi 1.14.2 chardet 3.0.4 defusedxml 0.6.0 diff-match-patch 20200713 Django 2.2.16 django-import-export 2.3.0 docutils 0.16 et-xmlfile 1.0.1 firebase-admin 4.3.0 google-api-core 1.22.2 google-api-python-client 1.12.1 google-auth 1.21.1 google-auth-httplib2 0.0.4 google-cloud-core 1.4.1 google-cloud-firestore 1.9.0 google-cloud-storage 1.31.0 google-crc32c 1.0.0 google-resumable-media 1.0.0 googleapis-common-protos 1.52.0 grpcio 1.32.0 httplib2 0.18.1 idna 2.10 jdcal 1.4.1 MarkupPy 1.14 msgpack 1.0.0 mysql-connector-python 8.0.21 odfpy 1.4.1 … -
Vue app fetches API data, and objects seem toad into my template, but the text does not appear
I have created a Vue app that fetches data from my Django REST API and shows it on a page. The data consists of a list of objects that resemble {'name': Whitney Portal, 'parent': Inyo National Forest', 'camp_id': 232123} I have an input field that users can type text into, and the Vue app will dynamically display all objects that contain the input text. It appears to be that the app is loading objects into the template, but none of the desired text is showing. I want to show the camp attributes, such as the name for each object. I have attached a random string 'I'm HERE!' in the html to each object generated, so I can see how many objects are displayed at any one time. However that is the only text showing for each object. When I type into my input field, the number of objects (and instances of 'I'm HERE!') changes. The objects respond as expected (I know what text to type into the box to make only one object show). For example, if I type in 'Inyo' then only one object remains (because only one of the objects in my database has 'Inyo National Forest' as … -
How to ignore or skip null values of table when filtering in Django?
I want to ignore or skip a filter clause when the data of that clause is null in the DB, in my case sometimes the digital_exp_score variable is Null, but I need to filter by that variable, the normal filter would be like this: review = Review.objects.get(id=review_id) offers = OfferGeneric.objects.filter( is_personalized=True, digital_exp_score__gte=review.digital ) But when digital_exp_score is Null it won't work, I want to ignore those cases and just pass that condition, How I do that? I have tried with the When Clause: offers = OfferGeneric.objects.filter( is_personalized=True, When(digital_exp_score__isnull=False , then=(digital_exp_score__gte=review.digital) ), ) And offers = OfferGeneric.objects.filter( is_personalized=True, digital_exp_score__gte=When( digital_exp_score__isnull=False, then=review.digital ), ) But neither works, I get syntax error, those methods are only for the value at the right of the condition? Is there any method for checking the values at the left of the condition (the DB values)? Something like this would be ideal: offers = OfferGeneric.objects.filter( is_personalized=True, digital_exp_score__gte=review.digital if digital_exp_score is not None else pass ) -
How to get real-time status updates of Django REST API task?
I have a Django REST API. When i hit GET request on this API, this executes my six python selenium bots one by one, And then returns the status of all bots with 200 code. The problem is that bots take too long to execute, so i want the status of first bot when it completes, then status of second bot, etc in the same GET request like Real Time updates. How can i achieve this? -
Changing Django's model attribute value
in models.py class Auction(models.Model): id = models.AutoField(primary_key=True) name=models.CharField(max_length=64) in views.py def Listing(request,Person_id): Per=Person.objects.get(pk=Person_id) if request.method=="POST": Per.name=(request.POST["Rename"]).cleaned_data Per.save() return render(request,"Projectapp/Person.html",{"Person":Person.objects.get(pk=Person_id)}) but then when checking Per.name it returns the old name. I want to ask how to change an attribute's value of django model after object creation -
DateTimeField object has no attribute strftime
My main code is this: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) publishdate = created_on.strftime('%Y/%m') class Meta: ordering = ['-created_on'] def __str__(self): return self.title When I run this code, I get: 'DateTimeField' object has no attribute 'strftime' referring to publishdate strftime works with datetime.datetime, and DateTimeField converts to datetime.datetime, so what am I doing wrong? I've tried to convert to datetime.datetime to no avail -
Django Microsoft Authentication
I'm trying to include in my Django website the possibility to sign in using a Microsoft login. I have set up a new App registration and included the below as redirect urls. I then followed this set of instruction in my Django site: https://django-microsoft-auth.readthedocs.io/en/latest/usage.html However when trying to access the admin module and click Microsoft, I'm getting this error. django version: 3.0.4 python version: 3.8.5 -
Django: image tag expected an Image object, got <ImageFieldFile: profile_pics/file_x.jpg>
I'm rendering the photo of a user in a Django/Wagtail template. I've rendered other images in other Wagtail pages, all of them uploaded through the Wagtail Admin page. However, this time I need to render on a Wagtail Page model from a Profile that asks for a photo when user signs up. in the HTML I'm using: {% image page.user.profile.photo fill-150x150 as post_img %} <a href="{{ post.url }}"> <img src="{{ post_img.url }}" class="mr-3" alt="{{ post_img.alt }}"> </a> But getting this error: If I delete that part, the template render ok, of course without the photo. Wagtail model: class PastorPage(Page): template = 'ministros/pastor_page.html' user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=False, null=False, related_name="+", on_delete=models.SET(get_sentinel_user), ) content = StreamField( [ ("title_and_text", blocks.TitleAndTextBlock(classname='text_and_title')), ("full_richtext", blocks.RichtextBlock()), ("simple_richtext", blocks.SimpleRichtextBlock()), ("cards", blocks.CardBlock()), ("cta", blocks.CTABlock()), ], null=True, blank=True, ) content_panels = Page.content_panels + [ StreamFieldPanel('content'), FieldPanel('user'), ] class Meta: verbose_name = 'Pastor' verbose_name_plural = 'Pastores' -
Django User Login Issue
I am back again with a Django Question. I am having issues with getting my login screen to work. I feel like maybe this is a simple issue that I am just not seeing. I am using the current versions of Python and Django. I am getting a NoReverseMatch error when trying to access my login page. Here is the code, along with some screen shots: base.html: <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 }}. {% else %} <a href="{% url 'users:login' %}">log in</a> {% endif %} </p> {% block content %}{% endblock content %} login.html: {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="submit">log in</button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/> </form> {% endblock content %} users/urls.py: from django.urls import path from django.conf.urls import url from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ # Login page #path('login/', LoginView, {'template_name': 'users/login.html'}, name='login'), path('login/', LoginView.as_view(template_name='users/login.html')), ] Code location Error message