Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does Import Error: Symbol not found: _PQencryptPasswordConn mean and how do I fix it?
I am trying to execute 'flask run' in the Downloads directory where my Flask_App resides. My Flask_App is 'applications.py'. When I execute 'flask run' in the development environment I am getting a URL. Once I paste the URL into Safari, I get this error. ImportError: dlopen(/Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Symbol not found: _PQencryptPasswordConn Referenced from: /Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so Expected in: /usr/lib/libpq.5.6.dylib in /Users/dhruvaiyer/anaconda3/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so I am using a MacOSX High Sierra. My PostgreSQL is version 11. My python is updated to version 3.7. And pip is upgraded and psycopg is on version 2.8.3. I have tried running 'flask run' on various directories and tried moving 'applications.py' into different libraries and directories that I am currently on. I have tried using sudo but I realise that I don't know the password. In the past I force-created another admin account when I accidentally removed admin status on my admin account...don't know if this has affected sudo or not but its not accepting my current admin password. I had an issue with installing psycopg2 as well but resolved that by re-downloading PostgreSQL 11. I have successfully installed SQLAlchemy and Flask-Session as well using pip. This is my code for 'applications.py' import os from flask import Flask, session from … -
Django-taggit how to modify to have same tag added by different user
I am trying to modify django-taggit to allow the same tag to be added by separate users. I have so modified django-taggit Model so that it has user and team_id values added when user adds tag. The goal is to allow different teams to have their own separate sets of tags. Teams may edit or delete their own tags and that should not affect other teams. Question: Where in the django-taggit code does it look for duplicate tag values and then not add them but instead refer to the existing tag? `apps.py` `forms.py` `managers.py` `models.py` `utils.py` `views.py` My modified django-taggit Model code is below. from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import IntegrityError, models, router, transaction from django.utils.text import slugify from django.utils.translation import gettext, gettext_lazy as _ from django.conf import settings from crum import get_current_user try: from unidecode import unidecode except ImportError: def unidecode(tag): return tag class TagBase(models.Model): name = models.CharField(verbose_name=_("Name"), unique=True, max_length=100) slug = models.SlugField(verbose_name=_("Slug"), unique=True, max_length=100) ### MODIFIED: added team and user to model team_id = models.CharField(max_length=10, blank=False, null=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.name def __gt__(self, other): return self.name.lower() > other.name.lower() def __lt__(self, other): return self.name.lower() < other.name.lower() class Meta: abstract … -
How do I store device and receive Auth token from my Django Webapp
I just started developing on xcode and I am currently trying to allow access with a user and password through to my Django Webapp. The django webapp already has an api-auth route. I am trying to find a direction to go. So far I have tried the normal /login/ route that I have with an HTTP POST. (Which I would usually do with just the webapp) I am assuming its not the same with my xcode app. def post(self, request): # TODO: User can get token even though user is not email verified # this should work for traderocket & flow track etc serializer = AuthTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] if request.current_site == user.site: token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) return Response({'token': None}) This is what my route for the auth looks like. This part of the project was not worked on by myself and I am a bit new to xcode. Is it just the normal http request I have been doing? How do I store the token? I tried to find these answers but perhaps I am looking at the wrong terms/concepts. -
How to sort a result of objects shown after a search with keyword in Django
Actually i have a working code but the issue that i am facing is how to sort the result of the queryset based on multiple rule. This is my models.py : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True)` viewed_by = models.ManyToManyField(CustomUser, related_name='viewed_by', blank=True) bookmarked_by = models.ManyToManyField(CustomUser, related_name='bookmarked_by', blank=True) thumbs_up = models.ManyToManyField(CustomUser, related_name='thumbs_up', blank=True) In my views.py i have managed to queryset the database and show all the results based on all matching words, but the missing point here is that i have managed only to sort the result by the number of bookmarks. For i.e : i have this two objects : Object 1 : name = How to use django forms ? Object 2 : name = Using django forms for searching the database. With object 1 is bookmarked by 20 users and Object 2 is bookmarked by 10 users and i type in my search bar : Using django forms database In the result i have the first object as the first answer shown in the list even if the second one have much more matchs with the searched keywords. So what i want to do here is to sort the result … -
How to fix 'The included URLconf 'gp.urls' does not appear to have any patterns in it'
when i tried to write the first urlpattern and the first view, i got this error, so i can be able to access to the authentification template, i have no idea what can be the source of this error # my gp/utls.py from django.contrib import admin from django.conf.urls import url from . import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.index, name='index'), ] # my views.py from django.shortcuts import render def index(request): return render(request,'gp/index.html') when i try to run the server this is the error i get raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'gp.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Plesk Django .py files showing in browser. How do I make it safe?
I create some django websites using Plesk Onyx. My problem is If I go to domainname.com/appname/settings.py or domainname.com/manage.py url i see everything in ".py" file. My folder permissions 755, file permissions is 644. The problem is solved when I set the file permissions to 640 or 600. Is there a shortcut in django related to this vulnerability? or do I need to change individual file permissions? I'm looking for an easy way. I don't know, maybe by adding a little code in django I can prevent these files from appearing. Im using python 3.6 - Django 2.2.3 - Plesk Onyx - Nginx -
Comparing request.path to a string in Django template
I've been messing around with Django for a bit and I ran into this issue, where the comparison in the if labeled below, returns false, when they're both the same string. If request.path is /test/ then "/{{values|lower}}/" is also /test/ yet they're not equal. Why is this the case? <form class="btn-group btn-group-sm btn-group-toggle btn-block" action="" method="POST"> {% for i in name %} {% csrf_token %} {{ form.as_p }} <input {% cycle name.0 name.1 name.2 name.3 name.4 as values %} // HERE {% if press == values or request.path == "/{{values|lower}}/" %} class="btn btn-outline-dark btn-block m-2 active" {% else %} class="btn btn-outline-dark btn-block m-2" {% endif %} type="Submit" name="{{values}}" value="{{values}}"/> // THESE TWO LINES PRINT THE STRINGS ON PAGE {{request.path}} /{{values|lower}}/ {% endfor %} </form> -
Make some elements of choice array readonly in Django?
I have a model: class myLimit(models.Model): limit = models.PositiveSmallIntegerField(help_text="The upper limit of the number of points that can be used.") TYPES_OF_LIMITS = [('perday','Limit Per Day'),('lifetime', 'Lifetime Limit'),('peruser', 'Per User'),] limit_type = models.CharField(choices=TYPES_OF_LIMITS, max_length=20, default='lifetime') ... I want to know how to disable (or make it read-only) the "peruser" ("Per User") choice/option. The current myLimit acts as a base model for an extended model which sets the default of limit_type to "peruser" and makes the entire thing read-only my using admin model's exclude = ('limit_type',). I set the default in the save() method of the extended model just before calling the super method. The main question remains: How to make a few choices read-only? I have read tutorials on making the entire field read-only, hiding it, and others but haven't figured out a way to make "only some choices" read-only. -
Always getting {"detail":"Unsupported media type \"application/json\" in request."} error when I try to post data on postman
I am working on a project that requires me to upload an image. However when I am trying to upload one and posting I ma getting the above error. I have no clue what to do anymore. I have already tried using FileUploadParser and creating class Base64ImageField too. Please Help. models class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) avatar = models.ImageField(upload_to='', blank=True, null=True) code = models.CharField(max_length=8, unique=True, default=unique_rand) emailVerified = models.NullBooleanField(null=True, default=None) facebookId = models.CharField( null=True,unique=True, default=None,max_length=255) googleId = models.CharField(null=True,unique=True,default=None,max_length=255) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') mobile = models.CharField(validators=[phone_regex, MinLengthValidator(10)], max_length=10, null=True, default=None) mobileVerified = models.NullBooleanField(null=True,default=None) status = models.BooleanField(default=False) serializers class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() avatar = Base64ImageField(required=False) code = serializers.CharField(read_only=True) serializers.FileField(use_url=False) class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) image = validated_data.pop('avatar') upr=UserProfile.objects.create(user=user,image=image,**validated_data) return upr views class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer user_serializer = UserSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser) def pre_save(self, request): request.avatar = self.request.FILES.get('file') def post(self, request): print(request.data) serializer= UserProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to display images in a loop
In a loop I iterate over several URLs stored in movie.poster. If I only print movie.poster it returns the URL. <ul> {% for movie in all_movies %} <li> {{ <img src="movie.poster" alt="Cheetah!" /> }} </li> <!--<input type = "submit" value = "delete"/>--> <!-- <img src="movie.poster" alt="Cheetah!" />--> {% endfor %} </ul> When I run the code below I get the following error message "Could not parse the remainder: […]" How could I fix this? -
What is the correct method for implementing <mysite.com/some_user> URL routing in Django?
I want my site members to get access to other user's profile pages via URL mysite.com/some_user instead of mysite.com/profiles/some_user, but with every request to another url path, the view function responsible for the user profile page gets executed. I expect Django to stop looking for any other url path when it finds a matching path, this is my base URL configuration: urlpatterns = [ path('', include('events.urls')), path('<str:username>', view_profile) ] and this is the view responsible for /some_user: def view_profile(request,username): try: member = User.objects.get(username=username) member_events = Feed.my_events(member) return render(request,'profile.html',{'member_events':member_events}) except User.DoesNotExist: print('No data') return HttpResponse('No data') now when I send a request to mysite.com/feedstream , despite the page loads correctly the view_profile() gets executed (judging by the No data print on server console) I could not find any guide online maybe because I don't know the exact keywords for the problem, what am I doing wrong? -
Django TypeError: argument must be int or float when trying to access model
I have a very odd error any time I try to access one of my models. All other models work fine. Here is what my model looks like: class Hop(models.Model): name = models.CharField(max_length=100, null=True, blank=True) aa = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True, default = 10) b = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) type = models.CharField(max_length=100, null=True, blank=True) description = models.CharField(max_length=600, null=True, blank=True) user_created = models.BooleanField(default=True) def __unicode__(self): return self.name When I run Hop.objects.all() I get the following error. Never seen this before. Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 250, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 274, in __iter__ self._fetch_all() File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\query.py", line 72, in __iter__ for row in compiler.results_iter(results): File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\models\sql\compiler.py", line 1044, in apply_converters value = converter(value, expression, connection) File "C:\Users\corym\Documents\Projects\mybrewlab vue\Backend\mybrewlabapi\env3\lib\site-packages\django\db\backends\sqlite3\operations.py", line 285, in converter return create_decimal(value).quantize(quantize_value, context=expression.output_field.context) TypeError: argument must be int or float -
How to make user permissions that expire after 24 hours?
I'm creating a service where I give users who pay for access - access for a timed period, i.e. 24 hours. Once they've made a payment. I auto file data into this premium model: class Premium(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) datetime_payment = model.DateTimeField(default=datetime.now, blank=True) order_id = models.CharField(max_length=250, blank=True) has_premium = models.BooleanField(default=False) class Meta: ordering = ['user'] permissions = (("can_access_premium", "Premium Access"),) def __str__(self): return f'{self.user}({self.has_premium})' So I want the user permissions for premium access to end after 24 hours. How can I change a user permissions. They can buy multiple times, so the trigger for this 24-permission is a payment. -
How to get raw query image url in Django?
I am trying to get the url of image by raw queries results. Tell that how i can get the image url by image name. cursor.execute(f"select p.id,p.name,p.price,p.sale_price,p.img,c.category from product_product p inner join product_category c on p.category_id=c.id order by p.id desc") How i get the absolute url of p.img ? -
char_filter not set propoerly
I am setting up custom char_filter in elastic search django but I am unable to find how to do it properly, I have tried few methods but no success. I have tried two methods but none is working from elasticsearch_dsl import analyzer, tokenizer my_char_filter = { "type": "pattern_replace", "pattern": "&", "replacement": "and" } my_char_filter = {"char_filter": { "type": "mapping", "mappings": [ "&=> and "] }} html_strip = analyzer('html_strip', tokenizer="standard", filter=["standard", "lowercase"], char_filter=["html_strip", "my_char_filter"] ) As I have run the command to rebuild index, It's throwing error Custom Analyzer [html_strip] failed to find char_filter under name [my_char_filter] Expected Output : Index should have created with & replace by and -
Django and Processing raising: "raise AppRegistryNotReady("Apps aren't loaded yet.")"
I wanted to upload some stuff from DB into google sheets. So i figured I will use processing or multy treading. There was few options, so I decided for processing like in this answer I used processing module, inserted it into view and vola, error from title. So i am pretty positive that it has to do something with processing. Without processing everything works fine. #sheet function that is used as proces def sheet(uid,model): gc = gspread.authorize(creds) wks = gc.open("yelp") all_entries = model.objects.filter(uid=uid) worksheet = wks.get_worksheet(0) counter = 0 for entry in all_entries: print('working') if counter < 100: worksheet.append_row([ entry.name, entry.yurl,entry.categories,entry.rating,entry.review_count,entry.phone,entry.surl,entry.address,entry.city,entry.state]) counter = counter + 10 else: time.sleep(100) #view that calls it def upload(request, uid): p = Process(target=sheet, args=(uid, Result)) p.start() print('process started') return render(request, 'YelpGetter/status.html') So I am expecting for the stuff from DB to be imported to google spreadsheets however i get error: [27/Jul/2019 20:23:00] "GET /latest HTTP/1.1" 200 7588 process started [27/Jul/2019 20:23:12] "GET /upload/610482019207 HTTP/1.1" 200 4430 Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\mlade\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\mlade\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "C:\Users\mlade\Desktop\YelpGetter\views.py", line 7, in <module> from YelpGetter.models import Search, … -
Unable to view django error pages on Google Cloud web app
Settings.py DEBUG=True But the django web application shows Server Error 500. I need to see the error pages to debug what is wrong on the production server. The web application works fine in development server offline. The google logs does not show detail errors. Only shows the http code of the request. -
I am trying to add include app urls to the project urls but it doesn't work It shows : issue is probably caused by a circular import
from django.contrib import admin from django.urls import path, include urlpatterns = [path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')),] -
User authentication in django : Logging in using api rather than form
I'm using Django, and am looking to have the option to login both using a web page (the standard way) and through a separate client process (for the sake of my testing, using python requests) I've seen another answer about doing an ajax login, but my understanding of this solution is that it would be vulnerable to a CSRF attack, as it's only taking the POSTed username/password. What I'd like to do is request a CSRF token (with a GET call to my custom /auth-api/login view), and then pass this in a POST call along with the username and password. This is what I currently have in views.py from django.middleware import csrf from django.http import JsonResponse def login( request ) : return JsonResponse( { 'csrf_token': csrf.get_token( request ) } ) From Python on the client end, I'm then doing: (I have verify=False here because I am currently using a self-signed SSL certificate for development purposes) result = s.get( "https://<ip_addr>/auth-api/login", verify=False ) csrf_token = json.loads( result.text )['csrf_token'] s.post( "https://<ip_addr>/auth-api/login", verify=False, data={'csrfmiddlewaretoken': csrf_token, 'username': "<username>", 'password': "<password>" }, cookies=result.cookies ) However, the text of the response to this tells me that the CSRF token is missing or incorrect. Am I missing something … -
failed to load a library: cairo / cairo-2 / cairo-goobject-2 / cairo.so.2 in django saas application djaodjin/djaoapp
I'm trying to run an open-source Django SAAS project called djaodjin/djaoapp locally on my windows machine. After creating a virtual environment and installing all requirements I'm getting the following error, Traceback (most recent call last): File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\template\utils.py", line 65, in __getitem__ return self._engines[alias] KeyError: 'pdf' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 256, in check for pattern in self.url_patterns: File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\site-packages\django\urls\resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\abish\workspace\djaoapp\djaoapp_env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
I make top of Articles ? but when i start my project i had error unhashable type: 'slice'
I make a list of articles that will be filtered by submission, I want regular articles in me, and then the most popular articles go to articles. I do everything vrodiby and I want to display them with I made a function that will filter the articles and then I output them using {% for top in articles_top %} <h1> {{ top.title }} </h1> {% endfor %} And I just need a function and not a class like this class ArticleIndex(ListView): model = Articles queryset = Articles.objects.all().order_by('-view') template_name = 'news/posts.html' paginate_by = 6 my Traceback: File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in get 157. context = self.get_context_data() File "D:\Users\MAestro\Desktop\RapterGame.com\itRapter\news\views.py" in get_context_data 34. context = super(ArticleIndex, self).get_context_data(**kwargs) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in get_context_data 119. paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\list.py" in paginate_queryset 69. page = paginator.page(page_number) File "D:\Users\MAestro\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\paginator.py" in page 75. return self._get_page(self.object_list[bottom:top], number, self) Exception Type: TypeError at /news/ Exception Value: unhashable type: 'slice' views.py class ArticleIndex(ListView): model … -
Preview the photo after selecting the file - Django
I can not find information on this topic. How to easily create a preview of the photo in Django after selecting it (before saving the form). As on the video below: https://youtu.be/HVd2v1aUED0 Is there any simple plugin that will enable this? I think that sending photos in this mode is very popular (that is, a thumbnail of the photo, before saving the whole model). Any help will be appreciated. -
How do I add patient model objects to another model’s ModelForm(IpdForm) template with many to one relationship in Django?
I am trying to create a Hospital Management System in which have Two ModelForms, one ModelForm creates Patient Object, And another form of model two is used to admit that Patient which means it uses Patient Objects in New Form Template with new fields and creates new ID Which have model one id(patient ID) and model two id(IPD ID )as well and model two is linked with model one with Patient Id,one patient can have multiple Ipd id models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); patient_id = models.AutoField(primary_key=True); gender= models.CharField(choices=GENDER, max_length=10) consultant = models.CharField(choices=CONSULTANT, max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient, on_delete=models.CASCADE, blank=False) def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','patient_id','consultant','gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','ipd_id','reason_admission','presenting_complaints', 'rooms','date_of_admission','consultant'] def __init__(self, *args, **kwargs): super(IpdForm, self).__init__(*args, **kwargs) self.fields['patient']=forms.ModelChoiceField(queryset=Patient.objects.all()) views.py: @login_required def new(request): if request.POST: form = PatientForm(request.POST) if form.is_valid(): form.save() return redirect('index.html', messages.success(request, 'Patient is successfully created.', 'alert-success')) else: return HttpResponse(form.errors) else: form = PatientForm() return render(request, 'new.html', {'form':form}) @login_required def ipd(request, patient_id): … -
Django - QuerySet Index Instead of Loop
Home Page In the picture above, I am trying to find a way to have 6 featured posts from my database appear instead of just six static entities in HTML. Here is the view for the home page: from django.shortcuts import render from singlePost.models import Post # Create your views here. def index(request): queryset = Post.objects.filter(featured=True) context = { 'object_list': queryset } return render(request, 'index.html', context) Here is a little bit of code from the home page HTML (looping through object_list): {% if forloop.counter0 == 0 %} <h3 class="mb-15 mb-sm-5 font-sm-13"><b>{{ obj.title }}</b></h3> {% endif %} My question is: how can I get the indices of object_list so I can just use the first 6 featured Posts? I do not know how to do that, so it is currently looping through all posts and I use an if as seen above to check the current index, but that just seems wrong looping 6 times instead of using indices. The loop would be fine if all the divs were the same, but as you see in the picture, they are not. So, how do I get the indices of a QuerySet? Or are there any better ways to do this then … -
Related name not working for django many to many field django
I am trying to access the value of an object that holds the ManyToMany relationship, similar to a related name for a ForeignKey or a OneToOne. How do I need to change my models to allow this? This is my current models.py from django.db import models from django.contrib.auth.models import User class Account(models.Model): account_owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='account_owner') account_name = models.CharField(max_length=50) members = models.ManyToManyField(User, related_name='account_profile') When I try {{ request.user.account_owner.account_name }} I get the expected value of the account name (if they are the owner). But when I try {{ request.user.account_profile.account_name }} I get nothing.