Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I would like to integrate google maps to my E-commerce website that is built on django framework
I have built my E-commerce website on django framework and i would like to integrate google maps to it. A buyer within my site should be able to specify the distance radius of the seller from whom they are comfortable to purchase from. So for example, a buyer can go to my site and from their location they can specify that whatever they are looking for should be from a seller who is within their specified geographical radius. So for example if they specify a 10Km radius, they should not see products from sellers who are 15Km away. A good example of what i am talking about is the Tinder app, where you can specify in the settings that you only want to see profiles within a specific geographical radius from your current location. I have never dealt with google maps that is why i have sought to get directions before i begin so that i do not post a code that cannot be understood here. Someone please point me in the right direction of how such a functionality can be integrated in django. Thank you. -
What exactly does the update() method here given that the if loop is giving an empty dictionary?
I don't understand what the dict_dictionary does to the email_ctx dictionary here, does it stay empty of is it overriding some data here? class EmailTemplateContext(Context): @staticmethod def make_link(path): return settings.MAILING_LIST_LINK_DOMAIN + path def __init__(self, subscriber, dict_=None, **kwargs): if dict_ is None: dict_ = {} email_ctx = self.common_context(subscriber) email_ctx.update(dict_) super().__init__(email_ctx, **kwargs) def common_context(self, subscriber): subscriber_pk_kwargs = {'pk': subscriber.id} unsubscribe_path = reverse('mailing_list:unsubscribe', kwargs=subscriber_pk_kwargs) return { 'subscriber':subscriber, 'mailing_list': subscriber.mailing_list, 'unsubscribe_link': self.make_link(unsubscribe_path), } -
i was unable to find the error in path i mentioned in django
i wanted to add two numbers .so i used request.get to get two values and then my code has to add the numbers and print the result on the server.but my terminal shows- Not Found: / [09/Oct/2019 18:07:30] "GET / HTTP/1.1" 404 2082 Not Found: /favicon.ico [09/Oct/2019 18:07:33] "GET /favicon.ico HTTP/1.1" 404 2133 i tried adding my appname in the INSTALLED_APP section too. urls.py from django.urls import path from . import views urlpatterns = [ path('add',views.add,name='add'), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'calc', ] ROOT_URLCONF = 'new12.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py from django.shortcuts import render from django.http import HttpResponse def add(request): val1=request.GET['num1'] val2=request.GET['num2'] res=val1+val2 return render(request,"result.html",{'result':res}) index.html {% extends 'base.html' %} {% block content %} <form action="add"> enter ist num: <input type="text" name="num1"><br> enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} printing the result on server result.html {% extends 'base.html' %} {% block content %} {{result}} {% endblock %} base.html <html> <body bgcolor="red"> {% block content %} {% endblock %} </body> </html> -
use values in the queryset of modelmultiplechoicefield
i have a ModelForm like this: class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_allowed_user_name class AddUserToPrivateCourseForm(forms.ModelForm): users = CustomModelMultipleChoiceField(queryset=None) class Meta: model = Course fields = [ 'users', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['users'].queryset=User.objects.all() and the method get_allowed_user_name in model is def get_allowed_user_name(self): return "{} {} - {}".format(self.firstname, self.lastname, self.mobile) the database has around 60k users and loading this page is very long and takes about half a minute so i wanted to instead of capturing everything from db just use .values() and take just what is needed for form so if i use User.objects.values_list('firstname', 'lastname', 'mobile', 'id') it works ok and captures and generate what i need but the problem is it is unable to show already selected users and just shows a list of all users what should be done to generate options correctly? -
How can I store mathematical formulas with django
I'm working on a calculator that uses some mathematical formulas produced with multi linear regression. The problem here is this formulas should be constructed in dynamic way. With the admin interface the user can update and create formulas. The issue is how to model f= a0 +a1x + a2x^2.... and save all the data on the database(coefficients). And in the future we will have complex formulas. Is there like a library or better way to model the application to support these features. -
Axios put request not working properly with Django Rest Framework
From axios I have to make a put request to the DRF. In DRF I'm using APIView class-based view. Before I was getting 403 forbidden error when I was making put request. Because it was not sending csrftoken in the request. I googled it and went through the CSRF with Django, React+Redux using Axios stack overflow question and somehow I was able to fix 403 forbidden issue. Going through the above StackOverflow question I changed a few lines of codes and they are. In my axios file axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; In my project's settings. py file ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But the wiered part is here when I pass any data to thorough put request from axios, it actually passing the flow to the APIView class (It's my assumption) from there I get a wired response. I could see that it sends the react's index.html as the data in the response. My views.py code class TestView(APIView): def put(self, request): print('inside put method') print(request.data) return Response('Test data passing in return') My Axios code import axios from "axios"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; return axios({ method: "put", … -
How do I correctly stack 2 slug models in the urls?
I have slugs set for my products and my categories, and when I click a product from my categories, my link goes from /shop/badges/ to shop/lakers, instead of shop/badges/lakers. Django spits out an attribute error. Generic detail view ProductDetailView must be called with either an object pk or a slug in the URLconf. My urls: urlpatterns = [ path('', CategoryView.as_view(), name='shop'), path('<slug:product_category>/', ProductListView.as_view(), name='products'), path('<slug:product_category>/<slug:product>/', ProductDetailView.as_view(), name='detail'), ] My get_absolute_url: def get_absolute_url(self): return reverse("products", kwargs={"product_category":self.slug}) return reverse("detail", kwargs={"product":self.slug}) I would like to have my urls implement each slug for category and badges stacked on top of each other, instead of just one when I click a product link. -
Django Middleware to Extend self.request for a social media apps
We know in Django, we can access to too many instances in self.request like self.request.user, self.request.data, self.request.authenticator etc I am trying to get self.request.mygroup writing custom middleware this is my models from django.contrib.auth.models import User from django.db import models class Person(models.Model): id = models.UUIDField( primary_key=True, default=uuid4, editable=False ) auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) class Group(models.Model): members = models.ManyToManyField( Person, related_name='group_members' ) I wrote this middleware and it is working fine: class GroupMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): person = Person.objects.filter( auth_user__id=request.user.id ).first() mygroup = Group.objects.filter( members__alias__in=[person.alias] ) request.mygroup = mygroup.first() response = self.get_response(request) return response Above middleware working fine but the problem is when I visit from incognito mode, I mean when I am not logged in, it throws me an error like AnonymouseUser doesn't have attribute self.request.user to handle this, I tried writing condition like if self.request.user.is_authenticated: but it occurs another error as same. I guess I crafted the middleware wrongly, Can anyone help me to extend self.request to get my own instance like self.request.mygroup? I am not getting what is the right way to write a middleware, i am very new in middleware I want self.request.mygroup should retun only authinticated user's group -
Django attribute module OS
I'm trying to intall Vataxia social network platform on my local windows machine, but I'm receiving message like. ERROR: Command errored out with exit status 1: command: 'c:\users\rade\desktop\vataxia\back\env\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-mb9x0ep8\\uWSGI\\setup.py'"'"'; __file__='"'"'C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-mb9x0ep8\\uWSGI\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Anyone know how to fix it? -
Adding an autoincrementing model to django 1.11 with UUID as primary key
I have a legacy Django Application (1.11) which uses UUID as primary key, hence doesn't have an ID field. My DB is postgres class model_name(models.Model): .... #model data ... companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... # Other model data I now need to add a human readable auto-incrementing identifier which will be used by users to refer to the records outside the system. The challenges are as follows: The system can have multiple entries being added simultaneously, so it needs to manage that without collisions ideally would need to add this to the save() method because new I have around 20000 records already in the database for this model. So whatever method I use, I will need to be able to add values for all previous records. I need to start numbering at 100,000 Is there a way to do this (Autofield may not work because its not going to be primary key and i already have n records in the system.) so it will remain consistent? -
How can i serialize that dictionary in Django?
{'test': , 'answers': , , , ]>, 'test_question': , 'test_button_list': [[{'number': 1, 'answered': False, 'correct': False}, {'number': 2, 'answered': False, 'correct': False}, {'number': 3, 'answered': False, 'correct': False}, {'number': 4, 'answered': False, 'correct': False}, {'number': 5, 'answered': False, 'correct': False}]], 'view': , 'form': } in my view: context = self.get_context_data() print(self.get_context_data()) html = render_to_string('difficult_test.html', context) if self.request.is_ajax(): return http.JsonResponse({"html":html, "context":context}) return response If i try to serialize i get this response: TypeError: is not JSON serializable -
Adding Bootstrap Modal (Dialogue window) to Django navbar
I want to add Bootstrap Modal to Navbar on Django. It works on documentaion page of official Bootstrap, but not in my Django project. Is that possible? <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> -
Is it possible to refer to acknowledged tasks after calling app.autodiscover_tasks() in django-celery?
In Django-Celery, is it possible to refer to a particular task after it gets discoverred with app.autodiscover_tasks() without explicitly reimporting it from a module? Something like app.discoverred_tasks.django_app1.task1? Are there any benefits of autodiscoverring other than printing a list of available tasks upon starting a celery worker? -
Decorator pattern to implement filtering and pagination in django api rest
I am trying to implement filtering and pagination in an rest api developed with Django and python. I need to choose when to use filtering, pagination, both or none of them in my endpoints. To do this, I have thought of combining a template pattern with a decorator pattern. This is my designed solution, when ModelViewSet is an abstract class provided by Django Rest Framework, DummyViewSet is my endpoint, and FilteringViewSetDecorator and PaginationViewSetDecorator are my decorators. This is my source code: class CustomView(viewsets.ModelViewSet): __metaclass__ = ABCMeta @abstractmethod def get_queryset(self, request, **kwargs): pass def serialize_queryset(self, queryset): print("CustomView: _serialize_queryset") serializer = self.get_serializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) def list(self, request, **kwargs): print("CustomView: list") queryset = self.get_queryset(request, **kwargs) return self.serialize_queryset(queryset) class ViewSetDecorator(CustomView): __metaclass__ = ABCMeta def __init__(self, viewset): print("ViewSetDecorator: __init__") self._viewset = viewset def get_queryset(self, request, **kwargs): print("ViewSetDecorator: _get_queryset") return self._viewset.get_queryset(request, **kwargs) class FilteringViewSet(ViewSetDecorator): @staticmethod def __build_filters(params): filters = [] for key, value in params.items(): if key != 'limit' and key != 'offset' and value is not None and value != '': query_filter = {key: value} filters.append(query_filter) return filters def get_queryset(self, request, **kwargs): print("FilteringViewSet: _get_queryset") queryset = super(FilteringViewSet, self).get_queryset(request, **kwargs) filters = self.__build_filters(request.GET) for query_filter in filters: queryset = queryset.filter(**query_filter) return queryset class PaginationViewSet(ViewSetDecorator): … -
How can I set header in swagger_auto_schema?
I have a next code. How can I add header: {'Authorization': 'JWT Token'} In settings: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' } }, 'USE_SESSION_AUTH': False } -
Django Mezzanine fabric deployment, settings error - SECRET_KEY setting must not be empty
So I have my project on my Ubuntu14 droplet on digitalocean, but whenever I try to testrun the server through the virtualenv, I get this error: ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Somehow, it has not registered the SECRET_KEY from the local_settings file. I deployed using Git, since I am running on Win7. Is there some step I missed to transfer the settings? Been running both "fab all" and the individual "fab install/secure/deploy" settings. Browsing the FTP shows that all files are on the server. -
Accessing django site in subfolder of multisite nginx server (default homepage works, not admin)
I'm trying to create a django site on my nginx server. I already have other site in other sub-folders. I use gunicorn service to redirect from nginx to django. I'm able to access the default django welcome page (https://example.com/django/) but I can't go to the admin page of my django site (if I enter https://example.com/django/admin, it redirect me to https://example.com/admin/login/?next=/admin/ and I get a nginx 404). I'm only starting webdev so I might be wrong, but is seems the error is in my nginx config. Here is my nginx configuration file: server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; } server { server_name example.com www.example.com; # listen 80; # SSL configuration listen 443 ssl default_server; listen [::]:443 ssl default_server; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # drop SSLv3 (POODLE vulnerability) ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_dhparam /etc/ssl/certs/dhparam.pem; root /var/www/example.com; index index.php index.html; location / { try_files $uri $uri/ $uri.html $uri.php$is_args$query_string; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ { include snippets/fastcgi-php.conf; # With php-fpm (or other unix sockets): fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; # With php-cgi (or other tcp sockets): #fastcgi_pass 127.0.0.1:9000; } location /biketrack { try_files $uri $uri/ =404; auth_basic "Restricted Content"; … -
How to create new field in output by annotate() with default value?
In SQL it would be SELECT *, 0 as new_field FROM table; I thought in django it would be like Article.objects.annotate(new_field=0), but it doesn't work: TypeError: QuerySet.annotate() received non-expression(s): 0. Is there the way to do it? -
How to use Google APIs to reduce in memory usage and to use Advance Google features?
A) I want to build a system that would allow users to POST videos to their youtube channel after they are logged in with the google account to my website. The video will be published on the website. B) After that, I also need that the users could comment on the videos that showed on my website, and on youtube. C) After that, I need that the user's profile pictures will be uploaded to their own Google Drive. Tasks: Upload Videos to the website with Youtube (Youtube Video API). Comment on videos on the website (Youtube Comments API). Upload profile picture to Google Drive (Google Drive API). I don't know where to start, and how to do that any user "Hosts" itself, for example, he can add videos, comments, and host his profile picture. Using Django with Python3 -
How to solve the problem of Dual behavior of django CustomUser in migration?
I have a data migration as below in which I want to use create_user method of CustomUser, get an instance of the created user, and use this instance to create instance of Partner model. It is worth mentioning that I have a Partner model that has a one-to-one relationship with CustomUser. I have two options: # Option One: def populate_database_create_partner(apps, schema_editor): Partner = apps.get_model('partners', 'Partner') CustomUser.objects.create_user( id=33, email='test_email@email.com', password='password', first_name='test_first_name', last_name="test_last_name", is_partner=True, ) u = CustomUser.objects.get(id=33) partner = Partner.objects.create(user=u, ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(populate_database_create_partner), ] In option one, I see this error: ValueError: Cannot assign "<CustomUser: test_email@email.com>": "Partner.user" must be a "CustomUser" instance. I then test this: # Option Two: def populate_database_create_partner(apps, schema_editor): Partner = apps.get_model('partners', 'Partner') CustomUser = apps.get_model('accounts', 'CustomUser') CustomUser.objects.create_user( id=33, email='test_email@email.com', password='password', first_name='test_first_name', last_name="test_last_name", is_partner=True, ) u = CustomUser.objects.get(id=33) partner = Partner.objects.create(user=u, ) class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_populate_database_createsuperuser'), ] operations = [ migrations.RunPython(populate_database_create_partner), ] I the see this error: CustomUser.objects.create_user( AttributeError: 'Manager' object has no attribute 'create_user' The create_user method does not work. If I do not use the create_user method and simply use CustomUser.objects.create(...), I will not be able to set password in here. -
django database config file for "OPTIONS" can only reads a .cnf format
If this is a good template for the DATABASES dictionary in django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' 'OPTIONS': { 'ssl': {'ca': '<PATH TO CA CERT>', 'cert': '<PATH TO CLIENT CERT>', 'key': '<PATH TO CLIENT KEY>' } } } } I want to read the OPTIONS key from file like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '<DATABASE NAME>', 'USER': '<USER NAME>', 'PASSWORD': '<PASSWORD>', 'HOST': '<HOST>', 'PORT': '3306' 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, "db_config.json"), }, } } however, this is giving me an error. The file is not being found. I noticed that all the examples from Django only use a .cnf file. and the cnf file really does work. However, I have a nested dict inside the .json file which I cannot seem to convert to .cnf (or INI) since these config files do not support nested parameters. How can I solve this? -
How can I pass empty request_body_schema to swagger_auto_schema in Django Rest Framework?
class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer @swagger_auto_schema(??? responses={200: "Redirect to Sign In page", 401: "Unauthorized Error"}) @action(detail=False, methods=['post']) def logout(self, request): I need to in request_body_scheme will a empty data, but I get UserSerializer structure. How to fix it? -
Django Allauth Ignoring Adapter
Allauth signin keep showing despite adding adapter. Following allauth documentation on Overriding the allauth signin, i created an adapter.py in my app (accounts) with: from allauth.account.adapter import DefaultAccountAdapter class NoNewUsersAccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): return False I equally added to my settings file: ACCOUNT_ADAPTER = 'accounts.adapter.NoNewUsersAccountAdapter' -
How to download files from user_directory_path in django
I am trying to download files that were uploaded to my django media directory. I am able to upload the files successfully, but I don't know the best method of downloading back these files. I have seen different examples online but I don't fully understand them. Here are my codes models.py: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) certification = models.FileField(upload_to=user_directory_path, blank=True) urls.py urlpatterns = [ ......... path('profile/', user_views.profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) file.html: <a href="{{ user.profile.certification.url }}">Download Certification</a> I get this error: ValueError The 'certification' attribute has no file associated with it. Do I create a view in my views.py and a url in my urls.py to handle the download? If so How do I go about it. -
Django Middleware extend self.request error when not logged in
We know in self.reqeust, there are too many instances like self.request.user, self.request.data self.request.authenticator I am trying to make self.request.person with this, instance, i should get my Person Model instance this is my model from django.contrib.auth.models import User class Person(models.Model): auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) name = models.CharField(max_length=50) this is my middleware.py file from account.models import Person class PersonMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): person = Person.objects.filter(auth_user=request.user.id).first() request.person = person response = self.get_response(request) return response Currently is working fine for logged-in user but the problem, when I go to incognito mode and visit the admin page, it through me an error that anonymous user doesn't have attribute request.user.id to solve this, I write a condition like this if request.user.is_authenticated: but it wasn't solved the issue, I guess, I wrote my middleware wrongly, can anyone help me to achieve this? What is the right way to write middleware to extend self.request to self.request.person?