Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement Search field in ManytoManyField(Django Admin) models.py
I currently have a ManytoManyField in Django where I can Select multiple Users with strg and mouseclick. With much more Users it gets heavily complicated to search the User I want to select. Is there a possibility to have a ManytoManyField, but also have a search_field for Users, so I can search and pick. Thank you for your help! -
How do I create a form in django that selects instances of another django model?
I'm new to django and so far I've created these models. Climb represents climbing routes with names, week, grade, and points associated if completed and a Climber model that has climbs_completed, which is a collection of Climb. My question is how do I create a django form that displays the existing Climb objects with a checkbox so that the user can select which Climb he/she has completed and save it to their climbs_completed field? class Climb(models.Model): name = models.CharField(max_length=20, default='') grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] grade = models.CharField(max_length=3, choices=grades, default='v-1') weeks = [(i,i)for i in range(1,13)] week = models.IntegerField(choices=weeks, default=0) points = models.IntegerField(default=0) def __str__(self): return self.name 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 @property def total_score(self): return self.climbs_completed.aggregate(total_score=Sum('points'))['total_score'] -
Django efficient use of prefetch related in one to many relationship and large db
I'm already a few days busy creating a list of devices. A device is linked with gateways due to the gatewaydevice class. "GatewayDevice" is a table in SQL, where a device can be linked to many gateways. But for every device there is only one gateway with no "end_date", that's the current one. I need to display that gateway, for every device. Besides that there are some other attributes, but those are fine. I will start with the code of the models and then my query and serializer models: class Device(models.Model): name = models.CharField(max_length=250, null=True, blank=True) class GatewayDevice(models.Model): gateway = models.ForeignKey( Gateway, on_delete=models.CASCADE, related_name="devices" ) device = models.ForeignKey( Device, on_delete=models.CASCADE, related_name="gatewaydevices" ) class Gateway(models.Model): name = models.CharField(max_length=250, null=True, blank=True) view: def get(self, request): """ GET the data from all the devices. """ devices = Device.not_deleted_objects.filter( delivery_status=Device.RECEIVED ).prefetch_related( "site__users", "software_update_history", "supplier", Prefetch( "gatewaydevices", queryset=GatewayDevice.objects.filter( end_date=None, gateway__isnull=False ).prefetch_related("gateway"), ), ) serializer_class = self.get_serializer_class() serializer = serializer_class(devices, many=True) devices_data = serializer.data return Response( {"total": devices.count(), "items": devices_data}, status=status.HTTP_200_OK ) serializer: class AdminDeviceSerializer(serializers.ModelSerializer): gateway = serializers.SerializerMethodField() class Meta: model = Device fields = [ "id", "name", "gateway", ] @staticmethod def get_gateway(device): return GatewaySimpleSerializer(device.gatewaydevices.get).data class AdminDeviceInfoSerializer(AdminDeviceSerializer): owner = serializers.SerializerMethodField() supplier = serializers.SerializerMethodField() class Meta(AdminDeviceSerializer.Meta): fields … -
how to architect 'crawling.py file' and 'django-restapi server'?
guys. i have a problem. i made an android application written by kotlin. this app communicates to 'django-restapi server' to get some data. 'django-restapi server' gets data from 'crawling.py' file(using selenium,headless chrome). app : show data to people django-restapi server : get data from crawling.py, and saving data on database crawling.py(with chromedriver) : crawling data from website, and sending data to server so, what i want to know is, i don't know how to upload them. i want to use aws. what i'm thinking now is, upload 'django-restapi server' and 'crawling.py' to aws lambda seperately. then, i will run 2 lambda. but i think it's bad architecture. the alternative is to upload all of them into an ec2. and scheduling crawling.py works once in 10minutes. can you advice me better answer? -
Django Admin. Change the title of app page
The default title for every app page is '''verbose_name + "administration"''' How can I change it? -
Cant seem to get my model formset to update my record
The function to create a record works perfectly but the update is the problem. the update function is able to pull the data from the database but u cant save any changes. here is my view.py ''' the create view function def HunCreateView(request): BenefitFormset = modelformset_factory(Staff, form=BenefitForm) form = HonpvForm(request.POST or None) formset = BenefitFormset(request.POST or None, queryset=Staff.objects.none(), prefix ='marks') if request.method == 'POST': if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): pv = form.save(commit=False) profileid = request.user.profile.id pro = Profile.objects.get(id=profileid) pv.worker = pro pv.save() for staff in formset: data = staff.save(commit=False) data.Pv_reference = pv data.save() except IntegrityError: print("Error Encountered") messages.success(request, 'Pv created successfully') return redirect('pv:userdash') context ={'form':form, 'formset':formset} return render(request,'pv/Honurarium.html',context) ''' the update function def HunupdateView(request,pk): pupdate= Pv.objects.get(IA_System_Code=pk) supdate = Staff.objects.filter(Pv_reference=pk) BenefitFormset = modelformset_factory(Staff, form=BenefitForm) form = HonpvForm(instance=pupdate) formset = BenefitFormset(queryset=supdate, prefix='marks') if request.method == 'POST': if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): pv = form.save(commit=False) profileid = request.user.profile.id pro = Profile.objects.get(id=profileid) pv.worker = pro pv.save() for staff in formset: data = staff.save(commit=False) data.Pv_reference = pv data.save() except IntegrityError: print("Error Encountered") messages.success(request, 'Pv created successfully') return redirect('pv:userdash') context ={'form':form, 'formset':formset} return render(request,'pv/Honurarium.html',context) and here is my url.py path('pv/honurarium/',views.HunCreateView, name = 'pv-honurarium'), path('pv/<int:pk>/update/honurarium',views.HunupdateView, name ='hunupdate') the add more and delete fieldset … -
Python, is there a function that give me the cumulate sum? [duplicate]
I have the following list value: iva_versamenti_totale={'Liquidazione IVA': [sum(t) for t in zip(*iva_versamenti.values())],} I want to obtain about the iva_versamenti_totale variable the following sum: p0, p1+p0, p2+p1, p3+p2 and so on... Ad example: iva_versamenti_totale = {'Liquidazione IVA': [1,2,3,4,5],} result={'Totals': [1,3,5,7,9],} -
How Python Django Templates Know about Model user data , when I haven't Passed any data of Model User to template
I've looked through different tutorials and Stack Overflow questions and I'm not sure why I'm still running into this issue: -
Why might my code be using my OS's installed Python when I'm running in a virtual environment?
I'm following a book which introduces Django and at the same time teaches TDD for Python. The stage I'm at is attempting to use POP to retrieve an email (sent to a yahoo.com email) in order to examine its contents. I am running everything on my local machine (which is running tests against a remote server, in my case a VPS hosted by Hostinger). We've just been told to do this, on the local machine (in fact source this from a local .env file): YAHOO_PASSWORD=myYahooPassword The failure which this gives is like this: (test_venv369) mike@M17A ~/IdeaProjects/TestingGoat $ STAGING_SERVER=mikerodentstaging.xyz python manage.py test functional_tests.test_login ... ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 72, in test_can_get_email_link_to_log_in body = self.wait_for_email( test_email, SUBJECT ) File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 28, in wait_for_email inbox.pass_(os.environ['YAHOO_PASSWORD']) File "/usr/lib/python3.6/os.py", line 669, in __getitem__ raise KeyError(key) from None KeyError: 'YAHOO_PASSWORD' ... and my first puzzled response was to export the variable, instead of leaving it as a non-exported variable. This gave another error: the FT hung (!), for about 60 s, before ending thus: ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", line 72, in test_can_get_email_link_to_log_in body = self.wait_for_email( test_email, SUBJECT ) File "/home/mike/IdeaProjects/TestingGoat/functional_tests/test_login.py", … -
Error in fetching data from database SQL Server
I have a django project, wherein I take comments from user by executing the following command: Comment = request.POST.get('comment').replace('\n', '\026').replace(' ', '\030') The Comment is then inserted into the DB in the above shown form. There are several 'ID's, each of which can have multiple Comments. Now, the task is to fetch those IDs and corresponding comments which contain particular keywords, which are provided by the user. Here is the query(sample) I am using to fetch the required data: query = "select Comment, ID from table1 where ID in ({}) and Comment like '{}'".format("'1','2','3'", "%Compilation failed%".replace(' ', '\030').replace('\n', '026')) I want this query to fetch all those ID/comment pairs which contain the keyword Compilation failed. However, executing this is fetching me some IDs which actually do not contain the 'Compilation failed' error. What could be the reason for this? I tried a lot but could not figure it out. Any help is greatly appreciated! -
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?