Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Payment subscription using PayPal and Django is this possible if the user does'nt have account with paypal
I develop an app using Django and i want a user to be able to pay me $5 a months. i found STRIPE but it's not working in my country. I want a user to be able to pay me with credit card or debit card. but is it possible for a user to be able to pay me without opening paypal account, or it is possible for a user to open an account with paypal before he/she can pay me. I get confused. -
How to create one to many generic relation between objects in Django
I have these two models: How do I correctly set the relationship so I can do backward queries? class Client(models.Model): city = models.CharField(max_length=16) worker = models.ForeignKey( "Worker", null=True, default="1", on_delete=models.SET_DEFAULT, related_name="assigned_workers", ) class Meta: abstract = True And: class Worker(models.Model): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) What I want to do is set up the models in a way I can do the following queries: Query the clients assigned to a worker using the worker object. Something like this: Worker.objects.assigned_workers.all() -
Wagtail Tagging: How to keep choosen tag order?
I have a Page Model with Tags in it. class ProjectPage(AbstractContentPage): tags = ClusterTaggableManager(through=PageTag, blank=True) content_panels = AppPage.content_panels + [ FieldPanel('tags'), ... and in the template {% if page.tags.count %} <div class="width2"> {% for tag in page.tags.all %} {# Loop through all the existing tags #} &#9654; <a href="{{ self.get_parent.url }}?tag={{ tag.slug }}">{{ tag }}</a><br /> {% endfor %} </div> {% endif %} If The Editor adds 4 Tags to the Tags Field Panel these Tags should appear in same order in the template. That might work if all tags are newly created in the database but Unfortunately it seems that in the many2many table they get stored always in the order the tags where first created and not in the order they where written in the FieldPanel. -
Static file doesn't exist and html-file doesn't work properly
output: 'static' in the STATICFILES_DIRS setting does not exist. I've tried os.path.join(BASE_DIR, '/static'), but it is doesn't work. I didn't have this problem before adding new html-file and I didn't change static-folder. Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] In static-folder I have placed folder 'main' and css-file. base.html I also have a problem with the file. It doesn't work correctly. Guess I didn't wire it right. <a href="{% url 'make_vision' %}"><li><button class="btn btn-info"><i class="fas fa-plus-circle"></i>Добавить запись</button></li></a> make_vision.html {% extends 'main/base.html' %} {% block title %}Добавление записей{% endblock %} {% block content %} <div class="features"> <h1>Форма по добавлению статьи</h1> <form method="post"> <input type="text" placeholder="Название статьи" class="form-control"><br> <input type="text" placeholder="Анонс статьи" class="form-control"><br> <textarea class="form-control"><br> <input type="date" class="form-control"><br> <button class="btn btn-success" type="submit">Добавить статью</button> </form> </div> {% endblock %} urls.py urlpatterns = [ path('', views.news_home, name='news_home'), path('make_vision', views.make_vision, name="make_vision"), ] views.py def news_home(request): news = Articles.objects.order_by('-data')[:2] return render(request, 'news/news_home.html', {'news': news}) def make_vision(request): return render(request, 'news/make_vision.html') When I started the server, I got an error that this path does not exist. -
IntegrityError - Exception Value with DB relations in Django on form submission
IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to automatically be assigned to the username of the comment model as well as the date_added. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.post.title} - {self.username}" def get_absolute_url(self): return reverse("new-comment", kwargs={"slug": self.post.slug}) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=80) slug = models.SlugField(max_length=250, null=True, blank=True) post_description = models.TextField(max_length=140, null=True, blank=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) main_image = models.ImageField(upload_to="post_pics") is_recipe = models.BooleanField() ingredients = models.TextField(blank=True, null=True) recipe_description = models.TextField(blank=True, null=True) cooking_time = models.CharField(max_length=20, blank=True, null=True) likes = models.ManyToManyField(User, related_name="post_likes") loves = models.ManyToManyField(User, related_name="post_loves") drooling_faces = models.ManyToManyField(User, related_name="post_drooling_faces") favorite_posts = models.ManyToManyField( User, related_name="favorite_posts", default=None, blank=True ) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "body" ] views.py def add_comment(request,slug): if request.method == "POST": form = NewCommentForm(request.POST, request.FILES) if form.is_valid(): form.instance.post_slug = {'slug': slug} … -
Getting indentation issue in Django while trying to pass context [duplicate]
I'm working on a project for a job interview and this is my first experience with django - I'm trying to upload an image to a dropzone and display it on a separate page. I've made the dropzone and the image upload creates a model, but when trying to pass the model into the render of the other page, I get an indentation issue. Here's what my views.py looks like: from django.http import HttpResponse, JsonResponse from django.shortcuts import render from .models import Drop def index(request): return render(request, 'dragAndDrop/index.html') def upload_file(request): if request.method == 'POST': myFile = request.FILES.get('file') Drop.objects.create(image=myFile) return HttpResponse('') return JsonResponse({'post':'false'}) def display(request): drops = Drop.objects.all() context = { 'drops': drops, } return render(request, 'dragAndDrop/display.html', context) This is the error that I'm getting: File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/urls.py", line 2, in <module> from . import views File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/views.py", line 20 return render(request, 'dragAndDrop/display.html', context) ^ TabError: inconsistent use of tabs and spaces in indentation If anyone can offer any assistance, that would be greatly appreciated! -
get first object from every type in Django query
I have a query like this: objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at') is there a way to fetch only the first item of every type and not all the items with these types by adding a condition to this query? -
django name 'form' is not defined
django name 'form' is not defined. i have a problem with loginpage, i want that users will register and login. the register page work but, when i enter a username and password of the register page, i have that problem: "name 'form' is not defined". Attaches photos. Thanks for all the answers. error: error views.py-login: login -
Django URL mapping Error : Using the URLconf defined in proctor.urls(i.e project.urls), Django tried these URL patterns, in this order:
Basically, my project has three apps: 1.logreg (for login/register) 2.usersite 3.adminsite Since, I am a beginner, I am just testing the code for the admission table only which is in usersite app. Admission Table When I try to go to the next page after filling the details of admission table through the form. I am getting an error like this: Using the URLconf defined in proctor.urls, Django tried these URL patterns, in this order: [name='login'] login [name='login'] registration [name='registration'] logout [name='logout'] usersite adminsite admin The current path, submit_admission/, didn’t match any of these. This is the urls.py of my project proctor from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include #from usersite.views import admission,submit_admission urlpatterns = [ path('',include('logreg.urls')), path('usersite',include('usersite.urls')), path('adminsite',include('adminsite.urls')), path('admin', admin.site.urls), #path('submit_admission/', submit_admission, name='submit_admission'), ] This is the urls.py of the usersite app from django.urls import path from.import views from django.contrib.auth import views as auth_views from usersite.views import submit_admission urlpatterns = [ #path('', views.admission, name='admission'), path('', views.admission, name='admission'), path('submit_admission/', submit_admission, name='submit_admission'), path('academicdetails', views.academic, name='academic'), path('achievementdetails', views.achievements, name='achievements'), path('personalinfodetails', views.personalinfo, name='personalinfo'), path('unauth', views.unauthorised, name='unauth'), path('logout', views.logout_view, name='logout'), path('logreg/login/', auth_views.LoginView.as_view()), ] This is the views.py of the usersite app Ignore the code after def submit_admission(request): from django.http import … -
Heroku Django Get Client IP Address
I have a django application running on heroku and I can't get the client's IP address. Every time I make a request on my heroku django app, the IP address keeps showing different. Like 10.x.x.x etc. It is not client public IP. It looks as if the same user is logging in from different IP addresses. I can't get the real client IP addresses. print(self.request.META.get('REMOTE_ADDR')) it is not working.every time this code runs it gives a different IP address. How can I get the client's IP address on view of my django project? -
Django Rest Framework and React File Transfer Project
I'm creating a file transfer project using Django rest framework and React JS. I need some help. models.py class UploadFile(models.Model): file_name = models.CharField(max_length=50) file = models.FileField(upload_to='Uploads/') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file_name serializers.py class UploadFileSerializer(serializers.ModelSerializer): class Meta: model = UploadFile fields = '__all__' views.py class UploadFileViewSet(viewsets.ModelViewSet): queryset = UploadFile.objects.all() serializer_class = UploadFileSerializer there are two questions (1) I want to upload multiple files in that model field. And also zip them. (2) I want to generate a download link for file field. -
Bad request in django when post with flutter
I am trying to do a post request with image and text. I followed a video but the endpoint used with fakeapi is working fine with flutter. My api is working fine with postman but when done with flutter it shows bad request. Help me!! Model.py class TestImageUpload(models.Model): image = models.ImageField(upload_to = "products/",blank=True, null=True) Serializer.py class TestImage(serializers.ModelSerializer): class Meta: model = TestImageUpload fields = "__all__" Views.py class TestImageView(ListCreateAPIView): try: serializer_class = TestImage def perform_create(self, serializer): serializer.save() response_msg = {'error': False} return Response(response_msg) except: response_msg = {'error': True} urls.py path('addimage/', TestImageView.as_view(),name= 'add_image_view'), Flutter Code class UploadImageScreen extends StatefulWidget { static const routeName = '/image-upload'; const UploadImageScreen({Key? key}) : super(key: key); @override State<UploadImageScreen> createState() => _UploadImageScreenState(); } class _UploadImageScreenState extends State<UploadImageScreen> { File? image; final _picker = ImagePicker(); bool showSpinner = false; Future getImage() async { final pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 80); if (pickedFile != null) { image = File(pickedFile.path); setState(() {}); } else { print("no image selected"); } } Future<void> uploadImage() async { setState(() { showSpinner = true; }); var stream = http.ByteStream(image!.openRead()); stream.cast(); var length = await image!.length(); var uri = Uri.parse('http://10.0.2.2:8000/api/addimage/'); var request = http.MultipartRequest('POST', uri); // request.fields['title'] = "Static Tile"; var multiport = http.MultipartFile('image', stream, length); … -
The best setup for Gunicorn + Django or why workers and threads at the same time degrade performance?
On my backend I use Django + Gunicorn. I use Nginx too but that does not matter for this question. Db is Postgres. I want to improve performance of my application (i have some api points with heavy i/o operations that degrade the whole backend), so i decided to survey how gunicorn can help me with that. I have read these SOF answers, and these, and this very nice article and many more but in reality i'm getting rather strange results. I created this point to experiment with Gunicorn config (very simple one): As you can see i have created some i/o operation inside my view. I want to optimize the amount of RPS and to measure that i'm going to use WRK with basic config 2 threads with 10 connections each. Lets start gunicorn with that config (basic simplest sync without any workers): Then i'm getting these results: Ok, that correlates with reality because this api point usually response in 50-100ms. Look: Now lets increase amount of workers to 8: I'm getting: Oops: i supposed that i'll get x8 performance and 160 RPS, because as i thought, new worker works in separate parallel process. 1. So the first question … -
Traefik Django & React setup
Recently I came across server configuration using GitLab CI/CD and docker-compose, I have two separated repositories one for Django and the other for React JS on Gitlab. The Django Repo contains the following production.yml file: version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: one_sell_production_django platform: linux/x86_64 expose: # new - 5000 depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start labels: # new - "traefik.enable=true" - "traefik.http.routers.django.rule=Host(`core.lwe.local`)" postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: one_sell_production_postgres expose: - 5432 volumes: - production_postgres_data:/var/lib/postgresql/data:Z - production_postgres_data_backups:/backups:z env_file: - ./.envs/.production/.postgres traefik: # new image: traefik:v2.2 ports: - 80:80 - 8081:8080 volumes: - "./compose/production/traefik/traefik.dev.toml:/etc/traefik/traefik.toml" - "/var/run/docker.sock:/var/run/docker.sock:ro" redis: image: redis:6 This is work perfectly using the Traefik, I have also the following code for React JS repo: version: '3.8' services: frontend: build: context: ./ dockerfile: Dockerfile expose: - 3000 labels: # new - "traefik.enable=true" - "traefik.http.routers.django.rule=Host(`lwe.local`)" restart: 'always' env_file: - .env Now I don't know how to connect both Django and React Js Repo using the Traefik and also how the CI/CD configuration should be, the following is the CI/CD configuration for Django Repo (I omitted unnecessary info and just include the deploy … -
get_throttling_function_name: could not find match for multiple
Traceback (most recent call last): File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main_.py", line 181, in fmt_streams extract.apply_signature(stream_manifest, self.vid_info, self.js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\extract.py", line 409, in apply_signature cipher = Cipher(js=js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 29, in init self.transform_plan: List[str] = get_transform_plan(js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 198, in get_transform_plan return regex_search(pattern, js, group=1).split(";") File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\helpers.py", line 129, in regex_search raise RegexMatchError(caller="regex_search", pattern=pattern) During handling of the above exception (regex_search: could not find match for $x[0]=function(\w){[a-z=.(")];(.);(?:.+)}), another exception occurred: File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mohd Athar\Desktop\Django\New folder\youtubedownloader\downloadapp\views.py", line 13, in index stream = video.streams.get_highest_resolution() File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main.py", line 296, in streams return StreamQuery(self.fmt_streams) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main_.py", line 188, in fmt_streams extract.apply_signature(stream_manifest, self.vid_info, self.js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\extract.py", line 409, in apply_signature cipher = Cipher(js=js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 29, in init self.transform_plan: List[str] = get_transform_plan(js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 198, in get_transform_plan return regex_search(pattern, js, group=1).split(";") File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\helpers.py", line 129, in regex_search raise RegexMatchError(caller="regex_search", pattern=pattern) Exception Type: RegexMatchError at / Exception Value: regex_search: could not find match for $x[0]=function(\w){[a-z=.(")];(.);(?:.+)} -
Preview of loaded CSV file with many columns
When the user drops the csv file in drag and drop section, He should be able to see a preview of that CSV file, but the problem is the csv file user can have many columns for example:- In the above image u can see due to the CSV file had many(23) columns it is now too long for my web page. Is it possible to contain it in a div tag or adding a scrollbar on the bottom of the table. I tried papaparse too but JS file of papaparse:- function Upload(){ var file = document.getElementById("fileUpload").value; data = Papa.parse(file, { worker: true, step: function(results) { Heiho(results.data); } }); } htmlfile of papaparse:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="heiho.css" /> <title>Document</title> </head> <body> <input type="file" id="fileUpload" /> <input type="button" id="upload" value="Upload" onclick="Upload()" /> <hr /> <div id="dvCSV"> </div> <script src="heiho.js"></script> <script src="https://cdn.jsdelivr.net/gh/mholt/PapaParse@latest/papaparse.min.js"></script> <script src="test.js"></script> </body> </html> Note:- I am not including paparse js and css file as it is too big u can download the file from the link below. What is papaparse? -
Django remember me error didn't return an HttpResponse object
I create forms.py like this. class LoginForm(forms.Form): username = forms.CharField(max_length=100,required=True) password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember me") In views.py I create function loginForm like this. def loginForm(request): if request.method == 'POST': form=LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') remember = form.cleaned_data.get('remember') user=auth.authenticate(username=username,password=password) if user is not None: if remember == "on": request.session.set_expiry(1209600) auth.login(request, user) return redirect('/main') else: message = "User not found" messages.info(request, message) form = LoginForm() return render(request,'login.html',{'form':form}) else: form = LoginForm() return render(request,'login.html',{'form':form}) In login.html I create form like this. <form action="loginForm" method="post"> <h2>Login</h2> <p> <div class="mb-3"> {{form|crispy}} {% csrf_token %} </div> <button type="submit" class="btn btn-primary">OK</button> </p> </form> If I not check Remember me it show this message. It's not remember me button. Please check this box if you want to proceed when I login it show error. ValueError at /loginForm The view device.views.loginForm didn't return an HttpResponse object. It returned None instead. If I remove this line it have no error. if remember == "on": request.session.set_expiry(1209600) How to create login form with remember me? -
Django form login error didn't return an HttpResponse object
I create forms.py like this. class LoginForm(forms.Form): username = forms.CharField(max_length=100,required=True) password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember me") In views.py I create function loginForm like this. def loginForm(request): if request.method == 'POST': form=LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') remember = form.cleaned_data.get('remember') user=auth.authenticate(username=username,password=password) if user is not None: if remember == "on": request.session.set_expiry(1209600) auth.login(request, user) return redirect('/main') else: message = "User not found" messages.info(request, message) form = LoginForm() return render(request,'login.html',{'form':form}) else: form = LoginForm() return render(request,'login.html',{'form':form}) In login.html I create form like this. <form action="loginForm" method="post"> <h2>Login</h2> <p> <div class="mb-3"> {{form|crispy}} {% csrf_token %} </div> <button type="submit" class="btn btn-primary">OK</button> </p> </form> If I not check Remember me it show this message. It's not remember me button. Please check this box if you want to proceed when I login it show error. ValueError at /loginForm The view device.views.loginForm didn't return an HttpResponse object. It returned None instead. How to create login form ? -
I have two tables named as intermediate_transaction and merchant_table. I have to find who is inactive user among all the users
I have to find the inactive users who is not doing any transaction in a week. If a user is doing transaction in 7 days atleast one then he is active user otherwise inactive. -
Is there a way to add Map coordinates in Django just as we add Datefield [duplicate]
I have been working on this project of address book application. I've completed the project and now I have one small task pending. Along with the address details, can I have a field in which someone can add a coordinate field. When we click on those coordinate it should redirect to Maps page(say google maps) where the place represent the coordinates should be displayed. Thank you in advance😊 -
Select radio item in edit view Django Template
I am making an edit view and I would like to have some radio fields selected when fetching the results. My issue is that I can't make my values of the forloop and the values from database comparing correctly. Let me be more clear with some code. I have these lists named mission_entry and gradings. mission_entry has some grades inside it, a vote from 1 to 5 in each value of the list. views.py mission_entry = MissionEntry.objects.filter(log_entry_id=log_entry_id) gradings = range(1,6) models.py GRADING_VALUE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) class MissionEntry(models.Model): student = models.ForeignKey( Student, on_delete=models.DO_NOTHING, blank=True, null=True) mission = models.ForeignKey( Mission, on_delete=models.DO_NOTHING, null=True, blank=True) log_entry = models.ForeignKey( LogEntry, on_delete=models.CASCADE, blank=True, null=True) learning_objective = models.ForeignKey( LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True) grade = models.CharField( max_length=10, choices=GRADING_VALUE, blank=True, null=True) comment = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) template {% for lo in mission_entry %} <tr> <td id='learning_obj'>{{lo.learning_objective.name}}</td> {% for grade in gradings %} <td> <input class="form-check {{grade}}" {% if lo.grade == grade %}selected{% endif %} type="radio" value="{{grade}}" name="grade{{lo.learning_objective.name}}" id="grade" required/> </td> {% endfor %} <td><input type="text" class="form-control" name="note" id='note' value="{{lo.comment}}"></td> </tr> {% endfor %} I know that {% if lo.grade == grade %}selected{% endif %} … -
WebDriverException at / Message: Service /app/.wdm/drivers/chromedriver/linux64/100.0.4896.60/chromedriver unexpectedly exited. Status code was: 127
I am trying to deploy a django website to a heroku app, however , my browser is giving me an error. The error is : WebDriverException at / Message: Service /app/.wdm/drivers/chromedriver/linux64/100.0.4896.60/chromedriver unexpectedly exited. Status code was: 127 Can anyone help me? -
jinja django dictionary, how do I insert this dictionary key from an model id
this is probably more simple than I think it is but I am looking to insert a value from a django html template: {% for cert in list_of_certs %} <td>{{ due.cert.id }}</td> {% endfor %} due is a dictionary: due = {} for cert in list_of_certs: due.update({cert.id: str(cert.exp - datetime.date.today())}) but I cannot figure out how to due this in Jinja (in python it would be due[cert.id]) any help you can provide would be great thanks! -littlejiver -
wrong path doesn't give error anymore in django
Before if I go to a wrong path django gives an error that there is no path by that name but now I can go to any url path even if I didn't specify that path. and I noticed that before I was able to add new templates and everything was fine, now whenever I add a new template it shows an empty page with the navbar and the footer only without the new template. but I'm still able to edit the old templates. urls.py from django.urls import path from . import views urlpatterns = [ path("", views.home, name=""), path('home/',views.home,name='home'), path('privacy/',views.privacy,name='privacy'), path('return/',views.returnP,name='return'), path('search',views.search_book,name='search'), path('contact_us/',views.contact_us,name='contact_us'), path('suggestions/',views.suggestions,name='suggestions'), path('books-list', views.bookslistAjax), path('<str:cats>/',views.CategoryView, name='category'), ] -
Comparing two fields of different models without using foreign key in django
This is regarding CRM software I have two models profile_candidate and Agent, profile_candidate contains some 20 fields and Reference_Mobile is one of them. Agent is the model which contains the names of all the users who work as agents with the field name user. here what I need to do is... I need to compare the field Reference_Mobile of each profile_candidate with all the users available in Agent model, and I need to retrieve the objects of profile_candidate(model) where the Reference_Mobile is not matching with any of the users in the Agent Model. Note: Without using foreign key for Reference_Mobile field from the Agent model, because I cannot display all the users to the candidates while filling the form of profile_candidate. This is the problem I am facing from last two days, I am beginner of Django and python too. I also many other different ways but I could not found the proper output. I hope I explained clearly the problem. Please anyone help me out in achieving this.. my views.py def lead_unassigned(request): team_values = profile_candidate.objects.exclude(Reference_Mobile = Agent.user) return render(request, 'leads/lead_list_unassigned.html', {'team_values':team_values}) Thanking in you Advance, Dinesh Babu