Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to sort a select based on the length of two concatenated fields
I'm using Django 3.0 This is my model: class StoreIdentification(models.Model): store = models.ForeignKey(Store, blank=True, on_delete=models.CASCADE, default=None) description_1_text = models.CharField(max_length=48, null=True, blank=True, default=None) description_2_text = models.CharField(max_length=48, null=True, blank=True, default=None) def __str__(self): return f'{self.store.name} - {self.description_1_text} + {self.description_2_text}' I have a select where I need to sort based on the length of the concatenated text of both description_1_text and description_2_text. I'm able to do each one of them separately, all my tries failed. Here are some tries: def identify(request): identifiers = StoreIdentification.objects.all().extra( select={'char_num': 'Length(description_2_text)' + 'Length(description_1_text)'} ).order_by('-char_num') for identifier in identifiers: # Do something ... This one is returning an error next to he Lenght (django.db.utils.OperationalError: near "Length": syntax error) Another try: identifiers = StoreIdentification.objects.all().order_by( Length('description_1_text' + 'description_2_text').desc()) This one concatenated the description_1_text and description_2_text before they were resolved. Try #3: identifiers = StoreIdentification.objects.all().extra( select={'char_num': 'Length(description_2_text) + Length(description_1_text)'} ).order_by('-char_num') The last try just ignored the Length(description_1_text) and ordered only based on description_2_text. I had a few other tries, all ended the same ... with some error. Any suggestions? -
Getting certain value from json
<h2>Content as Array.</h2> <p>Content written as an JSON array will be converted into a JavaScript array.</p> <p id="demo"></p> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr } }; xmlhttp.open("GET", "http://127.0.0.1:8000/test", true); xmlhttp.send(); </script> output: Content as Array. Content written as an JSON array will be converted into a JavaScript array. [{"model": "core.newcarmodel", "pk": 1, "fields": {"car_model_new": "swift"}}, {"model": "core.newcarmodel", "pk": 2, "fields": {"car_model_new": "wagonr"}}, {"model": "core.newcarmodel", "pk": 3, "fields": {"car_model_new": "baleno"}}, {"model": "core.newcarmodel", "pk": 4, "fields": {"car_model_new": "breeza"}}, {"model": "core.newcarmodel", "pk": 5, "fields": {"car_model_new": "spresso"}}] how to get all the carmodels values example: output: swift,wagonr,baleno....so on i would like to get carmodels values from json format and insert in variable like a list example: var carmodel = [swift,baleno,wagonr....] -
DjangoModelForm: How to add extra fields and preprocess them before sending to views
I have a model form which displays all the fields: class BatchForm(ModelForm): class Meta: model = Batch fields = ('__all__') It works fine and shows all the fields in the views. I now want to add extra fields to this form which dont exist in the model. These fields are: completed_tasks: int statistics: array I then want to add 2 methods in the form which auto populate these fields before sending it to the view. The methods will be: def completed_tasks_method(self, obj): return obj.assignments_per_task * obj.total_tasks() def statistics_method(self, obj): #something i cant figure out how to extend the modelform to add additional attributes and then how to populate the fields before sending them to the views. Can you please help ? Thanks. -
Write a thinner view in django ModelViewSet
I have a sample project as follow github link. The problem is the logic handles mostly on view, not serializers. I read it as a bad practice: class OrgAddAPI(viewsets.ModelViewSet): queryset = Organization.objects.root_nodes() serializer_class = OrganizationSerializer def create(self, request): alldata = request.POST # desc = alldata.get("desc", "0") # name = alldata.get("name", "0") desc = request.data.get("desc") name = request.data.get("name") code = request.data.get("code") subpath = request.data.get("subpath") try: parent = Organization.objects.root_nodes().get() except Exception as e: print(e.__class__.__name__) if e.__class__.__name__ == "DoesNotExist": parent = Organization.objects.create(name="BOSS", desc="boss",code="BOSS",subpath="ftech") else: response_dict = {"c" : ErrorCode.ORG_GENERIC_ERROR, "m": str(e), "e" : ErrorCode(ErrorCode.ORG_GENERIC_ERROR.name)} return Response(response_dict) try: Organization.objects.create(name=name, desc=desc, code = code, subpath =subpath, parent=parent) except Exception as e: response_dict = {"c" : ErrorCode.ORG_GENERIC_ERROR, "m": str(e), "e" : ErrorCode.ORG_GENERIC_ERROR.name} return Response(response_dict) response_dict = {"result": "true"} # update response_dict with whatever you want to send in response return Response(response_dict) I tried to refactor to serializer but it not jump to the new function: class OrganizationSerializer(serializers.ModelSerializer): children = RecursiveField(many=True) def validate(self,data): """ //// not jump check that root node must be available :param data: :return: """ serialized = jsonpickle.encode(data) print(yaml.dump(yaml.load(serialized), indent=2)) def create(self, validated_data): name = validated_data.get("name", None) // not jump serialized = jsonpickle.encode(validated_data) print(yaml.dump(yaml.load(serialized), indent=2)) class Meta: model = Organization fields = ('id', 'name', … -
How to use django notifications-hq?
I'm using django notifications for notification of my app and it notifies the user when their is some activities with their post. But i want to add the url of the post in the notification list so users will click the notification and can go to the specific post. I've tried it many ways but can't find the solution. -
How can I speed up call forwarding on Twilio? - Django
I just implemented call forwarding based on the following Twilio tutorial: https://www.twilio.com/docs/voice/tutorials/call-tracking-python-django The call forwarding works, however there are about 3 seconds of "static sounds" before the phone that is dialing the number starts hearing the phone ringer. Why is there such a delay in forwarding the call, how can this be resolved for a production level application? Calls are made over US phone networks, so did not expect delay issues. This is the function implementing the forwarding: # views.py # View used by Twilio API to connect callers to the right forwarding # number for that lead source @csrf_exempt def forward_call(request): """Connects an incoming call to the correct forwarding number""" # First look up the lead source source = LeadSource.objects.get(incoming_number=request.POST['Called']) # Respond with some TwiML that connects the caller to the forwarding_number r = VoiceResponse() r.dial(source.forwarding_number.as_e164) # Create a lead entry for this call lead = Lead( source=source, phone_number=request.POST['Caller'], city=request.POST['CallerCity'], state=request.POST['CallerState']) lead.save() return HttpResponse(r) -
Filter based on number of manytomany
I have models defined as follow: class Employee(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class Project(models.Model): ... employees = models.ManyToManyField(Employee, null=True, blank=True) I'm trying to retrieve all the projects that have at least one employee assigned to them, but I don't know how. I tried the following things: projects.filter(employees__gt=0) where projects = Project.objects.all() but I don't think this is the right query, because if I do projects.filter(employees_lte=0) it returns nothing, even if I have projects with no employees assigned. How can I retrieve what I'm looking for? Could you point to a page where I can find all the lookups I can use? Thanks! -
Django url dispatcher using repath arguments
In my django app . I have endpoints for a package with the months like : www.example.com/cart/packagename/months www.example.com/cart/stater/3 which i dont think will good as an url pattern I want something like : www.example.com/cart/?package=stater&months=3 And also want to encode the parameters 'package=stater&months=3' If anyone has any suggestions how to achieve that with django let me know. because before i worked with laravel and its pretty simple to do. -
vscode django extentions makes vscode can't recognize html files
I have installed most of django extensions on vs code , but vs code can't recognize the html files after installing any of them. Is there any way to use any django extension while the html files is recognized by vs code -
Generating PDFs from Pandas DataFrame with ReportLab with Python
I have been battling with exporting my Pandas DataFrame to PDF. Let me explain the situation. I have a Pandas DataFrame for example: commissions_df.columns = [ 'Versicherer', 'Produkt Bereich', 'Produkt Typ', 'Produkt', 'Vertragsart', 'Steuersatz', 'AP gesamt', 'BP gesamt', "Anteil Partner" ] I would like to filter by 'Versicherer', which is category type and have each DataFrame as a separate frame. I was successful at exporting each frame as a sheet with Excel. Here is an image of the way it looks: And here is the code I used to do that: Different_Versicherer = commissions_df.Versicherer.unique() number1 = np.random.randint(0,100) number2 = np.random.randint(101,800) FileName1 = 'FileName' con = "_" ext = ".xlsx" excelname = FileName1 + con + str(number1) + con + str(number2) + ext writer = pd.ExcelWriter(excelname) # iterate through each insurance and add a seprate sheet for all of them for Versicherer_names in Different_Versicherer: frame = commissions_df[commissions_df['Versicherer'] == Versicherer_names] frame.to_excel(writer, sheet_name= Versicherer_names[0:7],index=False) writer.save() Right now, I would like to export the DataFrames to PDF using ReportLab and have each unique item in Versicherer have its own page with header colour: So far here is what I tried: import reportlab from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.utils import ImageReader … -
Difference between 2 identical codes
I'm am trying to troubleshoot an HTTP response one code works fine but, the other one is returning an ValueError they are the both same code and I looked over them for 1hr side by side but, I can't find what is wrong with the bad code this is really bugging me. Working code:` from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: user = User.object.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username in use'}) except User.DoesNotExist: User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request.user) return redirect('home') else: return render(request, 'accounts/signup.html') def login(request): return render(request, 'accounts/login.html') def logout(request): return render(request, 'accounts/signup.html') BAD CODE: from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth def signup(request): if request.method =='POST': if request.POST['password1'] == request.POST['password2']: try: user = User.object.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error':'Username in use '}) except User.DoesNotExist: User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request.user) return redirect('home') else: return render(request, 'accounts/signup.html') def login(request): return render(request, 'accounts/login.html') def logout(request): return render(request, 'accounts/signup.html') ` -
Make search_fields for integer value
I made models like this and it has the IntegerField. class Corpus(models.Model): text = models.TextField(null=False) manual = models.IntegerField(blank=True,null=True) issues = models.ManyToManyField(Issue,blank=True,null=True) def __str__(self): return self.text And I set, "search_fields' admin class. I expected pull down menu for manual however there is only one text box on the page. class CorpusAdmin(admin.ModelAdmin): list_display = ['text','manual'] search_fields = ['text','manual'] list_editable = ['manual'] How can I use search_fields for integer value?? -
Having trouble with Django and adding to tables
I was following a tutorial on youtube and it came to a point where we were putting data on tables on the admin site. This is the link with the time stamp https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20490s when I finished with the info it brings up this error message OperationalError at /admin/products/product/add/ no such table: main.auth_user__old btw im on MacOs Catalina django = 2.1 python = 3.8 Anything I can do? -
Updating multiple objects with one request in Django and Django Rest Framework
I need to update multiple Education objects at a time from one request. My Views is: def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial, many=True) # many = True for multiple update if serializer.is_valid(): self.perform_update(serializer) response = create_response(True,data = serializer.data) return Response(response, status=status.HTTP_200_OK) else: response = create_response(False, err_name = serializer._errors) return Response(response, status = status.HTTP_400_BAD_REQUEST) and my serializer is : class Meta: model = Education fields = ['user','level', 'institute', 'start_date', 'complete_date'] 'many=True' is only work for multiple objects create. How to update multiple objects at a time? -
How to move local django project to an already established server
Note: I think this is just an ftp issue. I really just don't know which files to move to the server. I have seen lots of tutorials on configuring a server to host a django project. I already have that established, now I am unsure how to move my actual local django project to the server (in a way that does not cause a 502 Bad Gateway error). I have a properly configured server connected to a domain. I added a simple test app with one view that returned HttpResponse('working'). Went to my domain and saw this HttResponse. I thought, great everything is working, I can delete this app and upload my local project now (except for production-specific settings) and everything would work. I connected to the server via sftp, moved to my 'home/user/project' folder (contains env, django_project, manage.py). At this point, I don't think I need to copy everything from my local project to the server(such as my local env, and possibly my local manage.py and other files). I tried to copy over specific apps but that just lead to a 502 Bad Gateway error. I couldn't get to the bottom of that error so I scrapped the django … -
django.urls.exceptions.NoReverseMatch despite setting all the parameters
So I think I added everything correctly, with the url patterns, views, and the html page, but I'm not sure what went wrong. path('hero/<int:hero_id>/', manage_hero, name="manage_hero"), @login_required def manage_hero(request, hero_id): context = {'hero_bar' : True} profile = UserProfile.objects.get(user=request.user) hero = get_object_or_404(Accskill, id=hero_id) if not profile.player.guid == hero.guid: return render(request, "dashboard/no_permission.html", context={'redirect' : reverse("dashboard:dashboard")}) context['hero'] = hero context['form'] = ModifyHeroForm(hero=context['hero']) return render(request, "hero/hero.html", context=context) <td><a href="{% url 'hero:manage_hero' hero_id=hero.ID %}" class="btn btn-outline-primary" role="button" aria-disabled="true">管理英雄</a></td> -
Django: Where is the best place to store uploaded file(pdfs, docs) that a user share on a django project?
I am currently working on a Django project to make a file sharing website. I do aware that Django models cant save a file in their fields and only store a string that refers to it, and the file is saved in whatever folder i set in MEDIA_ROOT setting, which I find is not very secure and effective. So where do I store these uploaded files? Or is it safe enough to store it in the folder set by MEDIA_ROOT? I can’t give any progress now as it is still all in my head and I have been searching too and the answer is nowhere to be found(or maybe i didnt try enough). So what is the best practice to store these files? -
Get related_name of Django ForeignKey field at runtime
Let's say I have the following Django models: class Person(models.Model): name = models.CharField(max_length=50) class Pet(models.Model): name = models.CharField(max_length=50) person = models.ForeignKey(Person, related_name='pets', on_delete=models.CASCADE) I need to get the string value of related_name for Pet.person at runtime. I can get the related_query_name, which is "pet" but that's slightly different than the related_name, which is "pets": print(Pet._meta.get_field("person").related_query_name()) # pet Looks like the related name is on the Person class, but I'm not sure how to prove it's tied to Pet.person. print("pets" in [f.name for f in Person._meta.get_fields()]) # True Is there anyway to do this? -
How can we deploy my python-multitenant SAAS App in Amazon EC2?
First of all forgive me if this is not right place to ask this question. As we have been working on multi tenant based SAAS application using python, python-django, python django multitenant-schema, postgres and Redis for backend and angular for front-end. However, we would like to deploy this system on AWS EC2 for testing as well as to work on code automation (CI and CD) using AWS Code Pipeline. Can somebody guide me through right process or any link will be available? I went through this link but could not success and though there could be some easier way to do so. Thank you -
Heroku Django site is suddenly giving 400 errors on PUT requests
I'm not sure if this a Heroku or Django thing specifically, but thought I would try asking here. I have a site deployed on Heroku with Django REST and VueJS. The site was deployed last week and seemed to be working as intended. In the last few days, however, end-users haven't been able to make successful PUT requests, though they can access other parts of the site without a problem. I checked the logs and they seemed to be getting 400 errors all of a sudden. Everything is fine whenever I make a PUT request, and a couple of users had no issues the day before either. It's strange because its popped up all of a sudden, even though it seemed to be fine before. I'm a newb developer so I'm probably missing something obvious, but is it likely to be an error at the server end or something in my code...? Thank you! -
Conditional in crispy forms
I'm actually trying to figure out how to be able make a condition on a field in a HTML page. I've a form in which I want to render a field if the users ask for a 'web application' in the Choicefield above. But I've two problems. First the "conditionnalWeb" form render before the "typeOfTheProject" one. Second, I tried a lot of things but it never worked on how to make this condition. It's probably an easy solution but it's my first time working with django and crispy form. Here is the form: class ConfiguratorForm(forms.Form): queryOfProject = TypeOfProgram.objects.values_list('name') queryOfFramework = Framework.objects.values_list('name','version') queryOfDatabase = Database.objects.values_list('name','version') listFramework = [] listProject = [] conditionnalWeb=[] listFramework=[((q[0],q[1]),q[0]+" version "+q[1])for q in queryOfFramework] listProject=[(q[0],q[0])for q in queryOfProject] listDatabase = [((q[0],q[1]),q[0]+" version "+q[1])for q in queryOfDatabase] typeOfTheproject = forms.ChoiceField(choices = listProject) conditionnalWeb = forms.ChoiceField (choices = [('', '----'),("Only Backend","Only Backend"),("Only Frontend","Only Frontend")]) wantedFramework = forms.MultipleChoiceField(choices = listFramework) wantedDatabase = forms.MultipleChoiceField(choices = listDatabase) Here is the HTML: {% extends 'forms/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success">Save configuration</button> </form> {% endblock %} </html> I've left the easy {{form|crispy}} . All the others strategies that I tried … -
celery + redis Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused
I can not run the celery worker + redis + django. If I run this command to check that celery worker is ready to receive tasks: celery -A car_rental worker -l info I got this error: [2020-02-24 00:14:42,188: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. Trying again in 2.00 seconds... In my settings.py I have this: BROKER_URL = 'redis://localhost:6379' requirements.txt: amqp==2.5.2, asgiref==3.2.3, billiard==3.6.2.0, celery==4.4.0, redis==3.4.1 celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'car_rental.settings') app = Celery('car_rental') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) car_rental/init.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) and the structure of my project is like this: car_rental /car_rental __init__.py celery.py setting.py What I didn't understand is that I am using in the broker_url = 'redis://localhost:6379' but in the error I have: Cannot connect to amqp://guest:**@127.0.0.1:5672// -
I want to return a search result based on current user's data in the db django
This is my view.py def searchposts(request): if request.method == 'GET': query= request.GET.get('q') submitbutton= request.GET.get('submit') if query is not None: lookups= Q(suspect_name__icontains=query) | Q(complaint_name__icontains=query) results= CreateRecord.objects.filter(lookups).distinct() context={'results': results, 'submitbutton': submitbutton} return render(request, 'search.html', context) else: return render(request, 'search.html') else: return render(request, 'search.html') tho the search is working but it return a queryset that matches the query irrespective of the user. i want it to return on queryset that matches the current logged in user data in db. -
Replacing <select> in Django form with custom logic
I have a client who has an existing Django form template rendered from a view that simply extends UpdateView. In the existing template, {{ form.as_p }} is used to render out a fairly generic form i.e. input elements and a select element and an input type="submit". The select element is what is rendered for the model's ManyToManyField to allow multiple value selection. The client wants an 'Ajax-style' input autocomplete instead of the select element, however there is no API at all. The architecture is simply form rendering and then form POSTs. I've replaced the {{ form.as_p }} with a {{ form.xxx }} to render each of the input elements. And instead of the select element, I have written some custom Javascript and layout to manage all the autocomplete functionality. That code maintains an Array of the user selected values from all the possibilities. But I'm unsure how to proceed with using Javascript to get the form to submit with the correct payload. If this was an ajax-style submit, I'd serialize() the form and then add my custom values and then submit a POST to the API with the serialized payload. I could add a hidden select and then modify that … -
Perfoming search filter on my APIView in django
I am trying to implement a search on multiple fields in my Django api, but I don't want to use generics or LISTApi to do that. Please, how can I accomplish that? I imported Django filter also to try to accomplish that but it didn't work. Below is how my code is set up models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) views.py class ListUsersView(APIView, MyPaginationMixin): ''' Gets all the users in the database ''' queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] pagination_class = api_settings.DEFAULT_PAGINATION_CLASS filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('email', 'name', 'profiles__skills') search_fields = ['email', 'name', 'profiles__skills'] def get(self, request): page = self.paginate_queryset(self.queryset) if page is not None: serializer_context = {"request": request} serializer = self.serializer_class(page, context=serializer_context, many=True) return self.get_paginated_response(serializer.data) settings.py INSTALLED_APPS = [ ... 'django_filters', ... ] 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], urls.py path('users/', qv.ListUsersView.as_view(), name='list-users'),