Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Try except inside a function doesn't work but outside does
I'm trying to get the try except block outside of my function as a part of DRY. If I put it directly into the function it works @api_view(["GET", "POST"]) def user_info(request): if request.method == "GET": username = request.GET.get("username") password = request.GET.get("password") try: Account.objects.get(username=username, password=password) except Account.DoesNotExist: return JsonResponse({ "success": "false", "error_code": "1", }) But if I make it into function user_check it doesn't work @api_view(["GET", "POST"]) def user_info(request): if request.method == "GET": username = request.GET.get("username") password = request.GET.get("password") user_check(username,password) def user_check(username,password): try: Account.objects.get(username=username, password=password) except Account.DoesNotExist: return JsonResponse({ "success": "false", "error_code": "1", }) -
Is there a way better than this to save Database in django model from an external API?
I have an external API to get the data and I need to save the data into my Django Model. As of now I am writing a function that save the data into the Model from the JSON response of the API. Now since I need to save the database only once I need to remove the function so as to reduce the chance of duplicate data. So Is there any better way to save the data so that I do not need to remove the function and function is such that I runs only once in entire project? Any help would be appreciated. Thanks -
What should be the approach for the web platform i want to create and please don't down vote or close this question it is very important for me? [closed]
Let me start by what all things are involved: Data in csv file a python script that i have a python file containing a function that user have. On website the user will upload python file. Then the data i have in csv file will be parsed through user's given function which will generate a single Column Dataframe. Then the resultant Dataframe will be parsed through my Python script which will generate an output and this output will be presented to user on website. I am not able to get the approach and technologies involved but this is very important for me to do please help please Any resource or Reference will be helpful pls help Thank you. -
How to serialize a custom user model(inherited from AbstractUser class) in django rest framework?
I was following a tutorial on django rest framework in which we create a new user using register api route(/api/auth/register) and login the registered user using login api route(/api/auth/login). In this tutorial,for token authentication, django-rest-knox has been used and the default User model provided by django has been used for user accounts. I am trying to do something similar in my own app but I am using custom user model which has been inherited from AbstractUser class provided by django and also I am using Django Token authentication provided by rest_framework.authtoken. Following are the code and their results for serializers, Apiviews from the tutorial: Serializers look like this: from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") Now using these serializers API views were created … -
Django Rest Framework Session Authentication
I'm using Django-hosts and hosting my api at api.mydomain.com while my frontend is using django templates at mydomain.com. I'm having some trouble getting session authentication working– my understanding is that if I am session-authed on my web app, I should also be session-authed on my subdomain but this doesn't seem to be true. Is it because of the subdomain– and how should I deal with this? -
How to get extra columns in group by in Django?
I just want to include ID(and other fields) as well in the result of an annotate with values (i.e group by). I'll explain with an example (below is just an example, please suspend your disbelief on this bad model), class Book(models.Model): name = models.CharField() version = models.IntegerField() # Assming its just a number that increments when each version is published like 1...2...3 and so on. published_on = models.DateTimeField() author = models.ForeignKey(User) class Text(models.Model): book_text = models.ForeignKey(Book) What I want is the Max version(or editions) of a Book, which I achieve by Book.objects.values('name', 'author').annotate(Max('version')) **Generated SQL (MYSQL) query**: SELECT "name", "author", Max("version") AS "version__max" FROM "book" GROUP BY "name", "author" But the above result does not contain ID or published_on if I add them to values it groups by them as well, which is not what I want. I want to group by only name and author, But want other fields or at least get an ID. Expected SQL: SELECT "id", "published_on", "name", "author", Max("version") AS "version__max" FROM "book" GROUP BY "name", "author" -
I had created a login page, but whenever i enter credentials it shows me MultiValueDictKeyError at username
my html login page is: <html> <head> <title>Login Page</title> </head> <body> <form method="post" action="/login"> {% csrf_token %} <table width="20%" bgcolor="0099CC" align="center"> <tr> <td colspan=2><center><font size=4><b>User Login Page</b></font></center></td> </tr> <tr> <td>Username:</td> <td><input type="text" size=25 name="Username"></td> </tr> <tr> <td>Password:</td> <td><input type="Password" size=25 name="Password"></td> </tr> <tr> <td><input type="submit" onclick="return check(this.form)" value="Login"></td> </tr> </table> </form> <div> {% for messages in messages %} <h3> {{messages}} </h3> {% endfor %} </div> </body> </html> my views file is: def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request,'Invalid Credentials') return redirect('login ') else: return render(request,'login.html') my URLs for views are : from django.URLs import path from . import views urlpatterns = [ path('',views.homepage, name='homepage'), path('login',views.login, name='login'), path('registration',views.registration, name='registration'), ] kindly help me out to solve this problem kindly help me out to solve this problem kindly help me out to solve this problem kindly help me out to solve this problem kindly help me out to solve this problem kindly help me out to solve this problem kindly help me out to solve this problem -
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 = …