Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Showing user_1 that user_2 is typing
I am building a ChatApp and I am trying to implement a Feature that shows another user that User is typing in chat. User is typing is showing correctly to user who is typing BUT it is not showing in another side of user which is seeing that user_1 is typing. template.html <input type="textbox" id="typer" placeholder="Start typing here..." /> <div id="status"></div> <script> let timer, timeoutVal = 1000; // time it takes to wait for user to stop typing in ms const status = document.getElementById('status'); const typer = document.getElementById('typer'); typer.addEventListener('keypress', handleKeyPress); typer.addEventListener('keyup', handleKeyUp); // when user is pressing down on keys, clear the timeout function handleKeyPress(e) { window.clearTimeout(timer); status.innerHTML = 'Typing...'; } // when the user has stopped pressing on keys, set the timeout // if the user presses on keys before the timeout is reached, then this timeout is canceled function handleKeyUp(e) { window.clearTimeout(timer); // prevent errant multiple timeouts from being generated timer = window.setTimeout(() => { status.innerHTML = 'All done typing! Do stuff like save content to DB, send WebSocket message to server, etc.'; }, timeoutVal); } </script> <style> #typer { padding: 8px; font-size: 1.2em; } #status { padding: 10px; font-size: 1.1em; } </style> I tried by making a … -
Django PhoneNumberField library giving problem when using bootstrap class
I am using PhoneNumberField library. But when I access the field and give bootstrap class, the layout changes. It displays PhoneNumberPrefixWidget in one line and PhoneNumberField in another line. I want them to display next to each other. I tried using for loop but I still couldn't get what I want. forms.py phone_no = PhoneNumberField( widget=PhoneNumberPrefixWidget(attrs={'class': 'form-control'}) ) In settings.py PHONENUMBER_DB_FORMAT = 'NATIONAL' PHONENUMBER_DEFAULT_REGION = 'BT' In my html template {{ form.phone_no }} Is there a way to access this fields separately? By default when I access {{form.phone_no}}, both the fields appear together Thanks in advance -
Chartjs splitting double digit numbers
I have seen this question asked a few times but I couldn't find a solution that worked for me. I am passing a Django variable into Chartjs to plot, all of the single-digit numbers are correct but it turns double-digits into single. Like 11 is 1,1...23 is 2,3. I have tried a bunch of different ways but cant figure it out, I appreciate any help you can offer. var home_runs = '{% for game in all_games.home_ten %}{{ game.runs }}{% endfor %}' var ctx = document.getElementById('runChart').getContext('2d'); var runChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [ { label: home_team, data: home_runs }, { label: away_team, data: away_runs, ], } ] }, options: { responsive: true, }, }); -
Form.cleaned_data form not found in django
I am trying to auto create an agent from user. once a user signed up, it creates and agent successfully but it doesn't inherit it's name, and email from the signup form. I tried using Cleaned data but it says form not found. what should I do? here is my models.py: from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser from django import forms class User(AbstractUser): is_techtanium = models.BooleanField(default=False) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField() organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=4, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True, blank=True) middle_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) agent_type = models.CharField(max_length=20, null=True, blank=True) email = models.EmailField(null=True, blank=True) … -
got image from one model to second models via views and make a copy in pillow and save to new path,how to get new path img and old path img in html
model ''' class generated_certificates(models.Model): certifyuser = models.ForeignKey(User, related_name = "generated_certificates", on_delete=models.SET_NULL,null=True) cerficpic = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) cerficpic2 = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) cerficpic3 = models.ImageField(upload_to = 'pictures/generatedslips', null = True, blank = True) description = models.TextField(null = True) timestamp = models.DateTimeField(auto_now_add = True) def save(self, *args, **kwargs): userdata = self.certifyuser userprofile = profileforsurvay.objects.get(user = userdata) userrating = str(userprofile.total_rating) usertotalviews = str(userprofile.viewcounts) usergrade = str(gradcounter(userdata)) stamp = stampgenerator(usergrade, userrating, usertotalviews) if self.cerficpic: initial_path = self.cerficpic.path imag = self.cerficpic ext = initial_path.split('.')[-1] filename = "%s.%s" % (userdata, ext) new_path=os.path.join(os.path.dirname(initial_path),"generatedslips/",filename) print(new_path) newimg = paststamp(imag, stamp) newimg.name=imag.name newimg.path=new_path newimg.save(newimg.path) super().save(*args, **kwargs) #image saved to newpath but how to get newpath img in html template # if you see template code it show oldpath img my views where i copy images from other model named profileforsurvay# def generate_slip(request): profile = profileforsurvay.objects.get(user = request.user) img = profile.userpics.pic img2 = profile.userpics.pic2 img3 = profile.userpics.pic3 description = profile.description latests = generated_certificates(certifyuser = request.user, cerficpic = img, cerficpic2 = img2, cerficpic3 = img3, description = description) latests.save() return render(request, 'generate_slip.html') my template to show image: {% if i.cerficpic %} <div class="col-6 col-md-4" style="widh:500;height:500"><img src="{{i.cerficpic.url}}" > </div> {% endif … -
How to send the current form tab in a request.POST via JavaScript
I have a form, in the form I have a series of objects, for each object there is a tab. For example: object 1: tab1 object 2: tab2 object 3: tab3 Code example: <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="evidence-form-1-tab" data-toggle="pill" href="#evidence-form-1" role="tab" aria-controls="evidence-form-1" aria-selected="true">1</a> </li> <li class="nav-item"> <a class="nav-link" id="evidence-form-2-tab" data-toggle="pill" href="#evidence-form-2" role="tab" aria-controls="evidence-form-2" aria-selected="false">2</a> </li> </ul> I would like to know the value of the selected tab at the time of submitting the form. function validateRegister() { event.preventDefault(); $('#evidence-formset').attr('action', "{% url 'interpretation' %}").submit(); } Is there a way to inject the value of the current tab and then process it in the (request.POST) in the backend? -
Django Tutorial Error in Tutorial 4 (OperationalError at /polls/1/)
I m new to coding and web development, but I am keen to learn and progress. I have encountered this error during template rendering. Checked issues but cant find any answer can anyone help on this. Not able to understand what is the operational error. Error displayed on screen is as follows OperationalError at /polls/1/ no such column: polls_choice.id Request Method: GET Request URL: http://127.0.0.1:8000/polls/1/ Django Version: 3.2.1 Exception Type: OperationalError Exception Value: no such column: polls_choice.id Exception Location: /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/rishipalsingh/Projects/notes/mysite_dj1/venv/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/rishipalsingh/Projects/notes/mysite_dj1/mysite', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/rishipalsingh/Projects/notes/mysite_dj1/venv/lib/python3.9/site-packages'] Server time: Fri, 07 May 2021 10:20:59 +0530 Error during template rendering In template /Users/rishipalsingh/Projects/notes/mysite_dj1/mysite/polls/templates/polls/detail.html, error at line 10 no such column: polls_choice.id 1 2 <!--Option 3--> 3 4 <h1>{{ question.question_text }}</h1> 5 6 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 7 8 <form action="{% url 'polls:vote' question_id=question.id %}" method="post"> 9 {% csrf_token %} 10 {% for choice in question.choice_set.all %} 11 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> 12 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> 13 {% endfor %} 14 <input type="submit" value="Vote"> 15 </form> 16 17 <!-- 18 {{ question }} 19 20 --> polls/views.py def vote(request, question_id): … -
does image extension matters in django projects (like jpg and png)
am trying to load static and adding image in my project and I get this error "GET http://localhost:8000/static/kpn.jpg 404 (Not Found)" please I need your help -
Only one word is reading from .txt file
I am building a BlogApp and I am implementing a Feature, What i am trying to do :- I am trying to read and work on .txt file BUT when i write one word then it works fine BUT when i write two words then it is not working. views.py def defining(request): with open('wordlists.txt') as in_file: wordlist = in_file.read().splitlines() posts = Post.exclude.exclude(reduce(operator.and_,(Q(description__contains=x) for x in wordlist))) context = {'posts':posts} return render(request, 'defining.html', context) wordlists.txt good bad When i add good word ( only one word ) then it works fine BUT when i add bad after good then both doesn't work. I have no idea, where is the mistake. Any help would be Appreciated. Thank You in Advance. -
How to update my data on the DOM after updating on Django?
My code seems to work and it updates the likes on the backend and also the innerHTML of the like button changes on click. But How can I display the value of likes after clicking on the button? currently, I need to refresh the page. I have tried to add .then after fetching but I did not succeded to understand it completely and how to put it together with my POST method Thanks for any help! index.js function build_post(post){ // create new div for each thing that needs to be shown current_logged_in_user = document.querySelector('#user_detail').value; const element = document.createElement('div'); const post_username = document.createElement('div'); const post_description = document.createElement('div'); const post_date_added = document.createElement('div'); const post_likes = document.createElement('div'); // add the text for each div post_username.innerHTML = 'Username: ' + post.poster; post_description.innerHTML = 'Content: ' + post.description; post_date_added.innerHTML = 'Date: ' + post.date_added; post_likes.innerHTML = 'Likes: ' + post.likes; // append all divs to display-post element.appendChild(post_username); element.appendChild(post_description); element.appendChild(post_date_added); element.appendChild(post_likes); element.classList.add('element'); post_username.addEventListener('click', function() { load_user_info(post.poster); load_user_posts(post.poster); }); const like_button = document.createElement('button'); fetch(`/like/${post.id}`) .then(response => response.json()) .then(data => { result = data.result if(result == true){ like_button.innerHTML += 'Unlike' element.appendChild(like_button); }else{ like_button.innerHTML += 'Like' element.appendChild(like_button); } like_button.addEventListener('click', function() { if(like_button.innerHTML === 'Like'){ like_button.innerHTML = 'Unlike' }else{ like_button.innerHTML … -
Confused between OPTIONS request and GET request
I am totally new to REST and django-restframework and I am lost. In normal Django forms we have a form with the ForiegnKey field populated as dropdpwn. A user can select any option from that list. But I am not able to grasp how it is supposed to work in django-restframwork. I want to expose APIs for frontend developer so that they can know what options they can make available to a user and what options are already selected, if it is an update, for example. Doing some reading on SO and other sites I came across OPTIONS request and metadata. It does expose available choices for a ForeignKey field when I make OPTIONS request in browseable API. But I am confused and unsure whether it is what my frontend developers would expect or I will have to rework on it. This problem is not related code so I am not posting any code. It is general about my understanding and confusion of how I am supposed to expose available choices to frontend developers. What is wrong with using SerializerMethodField to send available choices instead of using of metadata(for OPTIONS request)? Why shouldn't we send the available choices in GET … -
TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User?
Upon attempting to test an AJAX request with an authenticated user, I'm getting the following error: TypeError: Cannot cast AnonymousUser to int. Are you trying to use it in place of User? Upon debugging the view it's saying that an AnonymousUser is being attached to the request. Even though I have created a custom APIClient that logs in a User. I have used the following method as suggested by the docs: https://www.django-rest-framework.org/api-guide/testing/#authenticating Why is an Anonymous User being attached to the request in the case? Here is the scenario I'm attempting: Login a User through a Django login view; User successfully logs in User accesses a login_required protected view to vote on a topic User upvotes/downvotes the topic API call made to validate the request to a DRF view tests.py class TestQuestionDuplicateUpvote(APITestCase): '''Verify that a client is informed that they already voted on a question posted.''' @classmethod def setUpTestData(cls): cls.user = User.objects.create_user('Mock', password="mocksecret") cls.client = APIClient() cls.client.login(username="Mock", password="mocksecret") def test_user_upvote_posted_question(self): response = self.client.put( reverse("questions_api:vote", kwargs={"id": 1}), data = {'vote': 'upvote'} ) new_vote_tally = self.question.votes.count() self.assertEqual(response.status_code, 400) self.assertEqual(new_vote_tally, self.old_vote_tally) self.assertIn(response.data['error'], "You have already voted") views.py class UserQuestionVoteView(APIView): renderer_classes = [JSONRenderer, ] parser_classes = [JSONParser, ] authentication_classes = [SessionAuthentication, ] throttle_classes = … -
Function returning multiple checkbox inputs not being rendered in Django
I have a database call to retrieve some records in my views.py def database(request): if request.method=="POST": #connect to the database #retrieve the results res = cur.fetchall() area_input = forms.DefineArea() tables_input = forms.DefineArea().print_tables(res) cur.close() con.close() dictionary = {'area_input': area_input, 'tables_input': tables_input} return render(request, "main/tables.html", context=dictionary) In my forms.py I have: from django import forms class DefineArea(forms.Form): area_name = forms.CharField(max_length=150) @staticmethod def print_tables(res): tables = [] for row in res: tables.append((row[0], row[0])) tables_input = forms.MultipleChoiceField(choices=tables, required=False, widget=forms.CheckboxSelectMultiple()) return tables_input I know this is working because if I return tables instead of tables_input, I see all the tables printed in the HTML. But when I test it in Postman I see the object reference to location instead: <django.forms.fields.MultipleChoiceField object at 0x000001DCF24FB828> Object not rendered But if I change it like I mentioned: class DefineArea(forms.Form): area_name = forms.CharField(max_length=150) @staticmethod def print_tables(res): tables = [] for row in res: tables.append((row[0], row[0])) tables_input = forms.MultipleChoiceField(choices=tables, required=False, widget=forms.CheckboxSelectMultiple()) return tables tables is just the list of tables I get from the database: All the records from the database being displayed from the list Do I need to do something to render the Django object? -
Django Install requirement
ERROR: Command errored out with exit status 1: 'C:\Users\mostafafci_1146\Desktop\port\cv\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-install-9mgdur4a\pillow_1609587497bb4640864de2290f45836a\setup.py'"'"'; file='"'"'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-install-9mgdur4a\pillow_1609587497bb4640864de2290f45836a\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\mostafafci_1146\AppData\Local\Temp\pip-record-koh1qob_\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\mostafafci_1146\Desktop\port\cv\include\site\python3.8\Pillow' Check the logs for full command output. -
Handling the TypeError: conversion from NoneType to Decimal is not supported
I am trying to get the typed amount from my template to my views in order to calculate the daily exchange rate from a currency to another based on this amount. But it seems that the request.GET.get('amount') method returns None because I am getting a conversion from NoneType to Decimal is not supported error. Bellow is my views: def Add_transfer(request, reference=None): amount = request.GET.get('montant') if request.method=="POST": form = TransferAddFrom(request.POST,request.FILES) if form.is_valid(): form.save() id = form.instance.id return redirect('details', id=id) else: form=TransferAddFrom() # Get conversion rate from USD to USD print(currencies.get_rate('USD','EUR')) # Convert amount from USD to CNY print(currencies.convert('USD','CNY',Decimal(amount))) return render(request, 'indexOld.html',{'form':form}) -
User object to Agent object in django
In my CRM, once the user has signed up it also creates them as agents. My problem is this, in the signup page, the users input their name and details, however once the agent has been created, the agent objects doesn't inherit from the user account. here's my MODEL.PY: from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_techtanium = models.BooleanField(default=False) is_organizer = models.BooleanField(default=False) is_agent = models.BooleanField(default=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Client(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField() organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=4, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, null=True, blank=True) middle_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) agent_type = models.CharField(max_length=20, null=True, blank=True) email = models.EmailField(null=True, blank=True) mobile_number = models.CharField(max_length=12, … -
In Django settings TypeError: 'module' object is not callable
File "D:\Python Development\Django_Broad\blog\blog\settings.py", line 19, in ALLOWED_HOSTS =config('ALLOWED_HOSTS', cast=csv()) TypeError: 'module' object is not callable Why am I getting this error? someone help me.. -
fetch function in javascript looping twice
function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; fetch('/emails/sent') .then(response => response.json()) .then(emails => { // Print emails console.log("Hello, world!"); // ... do something else with emails ... }); } ** corresponding api where fetch request is being made ** @login_required def mailbox(request, mailbox): # Filter emails returned based on mailbox if mailbox == "inbox": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=False ) elif mailbox == "sent": emails = Email.objects.filter( user=request.user, sender=request.user ) elif mailbox == "archive": emails = Email.objects.filter( user=request.user, recipients=request.user, archived=True ) else: return JsonResponse({"error": "Invalid mailbox."}, status=400) # Return emails in reverse chronologial order emails = emails.order_by("-timestamp").all() print(request.user) for email in emails: print(email) return JsonResponse([email.serialize() for email in emails], safe=False) Actually, fetch function loops twice and "Hello, world!" is printed twice in console, so emails when fetched also get displayed twice. Please tell me why fetch request is called twice on backend. Please feel free to ask for more information. -
ModelForm can't see my attributes-fields, form ProfileForm needs update, WHYYYY?
First of all i am new at programming and I was doing django eshop from the tutorials and everything was going well until everything crashed when I tried to make Cabinet in Users: here is My views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import RegisterForm from django.contrib.auth import authenticate , login as django_login , logout as django_logout from .models import Profile from .forms import ProfileForm def cabinet(request): django_user = request.user profile = Profile.objects.get(user=django_user) context = { 'form': ProfileForm(instance=profile) } return render(request, 'users/cabinet/main.html', context) My main.html {% extends 'base.html' %} {% block content %} <h1>Welcome {{ request.user.username }}!</h1> <form action="" method="post"> {% csrf_token %} <div> <label for="">First name</label> <input type="text" name="first_name" value="{{ request.user.first_name }}"> </div> <div> <label for="">Last name</label> <input type="text" name="last_name" value="{{ request.user.last_name }}"> </div> <div> <label for="">Email</label> <input type="email" name="email" value="{{ request.user.email }}"> </div> {{ form }} <button class="btn btn-success">Save</button> </form> {% endblock content %} My models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=13, blank=True, null=True) rate = models.IntegerField(default=4) def __str__(self): return '{} Rate: {}'.format(self.user.username, self.rate) and My forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import … -
Many to one relationship search and serialization in django rest framework
I am kinda new to Django and trying to understand how I can search in different models and create nested serializer. This is the simple model file that I have class Company(models.Model): company_name = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) NIF = models.CharField(max_length=9, null=True, blank=True) class Office(models.Model): company = models.ForeignKey(Company) office_name = models.CharField(max_length=50, default='Main') direction = models.CharField(max_length=50) class Employee(models.Model): office = models.ForeignKey(Office) employee_ name = models.CharField(max_length=50) mail = models.EmailField(null=True, blank=True) here the company has many offices and offices have many employees. So I am creating a search API in which a user can search the company_name or office_name or employee name and get the data in a relational format like this; company: { ------- office: { ------ Employee: { ------ } } } now my problem is filtering the data and serializing it in this format. I tried this Nested Serialization for serialization and also tried filter from here filter in django but not able to come up with the solution. Note: I am creating Django API by using django-rest-framework -
am actually configuring django on command prompt..... installed pip, python and django but whenever i run manage.py it raises an import error?
PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 22, in main() File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate virtual environment? PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 22, in main() File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 13, in main raise ImportError( 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? PS C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller> python .\manage.py migrate Traceback (most recent call last): File "C:\Users\Ileri\Desktop\java basics\reactdjango\music_controller\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of … -
Django - How to display multpile choices for Polls app
Following along the Django polls app tutorial, I was wondering if instead of having a Charfield for the choice Model and manually adding every response/choice to the database; Is it possible to have choices? For example: class Poll(models.Model): text = models.CharField(max_length=255) pub_date = models.DateField() def __str__(self): return self.text class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=255) votes = models.IntegerField(default=0) def __str__(self): return "{} - {}".format(self.question.text[:25], self.choice_text[:25]) You have standard choices for every Poll like this: class Poll(models.Model): text = models.CharField(max_length=255) pub_date = models.DateField() def __str__(self): return self.text class Choice(models.Model): VOTING_CHOICES = ( ('Aye', 'Aye'), ('Nay', 'Nay'), ('Abstain', 'Abstain'), ) question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField( max_length=7, choices=VOTING_CHOICES, default='Aye', )** votes = models.IntegerField(default=0) def __str__(self): return "{} - {}".format(self.question.text[:25], self.choice_text[:25]) Does that make sense? Every time I try to implement this, I either get an empty dictionary response when I POST from the form or the options show up in tuples(or do not render at all). -
problem of join between my django ORM tables
I am trying to join four tables where the three tables carry the primary key of the fourth table and this is my model. class patient(models.Model): choix = ( (0, 0), (1, 1), (0.1, 0.1), (0.15, 0.15), (0.2, 0.2), (0.25, 0.25), (0.3, 0.3), (0.4, 0.4), (0.5, 0.5), (0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9), ) date_creation=models.DateField(auto_now_add=True,null=True) Nom_patient=models.CharField(max_length=200,null=True) date_naissance=models.DateField(max_length=200,null=True) numero_telephone=models.CharField(max_length=30, null=True) adresse=models.CharField(max_length=100, null=True) matricule=models.CharField(max_length=200,default="Pas de matricule",null=True) assurance=models.CharField(max_length=200,default="Non assuré",null=True) compagnie=models.CharField(max_length=200,default="Pas de compagnie",null=True) medecin=models.CharField(max_length=200,null=True) pourcentage = models.FloatField(max_length=20,default='Pas de pourcentage',null=True, choices=choix) def __str__(self): return self.Nom_patient the second lab model class labo(models.Model): examen = ( ("Ac anti- HAV IgM B 70", "Ac anti- HAV IgM B 70"), ("Ac anti- HBc IgM B 70", "Ac anti- HBc IgM B 70"), ("Ac anti- HBe B 70", "Ac anti- HBe B 70"), ("Ac anti- HBs (Test qualitatif ) B 70", "Ac anti- HBs (Test qualitatif ) B 70"), ("Ac anti- HVs (Titrage) B 100", "Ac anti- HVC (Titrage) B 100"), ("Ac anti- HVC (Hépathie C) B 70", "Ac anti- HVC (Hépathie C) B 70"), ("Ag HBe B 70", "Ag HBe 70"), ("Ag HBs B 70", "Ag HBs B 70"), ("Antistreptolysine O ( ASLO) B 35", "Antistreptolysine O (ASLO) B 35"), ("Sérodiagnostic de Widal et Félix B 40", … -
how to Filter and get both tables using django
i'm working on a small project using Django and i would like to know how can i get the fields of the Client table too since i have a foreignkey, how can i filter where shared_with = 1 for example and get both of the tables this is my code : class ContactCenter(models.Model): contact = models.IntegerField(blank=False, null=False) contact_source = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(Client, related_name="contact_y", on_delete=models.CASCADE, null=True, blank=False) how can i get Client fields and ContactCenter both ? -
Django: How to display custom fields for inlines?
How do I display custom fields in my admin interface? Specifically, I have a function that is used to display images, and I would like that to show beside the name. Here is my code. models.py class Photo(models.Model): file = models.ImageField(upload_to='media/images') ... def __str__(self): return f"{self.title}" class Album(models.Model): photos = models.ManyToManyField(Photo,related_name="photos",blank=True,through="Photo") admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from .models import Photo, Album class PhotoInline(SortableInlineAdminMixin, admin.TabularInline): model = Album.photos.through extra = 2 class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") inlines = [PhotoInline] ... admin.site.register(Album, AlbumAdmin) Right now, in my admin interface, I only see the titles of each model.