Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: NoneType object is not callable on GeoDjango
Although I have read many similar articles about PointField and 'NoneType' object error, I can't figure out how this field should be automatically save according to the latitude and longitude variables I received from the user. Here is my model: from django.db import models from django.contrib.gis.db import models from django.contrib.gis.geos import Point class Firm(models.Model): FirmName = models.CharField(max_length=50) address = models.CharField(max_length=1000, null=True, blank=True) FirmAddress = models.PointField(null=True, blank = True, geography=True, default=Point(0.0, 0.0)) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) Logo = models.ImageField(null=True, blank=True) @property def save(self, *args, **kwargs): self.FirmAddress = Point(self.lng, self.lat) super(Firm, self).save(*args, **kwargs) On the Django shell, I type from firm.models import Firm command first and then Firm.objects.create(FirmName="QWERTY", address="temp", lat=24, lng=54, Logo='logo.jpg') command. Here is the error I got at the end: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Deniz\Desktop\PROJECT\fenv\lib\site-packages\django\db\models\query.py", line 453, in create obj.save(force_insert=True, using=self.db) TypeError: 'NoneType' object is not callable But when I look at my database, I see that a value of type geography-point has been added to the FirmAddress column. When I remove the FirmAddress feature and update the model, I don't get any errors and everything works fine. … -
Check if a user is in a group to post something Django
I'm trying to verify if a user is in a group and only if he is in that group he can post something in it, otherwise he will be redirected. I am pretty new to Django, I'm trying to add some more lines and ideas in order to further develop a site on my own. This is my code: models.py from django.db import models from django.urls import reverse from django.conf import settings from groups.models import Group from misaka import html from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group,related_name='posts',null=True,blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username, 'pk':self.pk}) class Meta(): ordering = ['-created_at'] unique_together = ['user','message'] views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy from django.views import generic from django.http import Http404 from django.contrib import messages from groups.models import Group,GroupMember from braces.views import SelectRelatedMixin from django.http import HttpResponseRedirect from django.urls import reverse from posts.models import Post from . import models from . import forms from django.contrib.auth import get_user_model User = get_user_model() from django import template register = template.Library() @register.filter def has_group(user, group): return user.groups.filter(name=group).exists() … -
[Microsoft][ODBC Driver 17 for SQL Server]SSPI Provider: No Kerberos credentials available
I have developed Django app and connecting remote sql server from Django app. If I run it in anaconda environment its running fine, but if I build docker container it gives me error sqlalchemy.exc.DBAPIError: (pyodbc.Error) ('HY000', '[HY000] [Microsoft][ODBC Driver 17 for SQL Server]SSPI Provider: No Kerberos credentials available (default cache: FILE:/tmp/krb5cc_0) (851968) (SQLDriverConnect)') (Background on this error at: http://sqlalche.me/e/dbapi) Here is Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN apt-get update \ && apt-get -y install gcc gnupg2 \ && curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN apt-get update \ && ACCEPT_EULA=Y apt-get -y install msodbcsql17 \ && ACCEPT_EULA=Y apt-get -y install mssql-tools RUN apt-get -y install unixodbc-dev \ && apt-get -y install python-pip \ && pip install pyodbc RUN pip install --upgrade pip RUN pip install Django RUN pip install python-dotenv RUN pip install --user django-crispy-forms RUN pip install pandas RUN pip install SQLAlchemy RUN pip install django-pyodbc-azure-2019 COPY . /app Here is the connection engine = create_engine('mssql+pyodbc://' + 'SQLserver' + '/' + 'database' + "?" + 'driver=ODBC Driver 17 for SQL Server') -
Incorporating Python and Django On GoDaddy
I've developed a small network of web pages with Python and Django. I can see them on my computer. But when I try to upload them to GoDaddy, I discover that their file structuring is way different to that of Django. For example, GoDaddy is expecting an index.html or a home.html in their root folder, but in Django, such a page is several subfolders deep, underneath your project folder and then your app folder, and then the templates folder, and finally the name of your app underneath the templates folder. So is Django incompatible with GoDaddy? If not, how do incorporate this file format into GoDaddy, so ultimately, I can see my web pages there? Anyone who has successfully incorporated a Django website on GoDaddy, I'd love to hear from you. Thanks. -
How to send a push notification to specific user in Django?
I’m using django as my backend and I want to use firestore for webRTC audio call. So that I need to send a notification to the user to answer the call. How can send the notification to the specific user using Django and I also haven’t made any authentication with firebase then how can I send a FCM to a specific user? -
please am new in django, what can i do to avoid repetition of the same query in different templates
1.This is my Home list view def get_context_data(self,*args,**kwargs): categories = Post.objects.values('category').annotate( posts_count = Count('category')) likes = Post.objects.values('likes').annotate(count_like=Count('likes')) display_menu = Category.objects.all() context = super( HomeListView , self).get_context_data(**kwargs) context ['categories'] = categories context ['display_menu'] = display_menu context ['likes'] = likes return context -
How to use self-signed and LetsEncrypt Certbot SSL certificates together in nginx?
I am hosting a django website on digital ocean. I have wish to access my website's IP using https with self-signed cert as Let's Encrypt does not provide certificates for public IP addresses. I followed this guide and wrote an nginx server block. I can access https://example-ip-address with: server { listen 443 ssl; listen [::]:443 ssl; include /etc/nginx/snippets/self-signed.conf; include /etc/nginx/snippets/ssl-params.conf; server_name 123.123.12.123; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/djangotemplates; } location / { include /etc/nginx/proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } server { listen 80; listen [::]:80; server_name 123.123.12.123; return 301 https://$server_name$request_uri; } And, I can access https://example.com and https://www.example.com with let's encrypt SSL cert by following this and this is the server block I wrote: server { server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/djangotemplates; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) … -
Django Foreign Key limit_choice_to with model object filter
I'm trying to limit the choices for a foreign key in my django admin tool. I stumbled across the limit_choices_to option for the ForeignKey model: https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to In my models, I have a Question_logic that has an attribute ifLogic which is a foreign key of the model Options (which represent the possible answers of options of a question). # Models.py class Options(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) option = models.CharField(max_length=200) class Question_logic(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) # error here: ifLogic = models.ForeignKey(Options, on_delete=models.CASCADE, limit_choices_to=Options.objects.filter(question=question)) thenLogic = models.CharField(max_length=200) However this approach does not work because apparently you can't reference an object in the model definition itself and I'm getting this error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. My logic is quite straightforward: I want the admin to chose only between the options that are relevant for the specific question. How do I implement this correctly? Thanks. -
500 Internal Server Error for some but not others
My site, https://hendrixia.com, gives an 500 Internal Server error for some users but not others. I have someone helping me debug, but without fruition. He is getting 500 internal server errors on his personal computer and at one of his webservers. I am able to load the site fine. We have no clue what is wrong. Obviously I'm not going to turn debugging on on a live site. But we are running out of options. Can anyone help? Site is built with python/django. postgresql db. hosted at heroku -
Other computers under same network cant access my django development server?
Steps taken: added in allowed_hosts ALLOWED_HOSTS = ["192.168.0.149"] cmd : python3 manage.py runserver 192.168.0.149:8000 Firewall not enabled in my mac I am getting ERR_CONECTION_TIMED_OUT This site cant be reached. both the computers are under same network. -
How do I make the Django form's choices elements dynamic?
I need to make a Django form containing two fields: region and city. Both fields contain options from the drop-down list. The city field should only be available after selecting region, and the options for the city field should depend on the previously selected region. Can this be done without resorting to js? -
How Can I store reviews from google to my database automatically in predefined timeframe?
I am pretty new to programming and I am thinking of how can I fetch the data from the google review API automatically in predefined time (twice daily) and store it in the django backend database ? I know I can fetch data using request package but everytime I fetch data it gives me all the data even that which was stored in the database in the earlier fetch. -
How to open multiple browser in one view using WordPress or Django?
I want to open multiple browser in one-page view. Please see the picture for better understanding my question. My willing page view -
Optimising DRF Serialization
I am facing a problem where I have to optimise the serialization of the ORM object. I have an object say Foo for which I have a huge serializer. I have mentioned a lot of fields, like class FooSerializer(ModelSerializer): bar = serializers.StringRelatedField(source="bar") apple = serializers.StringRelatedField(source="bar.food") cat = serializers.StringRelatedField(source="bar.animals.pet") ball = serializers.StringRelatedField(source="bar.toy") # a lot of other complex fields related with Foo # direct-indirect, 1-1 or 1-M relations class Meta: model = Foo fields = ['bar', 'apple', 'cat', 'ball', ....] Now, this is causing the serialisation to take a lot of time. I added logging and saw many SQL queries getting executed. A lot these queries are repeated. As per my understanding from documentations, even though Django QuerySet is lazily executed, the serialization in DRF is querying for each field to get populated. Please elaborate on how serialization fields are populated on lower level as well as it will help me more. What I want to achieve here is do minimal possible queries. In the example above, To get bar.food and bar.toy I want to do only one single query which will fetch bar object and I can access food and toy object. One possible solution I can think of is … -
Countdown in Django Html Template
I am trying to implement a countdown, that will give me the number of days and hours until the deadline. I have tried two different methods using the html filter but nothing is displayed. Is the filter not already part of Django? models.py class Quote(models.Model): deadline = models.DateTimeField(auto_now=False, blank=True, null=True) html filter Method 1: {{ quote.deadline|timeuntil:today }} Method 2: {{ quote.deadline|timesince:comment_date }} -
Can't redirect using urls patterns
When i try go to http://127.0.0.1:8000/1395ec37e4/ i get error: Page not found at ... I don't know why, twice, when i had changed variable getted_short_url to short_urlin urls.py and views.py(redirect_view) it could redirect me. I am confused... Log from page: Using the URLconf defined in cut_and_go.urls, Django tried these URL patterns, in this order: <str:getted_short_url> admin/ The current path, 1395ec37e4/, didn't match any of these. views.py: from hashlib import sha256 from .models import URL from .forms import URLInput from django.shortcuts import render, redirect def input_form(request): if request.method == 'POST': form = URLInput(request.POST) if form.is_valid(): getted_url = form.cleaned_data["full_url"] transformed_url = 'https://' + getted_url try: URL.objects.get(full_url=transformed_url) except URL.DoesNotExist: maked_url = sha256(transformed_url.encode()).hexdigest()[:10] URL(full_url=transformed_url, short_url=maked_url).save() else: form = URLInput() return render(request, 'shortener/input_form.html', {'form': form}) def redirect_view(request, getted_short_url): return redirect(URL.get_full_url(getted_short_url)) urls.py: from . import views from django.urls import path urlpatterns = [ path('', views.input_form), path('<str:getted_short_url>', views.redirect_view) ] -
How to loop [('A', 1),('B', 2),('C', 4)] this type of data in graph ( django python)?
i want the result as below this code, here (A,1) A is the label and 1 is the data, so that I can present it in my graph, if you have any other solution to present this data [('A', 1),('B', 2),('C', 4)] then please let me know, var myChart = new Chart(ctx, { type: 'bar', data: { labels: ["A","B","C"], datasets: [{ label: '# of Votes', data: [1,2,4], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 2 }] }, options: { scales: { y: { beginAtZero: true } } } }); -
Django filterset and Mutiple values
This is the first time I have used the Django filterset. When a filter field uses multiple inputs for a given purpose, it only gives one output, but can actually be two or more. Here is the code: class CourseFilterSet(django_filters.FilterSet): beneficiary = django_filters.CharFilter(method='get_beneficiary', field_name='beneficiary') type = django_filters.CharFilter(method='get_type', field_name='type') def get_beneficiary(self, queryset, field_name, value, ): if value: return queryset.filter(beneficiary=value) return queryset def get_type(self, queryset, field_name, value, ): print(value) resp = [] if value: data = CourseSubscription.objects.filter(subscription_type=value).values('course') l = len(data) print(data) for i in range(l): print(data[i]['course']) d = data[i]['course'] queryset = Course.objects.filter(id=d) return queryset return queryset class CourseFilterView(viewsets.GenericViewSet): serializer_class = CourseFilterSerializer queryset = Course.objects.all() filterset_class = CourseFilterSet Use two values in the beneficiary field, which give only the first or last output, not the correct output. Give me the right way to overcome this problem..! -
Django: How to stop giving new user Staff status and Superuser status status in default
When I register a new user, I had an login error in admin page. The error is that "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive". I found out that the new user has Staff status and Superuser status in default. And I can log in admin page in the new user account. So, I found out the login error happens because of giving the new user has Staff status and Superuser status in default. I thought these codes password1 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(max_length=30, required=False, help_text='Optional', widget=forms.TextInput(attrs={'placeholder': 'Repeat your password'})) in forms.py are the reason. So I tried register both with them and not with them. But, the result was same. How to make the new user has only active status, not Staff and Superuser status in default? Is the reason for the admin login error right? 2-1) If not, how to solve this? This is views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.views.generic import TemplateView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin from .forms import SignUpForm, ProfileForm from django.urls import reverse_lazy from .models import * from django.contrib import messages from django.contrib.auth import … -
how to display form submit value without storing in db django
I am trying to make a Sign-up page in django for a brand. I want the user register his/her brand on my web app but it will not store the information in db until the admin not accept it, but i don't know how can i do this Model.py class BrandRegister(models.Model): brand_name = models.CharField(max_length=50) owner_name = models.CharField(max_length=30) address = models.CharField(max_length=30) contact_no = models.BigIntegerField() -
NameError Occured when I add element into database
I am getting this error again and again and I don't know why I tried everything but does not seem work, I am trying to add element into mine home page! from django.db import models class ToDo(models.Model): name = models.CharField(max_length = 200, unique = False) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDo, on_delete = models.CASCADE) text = models.CharField(max_length = 300) complete = models.NullBooleanField() def __str__(self): return self.text my text is defined in that code but I don't understand why I am getting this error and I tried everything In [35]: lt.item_set.create(text = "moon", complete = False) Out[35]: --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\anaconda3\lib\site-packages\IPython\core\formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() ~\anaconda3\lib\site-packages\IPython\lib\pretty.py in pretty(self, obj) 392 if cls is not object \ 393 and callable(cls.__dict__.get('__repr__')): --> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) ~\anaconda3\lib\site-packages\IPython\lib\pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() --> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): ~\anaconda3\lib\site-packages\django\db\models\base.py in __repr__(self) 519 520 def __repr__(self): --> 521 return '<%s: %s>' % (self.__class__.__name__, self) … -
check if many to many field exists for using a post save method
I have a post save function as shown below def blog_notify_receiver(sender, instance, created, *args, **kwargs): if created: print(sender) print(instance) exists = instance.pricing_tier.all() print(exists) try: BlogNotification.objects.create() except: pass post_save.connect(blog_notify_receiver, sender=Blog) my blog model is as follows class Blog(models.Model): title = models.CharField(max_length=80, blank=True, null=True) pricing_tier = models.ManyToManyField(Pricing, related_name='paid_blogs', verbose_name='Visibility', blank=True) here I am getting exists as an empty queryset, how I can check it properly? if a particular plan exists I can create a notification for that plan group as follows if created and instance.pricing_tier.filter(slug='free-trial').exists(): but it doesn't work now as its output is None. Any help is much appreciated. -
Setting the max length of a string in a list - Django
I am creating a registration page for my website. I am following this tutorial. I have a bootstrap/html template with a form (Down Bellow), and I want to replace the html form with a UserCreationForm that I have already made in my forms.py file. The tutorial says to replace the html input fields with my user creation fields, but then bootstrap cannot style them. Can someone please help me so the default form fields have my python usercreationform? My code is down bellow. Register.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:400,700"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="{% static "registerstyles.css" %}"> <title>GoodDeed - Register</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="signup-form"> <form action="" method="post"> {% csrf_token %} <h2>Sign Up</h2> <p>Please fill in this form to create an account!</p> <hr> <div class="form-group"> <div class="row"> <div class="col"> <input type="text" class="form-control" name="first_name" placeholder="First Name" required="required" ></div> <div class="col"><input type="text" class="form-control" name="last_name" placeholder="Last Name" required="required"></div> </div> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="Email" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="Password" required="required"> </div> <div class="form-group"> <input type="password" class="form-control" name="confirm_password" placeholder="Confirm Password" required="required"> </div> <div class="form-group"> … -
How to get updating values from python to template without refresh? Django
I have a real time database(google firebase), and its data is constantly changing, I want to display this data on my template without reloading the template itself. I couldn't find any related information, also I am sort of a beginner especially to AJAX so if you can provide an example or a documentation that would be really helpful. Any help is appreciated -
Delete answer deleting everything instead of following filter
const DeleteAnswer = () => { let input = formInput.getFieldsValue() dispatch(deleteGuidedAnswer(input)) hideModal() formInput.resetFields() } <MinusCircleOutlined className='dynamic-delete-button' style={{ paddingLeft: '10px', position: 'absolute', top: '0%', right: '-5%', }} onClick={() => DeleteQuestion()} /> @require_http_methods(["POST"]) @login_required def delete_guided_answer(request): req = json.loads(request.body) guided_answers= req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(answer_id=guided_answer["answer_id"]).delete() return success({"res": True}) What my code does above is delete the answer based off answer id, however whenever i try to delete a certain item everything gets deleted instead, why is it that delete is not being filtered