Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to install Channels
I created a virtual environment using "pipenv shell". Then after installing Django using "pipenv install django==2.2", I used the commands "pipenv install channels" and "python -m pip install -U channels" to install Channels but am unable to do so. The error was: error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ BTW, I am using Microsoft Visual Studio Code latest version. Thanks in advance! -
Choice field with search based on django model
I have a model, which contains two fields: city and post office address. I want to make a form with two of these fields. Field with the city needs to be choice field and information must be taken from that model, but the main problem with post office number field. In this model, I have about 7k post office addresses and I need to have choice field united with search field and the post office addresses would be shown based on city field choice. Code of the model with information: class Warehouse(models.Model): title = models.CharField(_('Title'), max_length=255, db_index=True) address = models.CharField(_('Address'), max_length=255, db_index=True) @property def full_name(self): return '{}, {}'.format(self.title, self.address) def __str__(self): return self.full_name class Meta: verbose_name = _('Warehouse') verbose_name_plural = _('Warehouses') Code of the form: from django import forms from .models import Order class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ( 'first_name', 'last_name', 'patronymic', 'email', 'phone_number', 'region', 'city', 'address', 'post_office_address') Order model: class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) patronymic = models.CharField(max_length=50) email = models.EmailField() phone_number = models.CharField(max_length=13) region = models.CharField(max_length=30) city = models.CharField(max_length=30) post_office_address = models.CharField(max_length=100, null=True) address = models.CharField(max_length=50, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) … -
How to reverse 'url' of included urls in django
Suppose my projects urls.py looks something like this: urlpatterns = [ path("admin/", admin.site.urls), path("foo/", include("foo.urls"), name="foo"), ] Then I have a file foo/urls.py, that has some further urls: urlpatterns = [ path("bar/", views.bar, name="bar"), path("baz/", views.baz, name="baz"), ] What I would like to do Get the 'partial' url that takes you so far as the included 'urls'. For example, I could do reverse("bar") to get foo/bar. But I can't seem to do reverse('foo') to get just foo`. Is there a way of doing this. One (unideal) solution I could put a dummy view inside foo/urls.py right at the very end with a path of "", and then reverse this. However I don't like this solution. It feels hacky, and would potentially have problems if a user ever hit this URL. -
React with Django in production
I am planning to deploy an application which is built in react frontend, and calls a python backend. What I am planning is to deploy react on a linux box on a node.js server and python on django behind Apache. Can someone would suggest if this would be right architecture from production grade perspective? If application is expected to get 1000 requests per hour, then will this architecture work? or I should replace or add components or layers? -
How to build conversational form with django?
I am trying to build a conversational form with Django. It will be used in landing page. The form questions will be loaded one by one as user answers them. And there will be some greeting and "human-way" responses to user input (such as "wow! you did a good choice!" after user selects one of the choices from form). The experience and look of the app will be like a real-time chat but user can only select one of the choices from form or upload a file/image. 1. Which technology is better to use for it? I am planning to do it with Fetch. 2. Since I want it to work without page reloading, how do I need to load Django forms through Fetch? Do I need to pass elements of it with JSON and construct it in client-side or can I just pass it as an html with {{form.as_p}} and display it in HTML? Does these options make difference in matter of security? -
Refreshing access tokens as soon an api call is made to prevent session from expiring
I have made a custom JWT authentication system which stores the refresh token in a cookie and the access token in json format. Since access token is short lived, ideally one needs to refresh the token by making a refresh api call. I have made the api call. But what i want is that the session besides the expiration time of the access token, as soon as another API call is being made the access token expiration time refreshes. And finally when the Refresh token expires OR there is an idle time between 2 API calls enough to expire the access token should i use Sign in again or use refresh access token function respectively. These are the functions that I have used : Get Refresh Token def generate_refresh_token(user): refresh_token_payload = { 'user_id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1), 'iat': datetime.datetime.utcnow() } refresh_token = jwt.encode( refresh_token_payload, REFRESH_TOKEN_SECRET, algorithm='HS256').decode('utf-8') return refresh_token Get AccessToken def generate_access_token(user, refresh_token): if not refresh_token: raise exceptions.PermissionDenied('No refresh token provided') else: access_token_payload = { 'user_id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=0, minutes=20), 'iat': datetime.datetime.utcnow(), } access_token = jwt.encode(access_token_payload, settings.SECRET_KEY, algorithm='HS256').decode('utf-8') return access_token Function to manually Refresh Access Token path : localhost:8000/api/token/refresh/ @api_view(['POST']) @permission_classes([AllowAny]) def token_refresh(request): Account = get_user_model() refresh_token … -
Errno 111 Connection refused cant use email verification
messing around with ths e-commerce site from github https://github.com/justdjango/django-ecommerce When I try to register a new user and enter an email I get ConnectionRefusedError. I've been trying to figure out how to configure email verification with Django but all the tutorials I found you have to add the code in the settings.py file which this github does not have so I'm not sure how to fix this. Sorry if this is a stupid question i'm quite new to programming. File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused [13/Aug/2020 21:46:00] "POST /accounts/signup/ HTTP/1.1" 500 186279 -
How to reset __class__.__name__ of a model instance?
I figure unregister() is not resetting the class name test: eav.unregister(Patient) self.assertFalse(Patient.objects.__class__.__name__ == 'EntityManager') unregister: def unregister(model_cls): if not getattr(model_cls, '_eav_config_cls', None): return reg = Registry(model_cls) reg._unregister_self() delattr(model_cls, '_eav_config_cls') unregister_self: def _unregister_self(self): self._detach_manager() if not self.config_cls.manager_only: self._detach_signals() self._detach_generic_relation() The test fails because the unregistration process does not reset the class name for some reason. Am I missing something? -
How to add custom domain to Google App Engine programmatically
I have created a django app using Google App Engine Flexible and would like the application to add custom domain programmatically. Basically the application would use subdomain to separate multi-tenancy for example tenant1.domain.com, tenant2.domain.com. Those custom domain will then have SSL managed by App Engine which help secure the application. As I know there's already python client library here https://cloud.google.com/python/references/libraries but which one should I use? -
How To Find Django Version Of A Project?
I have a Django project forked from GitHub. But I don't know which version of Django is used in that project. How can I find the Django version of the project ? I haven't installed Django in my PC. -
How do I toggle boolean field
I am working on a project where user have his own profile, I want to create a BooleanField on model so that user can set profile privacy, private or public. I have added a BooleanField to modal (is_private). Also i have a toggle switch on template but i do not know how to go with it with Django. I want when a user click on switch boolean field is true (private), when user click again on switch boolean field is false (public). Jquery maybe needed as well. Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) is_private = models.BooleanField(default=False) Template: <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="customSwitches"> <label class="custom-control-label" for="customSwitches">Private Account</label> </div> <p class="text-muted font-weight-normal font-small"> When your account is private, only people you approve can see your photos and videows on Pixmate. Your existing followers won't be affected. </p> -
Cannot understand SerializerRelated fields (CustomSlugRelatedField)
I had written a CustomSlugRelatedField class a long time back. I cannot remember and figure out what purpose it solved earlier, as both the SlugRelatedField and my CustomSlugRelatedField have the same functionality class CustomSlugRelatedField(serializers.SlugRelatedField): def __init__(self, *args, **kwargs): # Instantiate the superclass normally query_field = kwargs.pop('query_field', None) super(CustomSlugRelatedField, self).__init__(*args, **kwargs) if query_field: self.query_field = query_field else: self.query_field = self.slug_field def to_internal_value(self, data): try: return self.get_queryset().get(**{self.query_field: data}) except ObjectDoesNotExist: self.fail('does_not_exist', query_field=self.query_field, value=smart_text(data)) except (TypeError, ValueError): self.fail('invalid') -
Merge two Django apps
In my Django project, currently there are 2 apps created (app1 and app2). I want to merge all of app2 contents including, html, js, views.py etc... into app1. Is there any easy way to do this merge (or) I should just manually cut paste all of the app2 contents into app1 contents accordingly? Once the merge is done, app2 is to be deleted forever. Please suggest any ideas. -
Is it a good idea to use Gmail as my smtp server in Django for production? [closed]
I am working on a small scale project, we do not expect to go beyond 3000 users; is there any problem if we keep using Gmail as our smtp? -
Django conditional details in template
In my Django application there are users with department codes and I want show different details on template to these users, but superusers should see everything. Here are my codes: template.html: {% if user.is_superuser or user.department_code=1%} <p>Your department code is 1 or you are a superuser</p> {% elif user.is_superuser or user.department_code=2%} <p>Your department code is 2 or you are a superuser</p> {% else %} <p> You are a superuser</p> {% endif %} In this case I am as a superuser seeing only first paragraph. How could I do it correctly ? -
How can you create a kdbx file using python?
I am currently trying to make a keepass app using Python's Django framework. What Python modules are best to use in order to create and load the kdbx files for each user? -
Django Foreign Key Fields serializers with primary key and slug value
I want Django to serialise Foreign Key and Many-to-Many fields with a JSON object with both primary key and slug value: On normal GET request I receive: { 'album_name': 'Undun', 'artist': 'The Roots', 'track': 89 } If I use SlugRelatedField, I can receive: { 'album_name': 'Undun', 'artist': 'The Roots', 'track': 'Airport Surroundings' } However I want to receive the data in the following format, how can this be achieved { 'album_name': 'Undun', 'artist': 'The Roots', 'track': {"id":89, "name":'Airport Surroundings'} } -
Properly set up django react frontend with S3 bucket
I need help to properly set up my Django - react frontend for deployment with S3 bucket. loading the static files to S3 is not a problem, however once I do that I can't access the main.js anymore. here is my index.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> {% if token is not None %} <meta id="token" name="token" value="{{token}}"> {% endif %} <link rel="icon" href="{% static 'frontend/images/logo.png' %}"> <title>-------</title> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/line-awesome.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/line-awesome-font-awesome.min.css' %}"> <link href="{% static 'frontend/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/font-awesome.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/flatpickr.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/jquery.mCustomScrollbar.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/lib/slick/slick.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/lib/animate/animate.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/lib/slick/slick-theme.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'frontend/css/responsive.css' %}"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body> <noscript> <strong>We're sorry but --------- doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <script … -
How to navigate through a nav bar that dynamically creates categories in Django?
So I have a blog website where user can make posts by assigning categories to the post, and once there is a new category this category will appear on my nav bar. And I can go from home page to X category but cant go from X category to Y category with a nav bar directly. How should i solve this issue. It is been 2 days, i am trying to solve it. base.html <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog:post_list' %}">Home</a> {% for tag in tags %} <a class="nav-item nav-link" href="tag/{{ tag.slug }}/">{{ tag.name }}</a> {% endfor %} </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="{% url "blog:about_page" %}">About us</a> <a class="nav-item nav-link" href="{% url "blog:contact_page" %}">Contact</a> <a class="nav-item nav-link" href="#">Support</a> </div> </div> So when i go from home page and choose category X the url is http://127.0.0.1:8000/tag/X/ and when i switch it is http://127.0.0.1:8000/tag/X/tag/Y/ I understand that code in base.html only allows to have this type of url: http://127.0.0.1:8000/tag/X/ But how should i solve it, i will appreciate andy help! -
Limiting voting per user django
I have this code that enables you to vote for an article, right now a user can vote unlimited times I want to make it so when people click the button first time it gets the value by one and then decreased by one and so forth. here's article.html: <button id="vote">vote</button> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $("#vote").click(function (e) { e.preventDefault() var upvotes = $("#total_votes").html() var updatedUpVotes = parseInt(upvotes) + 1 $("#total_votes").html(updatedUpVotes) $.ajax({ url: 'vote/', method: "GET", data: {}, success: function (data) { console.log(data) }, error: function (error) { console.log(error) } }) }) </script> vote function in views.py: def vote(request, article_id): article = get_object_or_404(Article, pk=article_id) article.votes += 1 article.save() return JsonResponse(data = {"vote": "Voted! Thank you for the vote."}) -
Stop affecting other objects of Django Many to Many model
I'm trying to replicate Blood Group as Model as defined in this picture. . In my models.py file I had my code to replicate the blood groups like this class BloodGroup(models.Model): name = models.CharField( max_length=3 ) gives = models.ManyToManyField("self") receives = models.ManyToManyField("self") def __str__(self): return self.name And in my admin.py file I had registered the model as follows class BloodGroupAdmin(admin.ModelAdmin): model = BloodGroup list_display = ['name', 'get_gives', 'get_receives'] def get_gives(self, obj): return ", ".join([item.name for item in obj.gives.all()]) def get_receives(self, obj): return ", ".join([item.name for item in obj.receives.all()]) admin.site.register(BloodGroup, BloodGroupAdmin) Initially I created plain BloodGroup objects without their gives and receives attribute by providing just their names alone. Thus I create an object for all 8 types. Then as I added relationships to each object I found that adding gives or receives for one object affects other objects gives and receives too, making it impossible to replicate the structure in image. How do I define relationships, without affecting other objects? In my admin site, I see field names as "get_gives" and "get_receives". How would i make the admin page show field names as "gives" and "receives" but still displaying objects as strings like the image below? -
python workon command doesn't activate the virtual environment in cmd windows 7
We are trying to install a django project in a remote server that is Windows 7. The installer make a virtual environment and install some packages in it, django among them. The virtual environment is created (I can see it typeing workon or lsvirtualenv) but is not activated if I type workon in a cmd, simply prompts current path after press enter key In which cases happen this? Why can't I activate a virtual environment that exists? Note: This process finish successfuly in local machines -
Count number of times the value repeated in tuple [duplicate]
For example let us consider a tuple and get the count of 'hhh' and 'one'how many times it is totally repeated in the entire tuple. tuple = (('abc','def',1111,'hhh'),('xyz','ijk',2222,'hhh'),('qaz','stu',3333,'one'), ('yuz,'edc',7777,'two'),('www','yui',444,'one')) for i in tuple: for x in i: x.count() Here i want only count of 'hhh' and 'one' in the whole tuple. -
How i can generate urls in django?
What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language. -
Outputting all value descendants from a table when ManyToMany Django ORM
There are two tables catalog_product: id |name 10 prod3 9 prod2 8 prod1 11 prod5 catalog_productcategory: (mptt model) id | name | lft | rght | tree_id | level | parent_id 2 root1 1 6 1 0 null 3 subroot1 2 5 1 1 2 5 subsubroot1 3 4 1 2 3 6 root2 1 4 2 0 null 7 subroot2 2 3 2 1 6 Link table catalog_product_category: id | product_id | productcategory_id 7 10 2 8 9 3 9 8 5 10 11 7 the catalog_productcategory tree abstract looks like this: root1 subroot1 subsubroot1 root2 subroot2 My two models with many-to-many relationship class ProductCategory(MPTTModel): """категории продуктов""" name = models.CharField(max_length=255) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name def get_products(self): return self.category_products.all() class Product(models.Model): """Продукты""" name = models.CharField(max_length=1024) category = models.ManyToManyField(ProductCategory, related_name="category_products") def __str__(self): return self.name When accessing root1, I want to receive not only products that are in this root category, but also all products that are in child categories, and when accessing a child category, only what is in it. def getiing(request): categories = ProductCategory.objects.prefetch_related('category_products') stores = [] for cat in categories: products = [{'product_id': product.id, 'product_name': product.name} for …