Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create and implement a search function in Django?
I have created a blog app using Django and I would like for users to be able to search through the posts. Now doing a simple query lookup in Django is fairly straightforward, however, I need to add some Elasticsearch-like functionality. For example, if the spelling is incorrect it should still return the correct objects and I would also like to search both the titles and content of the posts. So if anyone knows of a free service that does this or how I can implement this myself, please let me know! -
How to update celery state depending on the task in the chain in Django
I have a Django app. When a process is initiated, a chain of celery tasks start. I track the status of the chain/progress in database. But celery status become SUCCESS right after first task is complete which only writing the process in database. Documentation is very complicated for me and I cannot make it work with examples on the web. How can I control the status so it only becomes SUCCESS when completes all the tasks? How can I update the status for each task? (Like task 2 is completed or working on task 3) How can I integrate failure as well? Chain Code chain( task1.s(), task2.s(), task3.s(), task4.s(), ).apply_async() Example task structure (Task 1) @app.task(bind=True) def task1(self, job_name=None, assigned_by=None): task = Tasks(task_id=self.request.id, job_name=job_name, assigned_by=assigned_by) task.save() return assigned_by -
Django admin: add/edit nested models on inlines
I have the following models. class Recipe(models.Model): title = models.CharField(max_length=200) class RecipeInstruction(models.Model): recipe = models.ForeignKey(Recipe, related_name='instructions', on_delete=models.CASCADE) text = models.CharField(max_length=255) class RecipeInstructionIngredient(models.Model): recipe_instruction = models.ForeignKey(RecipeInstruction, related_name='instruction_ingredients', on_delete=models.CASCADE) text = models.CharField(max_length=50) A recipe has one or more instructions to be followed and each instruction relates to a number of ingredients. The recipe for noodle soup could have an instruction "Add the spices" which could relate to the ingredients "pepper" and "salt". I am trying to find a way to have one django admin page from which I can edit the entire recipe without having to go to different pages to create/edit different models. Partially this can be done with inlines but I am struggling with the nested RecipeInstructionIngredient. My current admin looks like this: class RecipeInstructionInline(admin.TabularInline): model = RecipeInstruction extra = 1 show_change_link = True class RecipeInstructionIngredientInline(admin.TabularInline): model = RecipeInstructionIngredient extra = 1 class RecipeAdmin(admin.ModelAdmin): inlines = [ RecipeInstructionInline, ] class RecipeInstructionAdmin(admin.ModelAdmin): inlines = [RecipeInstructionIngredientInline] admin.site.register(Recipe, RecipeAdmin) admin.site.register(RecipeInstruction, RecipeInstructionAdmin) This creates an admin page where I can create/edit a recipe and add one or more instructions inline on the same page. However you cannot select one ore more ingredients to be linked to those instruction. I did add the "change link" … -
Django Channels - receiver function called multiple times depending on number of open web sockets
I don't understand the behavior of Django Channels 2.4.0. When multiple web sockets are open, the receiver function is called as often as web sockets are open. Here the minimal code from the well-known chat example of the channels documentation # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group async def chat_message(self, event): print(event) # this is called as often as sockets are open message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) The problem becomes strong when I want to do logic things in the database triggered from the receiver function. Then things start to be done multiple times depending how many web sockets are open. Any idea what I'm missing here? -
Adding Jinja2 to Django Cookiecutter
I love django Cookiecutter but it moves things around and makes it a challenge to set things up via things like the Django docs. I am trying to install Jinja2 via the Django docs. I want to install the environment code to be able to use URL and static. But Cookiecutter moves the settings folder and I can not figure out how to call it? Here is the file structure. It is a matter of adjusting this line: ‘environment’: ‘nesoi.jinja2.environment’ { ‘BACKEND’: ‘django.template.backends.jinja2.Jinja2’, ‘DIRS’: [], ‘APP_DIRS’: True, ‘OPTIONS’: { ‘environment’: ‘nesoi.jinja2.environment’ }, } This is the environment in the jinja2.py file: from django.templatetags.static import static from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': static, 'url': reverse, }) return env Thanks so much. -
Django path issue when deploying with Zappa to AWS
I am trying to deploy a Django site using Zappa. I followed this guide to get things off the ground but used Pipenv as virtual environment manager. Django seems to be running, but I am having an issue with the stage in the url being evaluated: Error. I am expecting django to ignore the dev/ part of the url but apparently it considers it and hence cannot resolve the urls correctly. I have been searching quite a bit but could not find anything useful. Some recommended changing FORCE_SCRIPT_NAME (Django in sub-directory) but that did not lead to anything for me. My configuration for zappa_settings.json: { "dev": { "aws_region": "eu-central-1", "django_settings": "coi.settings", "profile_name": "default", "project_name": "coi-project", "runtime": "python3.7", "s3_bucket": "zappa-...", "timeout_seconds": 60, "vpc_config" : { "SubnetIds": [ "subnet-03bc...", "subnet-04d3...", "subnet-0f81..." ], "SecurityGroupIds": [ "sg-089c..." ] } } } The environment (pip freeze): argcomplete==1.11.1 asgiref==3.2.7 boto3==1.13.5 botocore==1.16.5 certifi==2020.4.5.1 cfn-flip==1.2.3 chardet==3.0.4 click==7.1.2 diff-match-patch==20181111 Django==3.0.6 django-crispy-forms==1.9.0 django-login-required-middleware==0.5.0 django-reversion==3.0.7 django-reversion-compare==0.12.2 django-s3-storage==0.13.0 docutils==0.15.2 durationpy==0.5 future==0.18.2 hjson==3.0.1 idna==2.9 importlib-metadata==1.6.0 jmespath==0.9.5 kappa==0.6.0 Markdown==3.2.1 mysqlclient==1.4.6 pip-tools==5.1.2 placebo==0.9.0 PyMySQL==0.9.3 python-dateutil==2.6.1 python-dotenv==0.13.0 python-slugify==4.0.0 pytz==2020.1 PyYAML==5.3.1 requests==2.23.0 s3transfer==0.3.3 six==1.14.0 sqlparse==0.3.1 text-unidecode==1.3 toml==0.10.0 tqdm==4.46.0 troposphere==2.6.1 urllib3==1.25.9 Werkzeug==0.16.1 wsgi-request-logger==0.4.6 zappa==0.51.0 zipp==3.1.0 -
I have made a chatbot through IBM AI Watson Assistant.How do I integrate with my own CRM?
As the title suggests I have made a chatbot through IBM AI Watson Assistant and have implemented on my website. I have also made a separate CRM through Python and Django and I have created a separate Messages html where I want the chatbot messages to be recorded so that the sales representatives can follow up with potential customers. Is there an easy way to do this? Can the messages be recorded in the CRM?? -
django.core.exceptions.ImproperlyConfigured: error is coming
I am new to Django and hence don't have much idea about it. I am trying to create an app having the following contents in my view.py file: from django.shortcuts import render from fusioncharts.models import City def pie_chart(request): labels = [] data = [] queryset = City.objects.order_by('-population')[:3] for city in queryset: labels.append(city.name) data.append(city.population) return render(request, 'pie_chart.html', { 'labels': labels, 'data': data, }) The content of my urls.py file inside the app is as follows: from django.urls import path from fusioncharts import views urlpatterns = [ path('pie-chart/', views.pie_chart, name='pie-chart'), ] and the content of my urls.py file inside the main project folder is as follows: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', include('fusioncharts.urls')) ] In the settings.py file, I have added the following: ROOT_URLCONF = 'Piechart.urls' and under the TEMPLATES, added the following: 'DIRS': ['Piechart/fusioncharts/templates'], Now while running my app, I am getting the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'Piechart.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Can anyone please say what's going wrong? -
Heroku Postgres - How come my production database is working, even though not listed in settings.py - Django?
I configured my database in Heroku several months ago so don't remember exact steps I took. I'm using the Heroku-Postgres add-on: https://devcenter.heroku.com/articles/heroku-postgresql I have a DATABASE_PASS listed as a config var in Heroku. And I have a config var for DATABASE_URL In my settings.py file I only have the following as it relates to my database - Why is my app still working in production on Heroku if DATABASES variable is referring to localhost only?: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_dev', 'USER': 'postgres', 'PASSWORD': os.environ.get('DATABASE_PASS'), 'HOST': 'localhost', 'PORT': '5410', } } The Heroku-Postgres documentation states the following: The value of your app’s DATABASE_URL config var might change at any time. You should not rely on this value either inside or outside your Heroku app. Am I doing something wrong? Should I not rely on DATABASE_URL as a config var? -
object filtering in template django
I have 2 class of model post and comment for loops in my template like this I have a for loop like this {% for post in posts %} {% endfor %} and I want to make filter like this Comment.objects.filter(post=post.id) in my for loop and get some value how to write it properly? -
How to Implement Multiple User Types with Django?
I want to create a Django model like user_types = (("Agent", "Agent"), ("Branch", "Branch"), ("Company", "Company")) class User(models.Model): email = models.EmailField(db_index=True, unique=True) username = models.CharField(db_index=True, max_length=255, unique=True) user_type = models.CharField(max_length=100, choices=user_types, blank=False) and if user define user_type to store these field data there should come some extra field like: if user_type is Agent then: agent_code agent_name if user_type is Branch then: Branch_code Branch_name Branch_Id if user_type is Company then: Company_code Company_name Company_Id Is there any good way to handle this model? -
I want to detect the user's computer language so that I can translate the page according to it
I want the user to enter the website to see the text translated in his computer's language and this is what I am trying to do but when I change my computer language into Spanish, nothing changes def index(request): lang = get_language() translation.activate(lang) return render(request, 'index.html') -
How can I hide Vue code in a non SPA Django and Vue project?
I am working on a Django web app and have used Vue components inside it. Everything is fine but my only concern is that I don’t want the source code to be visible in production . I don’t want to go by the full SPA route as it will take a lot of time and effort. Can I make the code less human readable ? See if i view it in the browser then it’s completely readable and I would not like it this way in production Please help me here !! Thanks in Advance -
How do I link a User with a django model as soon as the User is created?
I am new to Django and my question is how do I link a Django User with the Climber model that I created as soon as the user is registered? So far, I can register a new User with Django's builtin user registration form. But when I go into my admin page I see that I have to create a new Climber manually and select which User I want it to link to. Thank you in advance! class Climber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] highest_grade = models.CharField(max_length=3, choices=grades, default='v0') team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) climbs_completed = models.ManyToManyField(Climb, blank=True) def __str__(self): return self.user.username # for each climbs_completed, sum up the points def total_score(self): pass -
How to access sum of reverse foreign key single field using template filter in django?
Suppose I have 2 models Customer & Account. Models class Account(models.Model): customer = models.ForeignKey(Customer,on_delete=models.CASCADE, blank=True,null=True,related_name='account') desc = models.CharField(max_length=100) paid = models.IntegerField(default=0) received = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Customer(models.Model): name = models.CharField(max_length=30,unique=True) contact = models.CharField(max_length=10) I want to access Sum of received & Sum of paid field in template Customer View def show_customer(request,id=None): customer = Customer.objects.filter(user=request.user) return render(request,'customer/show_customer.html',{'customer':customer}) show_customer.html <html> {% for cust in customer %} {{cust.name}} {{cust.contact}} **Here I want sum of paid & sum of receive for current customer** </html> -
getting the value of request.GET in python
I tried to get the data in request.GET data however this gives me an empty values or None when printing. class SchoolMixin(ProfileTypeRequiredMixin, MultiplePermissionsRequiredMixin): profile_type = 'manager' permissions = { 'any': ('school.admin, ) } def init_vars(self, request, *args, **kwargs): self.schools = self.request.user.manager.school self.vals(request) def vals(self, request): if not request.GET: if self.schools.school_set.exists(): school = self.schools.school_set.all()[0].pk else: school = None data = { 'school': school, } else: data = request.GET self.filter_form = forms.FilterForm( data=data, prefix='FILTER', school_manager=request.user.manager, user=request.user ) self.filter_form.is_valid() self.school = self.filter_form.cleaned_data['school'] def get_context_data(self, **kwargs): data = super(SchoolMixin, self).get_context_data(**kwargs) data['filter_form'] = self.filter_form return data class FilterForm(forms.Form): school = forms.ModelChoiceField( label=_('School'), required=False, queryset=School.objects.none(), empty_label=_('School'), widget=forms.Select(attrs={'class': 'form-control'}) ) .... def __init__(self, *args, **kwargs): self.school_manager = kwargs.pop('manager') self.user = kwargs.pop('user', None) super(FilterForm, self).__init__(*args, **kwargs) url(r'^school/$', views.ExportView.as_view(), name='export'), I tried on older branch and I get the value of request.GET, I use the self.request.GET but still I get an empty or None. Thanks -
Creating a model in Django whose field has multiple other fields inside it
I'm quite new to Django and would like to clear a noob doubt. Say I have a post request to a model 'Scans' in django. The json data for the same looks like [{"id":1, "results":{"low": 3, "medium": 6, "high": 7}, "machine": "Windows", "report": "yes"] How should the model look like? I can't figure out what field type I should give to "results". -
Adding products to cart not working properly
I'm facing a problem with the code, a bug to be more specific, that is when I'm adding an item to the cart for the first time(with variations let's say Green and Medium), it's being added nicely. Then when I'm adding another item(let's say Blue and Small), it's also working. But when, I'm increasing the item quantity from the order_summary.html, it's increasing the quantity of the other item not the one I clicked(if I clicked Red and Medium, Blue and Large's quantity is increased) and says : Please specify the required variations. Why is this happening? It's also worth noting that when I'm adding the same item with same variations from my single product page, then it's working fine. I think this bug is occurring because of the way my views is written. I tried to solve it myself, but I'm getting lost. Can anyone please help me out? Thanks in advance! My models.py: class Item(models.Model): title = models.CharField(max_length=120) price = models.FloatField() class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) name = models.CharField(max_length=50) # size, color class ItemVariation(models.Model): variation = models.ForeignKey(Variation, on_delete=models.CASCADE) value = models.CharField(max_length=50) # small, medium large etc class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) item_variations = … -
Catch 401 exception in django
I'm trying to catch exception via try-catch in Django for unauthorized users i.e status code of 401. I tried: try: result = Users_Details.objects.get(auth_token=auth_token) result.password = password result.save() except Users_Details.DoesNotExist as e: error = {"status": "failure", "reason": str(e)} return JsonResponse(error, status=status.HTTP_401_UNAUTHORIZED) But it's not working. what am I doing wrong here ? -
Django Jinja2 how to convert things like {% load tawkto_tags %}?
How do I make the jump with Jinja to load things like my tags at the top of the html? {% load tawkto_tags %} I am using django-jinja with Cookiecutter. Is changing to Jinja really worth the speed??? Thanks! -
form validation errors in django
Every time I'm facing field validation error for datetime field in django. Actually I didn't know how this field works. Here is my model. and also I'm using crispy forms enter image description here class Customer(TimeStampWithCreatorMixin): check_in = models.DateTimeField(_("Check In"), auto_now=False, auto_now_add=False) and here is my forms.py code class CustomerCreateForm(forms.ModelForm): class Meta: model = Customer exclude = ('updated_by',) widgets = { 'check_in': forms.TextInput(attrs={ 'class': "form-control datetimepicker-input", 'id': "check_in", 'data-toggle': "datetimepicker", 'data-target': "#check_in", 'autocomplete': 'off', }) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('check_in', css_class='form-group col-md-6 mb-0'), ) ....... Submit('submit', 'Add Customer') ) I'm also using https://tempusdominus.github.io/bootstrap-4/ for date and time picker. -
Enabling SSO across several domains that consume the same service based backend
The most obvious solution here will allow session based authentication which is considered a bad practice in Django shomehow. So I have worked out a simple way to play the token in a cookie and then try to read it from the cookie if it is absent in the headers (like in the case of moving between 2 different domains that consume our API). The request returns the following data in the 'Cookies' sections under 'Network' However, under 'Application' I cannot see the cookie at all This is the code I have written middleware.py class WhiteLabelSessionMiddleware(MiddlewareMixin): def process_request(self, request): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if cookie_token: print(cookie_token) if cookie_token and not request_token: # must be assigned by reference request.request.META['HTTP_AUTHORIZATION'] = cookie_token def process_response(self, request, response): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if not cookie_token and request_token: response.set_cookie(settings.WHITE_LABEL_COOKIE_NAME, request_token, max_age=settings.SESSION_COOKIE_AGE, expires=settings.SESSION_COOKIE_AGE, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE) return response settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.WhiteLabelSessionMiddleware', 'core.middleware.TimezoneMiddleware', 'core.middleware.LastSeenMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'referrals.middleware.ReferralMiddleWare', 'audit_log.middleware.UserLoggingMiddleware', 'axes.middleware.AxesMiddleware', ] WHITE_LABEL_COOKIE_NAME = 'nex_token' SESSION_COOKIE_AGE = 60 * 60 * 24 * 30 * 12 _COOKIE_EXPIRES = datetime.datetime.utcnow() + \ datetime.timedelta(seconds=SESSION_COOKIE_AGE) SESSION_COOKIE_EXPIRES = \ datetime.datetime.strftime(_COOKIE_EXPIRES, "%a, %d-%b-%Y %H:%M:%S GMT") SESSION_COOKIE_DOMAIN = '.n.exchange' … -
Database Engine for PyODBC
So django currenty only provide 4 backend database engine which is : 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' If I use MySQL, all I have to do is just fill the Engine with 'django.db.backends.mysql'. But now, because my main Database is DB2, I'm having some issues to connect it with pyodbc. A help would be appreciate. Thanks! DATABASES = { 'default': { 'ENGINE': '', #some pyodbc backend database 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Field 'id' expected a number but got 'on'
I am doing a project included in Django Documentation.When i enter URL-http://localhost:8000/polls/1/vote/ i get the Error at below line, ` selected_choice = question.choice_set.get(pk=request.POST['choice']) -
I want to restrict the user from adding the duplicate value in 'type' field
class Device(models.Model): # name of the table type = models.CharField(max_length=100, blank=False) price = models.IntegerField() choices = ( ('AVAILABLE', 'Item ready to be purchased'), ('SOLD', 'Item Sold'), ('RESTOCKING', 'Item restocking in few days') ) status = models.CharField(max_length=10, choices=choices, default="Sold") # Available, Sold, Restocking issue = models.CharField(max_length=100, default='No Issue')