Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find best candidates in efficient way, Django
I'm beginner in django and python. I have models : class Employee(models.Model): full_name = models.CharField(max_length = 64) title = models.CharField(max_length = 64) def __str__(self): return f"{self.full_name} ( {self.title} )" class Skill(models.Model): name = models.CharField(max_length = 64) def __str__(self): return f"{self.name}" class Candidate(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name="employee") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name="skill") def __str__(self): return f"{self.id}: {self.employee} knows - {self.skill}" class Job(models.Model): title = models.CharField(max_length = 64) skills = models.ManyToManyField(Skill, blank=True, related_name="Jobs") def __str__(self): return f"{self.title}" In views.py, i have 'finder' function : def finder(job_id): job = Job.objects.get(id=job_id) # get the specific job relevant_candidates = [] # all the relevant candidates of this kob common = [] # number of common skills between the employee_skill and the relevant_employees_by_title = Employee.objects.filter(title = job.title) # first filter the candidates by the job title job_skills = [] for skill in job.skills.all(): print(skill.id) job_skills.append(skill.id) for employee in relevant_employees_by_title: employee_skills =[] candidateCorrect = Candidate.objects.filter(employee__id = employee.id).values_list('skill', flat=True) for skill in candidateCorrect: employee_skills.append(skill) common_skills = list(set(job_skills) & set(employee_skills)) if (len(common_skills)>0): #if there are common skills relevant_candidates.append(employee) common.append(len(common_skills)) candidates = zip(relevant_candidates,common) candidates = sorted(candidates,key = lambda t: t[1], reverse = True) # sort the candidates by the number of common skiils , descending order candidates = candidates[:50] … -
Django app with offline mode: store datas both in remote and local postgresql database?
I have a problem quite similar with this post but was thinking for an easiest implementation My Django app is deployed on a remote server with Postgresql database (main central remote database). Users online: data are stored both in the remote database and, if possible, in a local postgresql database (local database hosted on a dedicated laptop) Users offline (when server where app is hosted is down): 'central' user need to be able to use Django web app on the dedicated laptop (with PWA) with the most up-to-date local database When back online, the remote database is synchronized Django can use multiple databases. But is my solution possible? I have read for Django sync and collect-offline apps... thanks for advices -
Nested if statment, json, django
My code which is working: def json_response(self, request): ... return JsonResponse({ 'Name': 'Harry' if name.pretty else name.something I want to add nested if statment but i dont know how. It should be something like: 'Name': Harry if name.pretty else name.something(if exists) otherwise name.something_else -
no mail default in form
I am using a form django and I want values that are already defined in my model. But the default value for mail is not showing up in the form. Why? forms.py class ForeningForm(ModelForm): class Meta: model = Forening exclude = ['ordf','kass','adress'] fields=['fname','fphone','mail','homepage','direktansk','anslutenannat',\ 'anteckningar','uppdaterad'] model.py: class Forening(Model): fname=CharField(default='missing',max_length=100) ordf=OneToOneField(Person,on_delete=CASCADE,related_name='ordf') kass=OneToOneField(Person,on_delete=CASCADE,related_name='ka') fphone=PhoneField(default='9999999999') adress=OneToOneField(Adress,on_delete=CASCADE,related_name='ad') mail=EmailField(default='missing@gmail.com') homepage=TextField(max_length=400,default='www.homepage.com') direktansk=BooleanField(default=False) anslutenannat=BooleanField(default=False) anteckningar=TextField(max_length=500,default='missing') uppdaterad=DateTimeField(default=timezone.now) def __str__(self): return 'förening: ' + self.fname class Meta: ordering=('fname','ordf') views.py: class Fcreate(CreateView): form_class=ForeningForm template_name='kammem/create.html' def form_valid(self,form) fname=form.cleaned_data['fname'] venue=form.cleaned_data['venue'] fphone=form.cleaned_data['fphone'] mail=form.cleaned_data['mail'] homepage=form.cleaned_data['homepage'] direktansk=form.cleaned_data['direktansk'] anslutenannat=form.cleaned_data['anslutenannat'] antekningar=form.cleaned_data['antekningar'] uppdaterad=form.cleaned_data['uppdaterad'] -
Halted output from Django until application exit
When i start my Django app I expect it to print me some nice welcomming messages for what host and port I can use to access the website/rest... I do not. I get an output: "My app Stared message from apps.App.ready()" Watching for file changes with StatReloader This is all the text I see until i press CTRL+C Then I see the full log. Using proactor: IocpProactor Performing system checks... System check identified no issues (0 silenced). February 18, 2021 - 13:00:06 Django version 3.1.6, using settings 'project_name.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Using proactor: IocpProactor Why do I not see the logs that was posted hew minutes before the CTRL-BREAK message? Following guides on how to setup your Django project they show that information stright away. -
Django app(with PostgreSQL) monthly price at Google App engine
How much will it cost monthly to deploy simple Django app with PostgreSQL db at Google App Engine? -
Django Request Returns JSON as 'str' instead of 'dict'
I'm working on a Django app that should receive a request from a payment API, instead of the API returning the JSON as 'dict' it returns a string, this makes it hard to use the response as a variable, below is the response and the code. Any help would be appreciated. request.body returns { "Body":{ "stkCallback":{ "MerchantRequestID":"31704-1162534-1", "CheckoutRequestID":"ws_CO_170220211453010899", "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ { "Name":"Amount", "Value":1.00 }, { "Name":"MpesaReceiptNumber", "Value":"" }, { "Name":"TransactionDate", "Value":20210217145321 }, { "Name":"PhoneNumber", "Value": } ] } } } } The view def callback(request): callback = json.dumps(request.body.decode('utf-8')) body_data = json.loads(callback) print(body_data) # returns 'str' instead of 'dict' return render(request, 'callback.html') -
Dialogflow front end and database through django and python
I'm currently trying to integrate my dialogflow agent onto a front end website through django and python, whilst trying to store the chat history into mongoDB/firebase so that at the end of the chat, users will have the option to download the whole chat session. However, all implementations seem to need to use google cloud sql , which needs a billing account. Will it need to be implemented through a webhook? This is a project for university hence my team and I are relatively new and clueless on how to do it for free, any help will be appreciated. -
How to push the notification on web browser using django
I create a Todo web application in Django and i deploy it on Heroku. I want to know how can i push the notification in my browser for upcoming task.Thanks in advance. -
Submit form from Paypal script after approved payment in Django
I have a user registration form and I would like the user to pay in order to register for my app. I have the frontend paypal set up for the payment as well as the user registration with a submit button but I do not know how to integrate the two. <div id="paypal-button-container"></div> <script src="https://www.paypal.com/sdk/js?client-id=sb&currency=USD"></script> <script> // Render the PayPal button into #paypal-button-container paypal.Buttons({ // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '00.01' } }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { // Show a success message to the buyer alert('Transaction completed by ' + details.payer.name.given_name + '!'); }); } }).render('#paypal-button-container'); </script> <button class="w3-button w3-blue w3-padding-large" type="submit"> Buy Now </button> </form> I would like the submit button to be used in the 'onapprove' part of the script but I am not sure how. Alternatively I was thinking of calling my 'buy' function from the views def buy(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): data = form.cleaned_data email = f"{data['email']}" username = f"{data['username']}" form.instance.username = username form.save() return redirect('login') else: form = UserRegisterForm() return render(request, 'users/buy.html', {'form': form}) The other thing is that the … -
Django save many to many relationship on custom many to many model
Trying to set values for a custom many to many model in Django. My User model has a many to many field named as dispatcher_county. I have created a model to handle many to many relationship between user's who are dispatchers and counties named as DispatcherCounty. Check the create method in UserPostSerializer mentioned below to see how I am creating users who are dispatchers and drivers. Error Received: AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' requirements: Django==3.0.8 djangorestframework==3.11.0 mysqlclient==2.0.1 model.py class User(AbstractBaseUser): """ This is a class for user table which overrides functionalities of default django user model. Attributes: name (CharField): Name of a user. email (EmailField): Email address of a user. mobile (CharField): Phone number of a user. date_joined (CharField): When a user was added. last_login (CharField): Last login date time of a user. is_admin (CharField): If user is a admin or not. is_active (CharField): If user is active or not. is_staff (CharField): If user is staff or not. is_superuser (CharField): If user is a superuser or not. role (OneToOneField): One to one relationship with role table. """ name = models.CharField(max_length=80) email = models.EmailField(max_length=255, unique=True) mobile = models.CharField( validators=[ RegexValidator( regex=r"^\d{10,14}$", message="Phone number must be entered in format: '+999999999'. … -
How to empty all contents of a Django table in a management command before filling it with new data
I am quite new to Django so forgive me if this is an easy answer. I'm creating a simple app that will display data that I scrape from the web on a daily basis. This will be pricing data for certain items; so basically on a daily basis, the only thing that would really change would be the price of a given item. Eventually, I will have an app that contains an HTML table in which I will populate an item ID as well as its price using only the data that is scraped for the current day... i.e any item ID in the table should appear only once and have today's price. I want to keep historical data for another app where I will display prices over time. I set up a management command which will run the scraper for me and dump my data into the sqlite database and am also using django-simple-history to store historical data. The way I understand this is working is my scraper dumps my data into both the table that I created (model_data) as well as a historical table (model_historicaldata). What I am hoping my scraper will do on a daily basis is … -
Django DRF incorrect pagination count
I use a custom yet simple pagination class for my django drf application: from rest_framework.pagination import PageNumberPagination class CustomPagination(PageNumberPagination): page_size = 10 page_size_query_param = "page_size" max_page_size = 100 I have also a ViewSet action that does some operation on the inherited queryset and return the result paginated: class MatchOfJobViewSet(ModelViewSet): serializer_class = MatchSerializer filter_backends = (DjangoFilterBackend,) # classic filter inheriting from django_filter.FilterSet filter_class = MatchFilter def get_queryset(self): job_pk = self.kwargs["job_pk"] return Match.objects.filter(job_pk=job_pk) @action( detail=False, methods=["get"], url_path="dynamic", serializer_class=MatchDynamicSerializer ) def dynamic(self, request, *args, other_args, **kwargs): """return the list of matches with a dynamic serializer""" # some operation on the queryset queryset = self.get_queryset().select_related("some_field") # apply the filters queryset = self.filter_queryset(queryset) # paginate page = self.paginate_queryset(queryset) # I use a custom serializer that takes extra arguments # to update dynamically the fields to be serialized serializer = self.get_serializer(page, many=True, other_args=other_args) # unchanged from the generic list response return self.get_paginated_response(serializer.data) The response I get from the view is like this { "count": 308, "next": "https://blabla.com?page=2&page_size=100", "previous": "https://blabla.com?page=4&page_size=100", "results": [...] } The count indicates 308 entries although there are only 297 entries when I check in the database (which causes the last page to end up empty) From what I read the count parameter is … -
hot to get all url of changelist from django
im using django 1.11 and python version 3.6. im building a middleware in django which will check only the changelist page and save the url, req, response data into the table. i have builded the middleware but stuck in a situation where i have to match the current/present url is whether a changlist or not. i got the current url by request.get_full_path() i can list all the urls by ./manage.py show_urls. for example ./manage.py show_urls command shows my changelist url is /admin/shipment/providerpincode/ now how i will match/get the all changelist url with present url in the code. sorry for my bad english -
How we can create generic API in django?
I'm totally new to Django. I'm creating Generic API. List and Create are working well but ID is not visible in DELETE and UPDATE. This is my views.py file from rest_framework import generics from rest_framework import mixins This is my urls.py code from .views import GenericApiView path('inspections-templates', GenericApiView.as_view()), But as I check documents the ID is not available for UPDATE & DELETE. Can you please someone guide me on how can I update and delete the record. Thanks in advance -
Django AdminDateWidget appreaing as TextInput
I don't understand how widgets work. I tried this minimum example : in my forms.py class PartialResetForm(forms.Form): date = forms.DateField( label="Starting date", widget=AdminDateWidget() ) in my admin/intermediary_reset_page.html {% extends "admin/base_site.html" %} <!--Loading necessary css and js --> {{ form.media }} {% block content %} <form action="" method="post">{% csrf_token %} <!-- The code of the form with all input fields will be automatically generated by Django --> {{ form }} <!-- Link the action name in hidden params --> <input type="hidden" name="action" value="custom_action" /> <!-- Submit! Apply! --> <input type="submit" name="apply" value="Submit" /> </form> {% endblock %} in my admin.py as the definition of an action def custom_action(self, request, queryset): form = PartialResetForm() return render(request, "admin/intermediary_reset_page.html", { "items": queryset, "form": form }) For now I don't care about the queryset, it will be my next topic. With this simple example, I wanted to have a calendar in order to help pick a date, but only a TextInput appeared. I believe it is due to the fact that AdminDateWidget inheritates from TextInput. My question is why isn't it appearing as a calendar ? I imported the media and declared my widget, I don't understand what else I'm supposed to do. -
React Native, Django and Google places integration
I have an app I'm building with react native and django... I created a post model which stores location coordinates, now I want a situation where a user tries to create a post, they will use google places to get the address they want. Then it should store the coordinates in the backend. And also in the frontend, it should not display coordinates from the backend but the address as it is from google places. -
How can I lists all the products according to their foreign key?
I am working on my first eshop website using django framework and I got stuck on a problem. I have created a general model for different kinds of products (like laptops, books etc.). Each product that is added to the website can be found by on its foreign key that links that product to a specific category. models.py class ComputerScienceCategory(models.Model): name = models.CharField(max_length=50, blank=True, null=True) description = models.CharField(max_length=300, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" class ComputerScienceProducts(models.Model): name = models.CharField(max_length=50, blank=True, null=True) price = models.FloatField(blank=True, null=True) description = models.TextField(max_length=300, blank=True, null=True) resealed = models.BooleanField(blank=True, null=True) category = models.ForeignKey(to=ComputerScienceCategory, on_delete=models.CASCADE, blank=True, null=True) img = models.ImageField(upload_to='gallery', blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = "Product" verbose_name_plural = "Products" views.py class ComputerScience(ListView): model = ComputerScienceCategory template_name = "computer_science.html" context_object_name = "category" class CompSProd(ListView): model = ComputerScienceProducts template_name = "laptops.html" context_object_name = "products" laptops.html {% extends 'index.html' %} {% block title %} <title>Laptops</title> {% endblock %} {% block cont2 %} <p style="margin-top:100px;">dsfhsdifsdfsdfsd</p> {% for prod in products %} <p style="margin-top:150px;"> {{ prod.name }} <img src="{{ prod.img.url }}" alt="image"> </p> {% endfor%} {% endblock %} The question is how can I … -
Django Admin not allowing to enter data to table
So am using django admin in my project , i already had some columns during development of my project , as time went the column is reduced from 2 to 1 and column name is changed . So i made changes in code but i am not able to write to django admin . inn django admin UI or in django code . it says table not present admin.py from django.contrib import admin from .models import SalesforceTicket, UploadedFiles # Register your models here. admin.site.register(SalesforceTicket) admin.site.register(UploadedFiles) views.py def files(request): num_of_files = 1 filled_multi_file_form = MultipleForm(request.GET) if filled_multi_file_form.is_valid(): num_of_files = filled_multi_file_form.cleaned_data['num_of_files'] FilesFormSet = formset_factory(FilesForm, extra=num_of_files) formset = FilesFormSet() if request.method == 'POST': filled_form = SnippetForm(request.POST, request.FILES) filled_formset = FilesFormSet(request.POST, request.FILES) if filled_form.is_valid() and filled_formset.is_valid(): SalesforceTicket = filled_form.save(commit=False) SalesforceTicket.save() SalesforceNumber = filled_form.cleaned_data['SalesforceNumber'] for form in filled_formset: data = form.save(commit=False) data.SalesforceTicket = SalesforceTicket data.save() file = form.cleaned_data['files_to_upload'] path = form.cleaned_data['path'] server = form.cleaned_data['server'] note = 'File Uploaded Successfully !!' filled_form = SnippetForm() filled_formset = FilesFormSet() else: note = 'Please try again!' return render(request, 'myforms/files.html', {'note': note, 'SnippetForm': filled_form, 'formset': filled_formset}) else: form1 = SnippetForm() filled_formset = FilesFormSet() return render(request, 'myforms/files.html', {'SnippetForm': form1, 'formset': filled_formset}) forms.py from django import forms from .models import SalesforceTicket, UploadedFiles … -
How to Create and Update data in nested serializer using generic ListCreateAPIView and RetrieveUpdateDestroyAPIView?
I am working on genericAPIViews in DRF. I am using a built in user model with UserProfile model having one to one relation with it. But I am unable to create user due to nested serializer. My question is that how I can create and update my built in User model and Profile User model at the same time as UserProfile model is nested in User model.Here is my code: Models.py USER_CHOICE = ( ('SS', 'SS'), ('SP', 'SP') ) LOGIN_TYPE = ( ('Local', 'Local'), ('Facebook', 'Facebook'), ('Google', 'Google') ) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') cell_phone = models.CharField(max_length=15, blank=True, default="", null=True) country = models.CharField(max_length=50, blank=True, default="", null=True) state = models.CharField(max_length=50, blank=True, default="", null=True) profile_image = models.FileField(upload_to='user_images/', default='', blank=True) postal_code = models.CharField(max_length=50, blank=True, default="", null=True) registration_id = models.CharField(max_length=200, null=True, blank=True, default=None) active = models.BooleanField(default=True) # roles = models.ForeignKey(Role, null=True, on_delete=models.CASCADE, related_name='role', blank=True) user_type = models.CharField(max_length=50, choices=USER_CHOICE, null=True, blank=True) login_type = models.CharField(max_length=40, choices=LOGIN_TYPE, default='local') reset_pass = models.BooleanField(default=False) confirmed_email = models.BooleanField(default=False) remember_me = models.BooleanField(default=False) reset_code = models.CharField(max_length=200, null=True, blank=True, default="") reset_code_time = models.DateTimeField(auto_now_add=True, blank=True) longitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) latitude = models.DecimalField(max_digits=80, decimal_places=10, default=0.00) r_code = models.CharField(max_length=15, null=True, blank=True) refer_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="user_refer") referred = models.ManyToManyField(User, related_name="user_referred", null=True, blank=True) … -
How to use the length method in Django ORM Query
In the below class, I need to display the length of name above 25 and country =UK class Emp(models.Model): name=models.CharField(max_length=2000) country=models.CharField(max_length=1000) -
Display specific property between related models in admin panel
I have one model lets call it A. It has N number fields, something like that: class A(models.Model) field1 = models.CharField(max_length=100) field1 = models.CharField(max_length=100) name = models.CharField(max_length=100) I have another model B, which is related to A 1:M class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) field1 = models.CharField(max_length=20) field2 = models.CharField(max_length=20) Here is my admin.py about model B: from django.contrib import admin from project_apps.b_apps.models import B admin.site.register(B) So far so good, but in admin page, when i click on B model it shows me relation to A in that way: A object(1), A object(2) etc. ( for example) That is very confusing. How can i achieve to display A.name1, A.name2 etc. instead of A object(1) -
Error: You don't have permission to access that port
i am using ubuntu server and want to deploy django project in aws using ec2, and it requires me to use port 80 to access its http how do i solve this problem? i heard from other people using sudo and enabling env but this error is all i got ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Please help I really need help -
NoReverseMatch at /wiki/ [duplicate]
What is a NoReverseMatch error, and how do I fix it? Reverse for 'title' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)$'] I'm quite new on programming. I can´t load my index.html due to the above error. Looks like the variable title is empty and I can't understand which kind of pattern is (?P[^/]+)$' Might be a problem with variables or is a url problem? When I hardcode the others urls it works fine (ex wiki/add, wiki/css, wiki/edit, wiki/search) This is views.py def index(request): entries = util.list_entries() return render(request, "encyclopedia/index.html", { 'entries':entries, "form":form, }) This is urls.py from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.get_page, name="title"), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path("wiki/", include("encyclopedia.urls")), ] Any kind of help will be much appreciated, i have not been able to fix it since yesterday. I wals looking a helpful reply "What is a NoReverseMatch error, and how do I fix it?" but i wasn´t able to fix my bug. -
why instance.profile.save() when its not declared
I have some trouble understanding this code and i'll like someone to explain vividly how the signals and receivers work including the parameters declared in the create_profile() function #impor of libraries from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() Why do we need to execute instance.profile.save() here, given that post_save signal is a proof that the user is already saved and a profile associated that user is already created? Please help me understand the below too! Thanks In instance.profile.save() is profile an in-built keyword?