Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use Django channels to open a Websocket for Django Rest Api?
https://github.com/prateekamana/tempstack So I have a simple app where I want to fetch articles in my react fronted without having to refresh the page dynamically. I know for that I either have to implement websockets or sse connection. So I tried to implement that using Django channels but I can't figure out how to set it up. I installed channels but everywhere the examples are for a chat application, I just want to simply fetch articles with the websocket from my rest api. Could you please tell me how do I route the websockets without the AuthMiddlewareStack() ? (Because I gather that has to do something with user authentication which I don't want to deal with as it is not a chat app.) # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ url(r"^chat/admin/$", AdminChatConsumer), url(r"^chat/$", PublicChatConsumer), ]) ), # Using the third-party project frequensgi, which provides an APRS protocol "aprs": APRSNewsConsumer, })``` -
How to get group name of a user from request object inside template in Django3.0?
I have two groups - admin and customer. For navbar, I want to hide some navigation links from users belonging to customer group. For this, I am using following code:- Navbar.html {% load static %} <style> .hello-msg{ font-size:18px; color:#fff; margin-right:20px; } </style> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> {% if request.user.groups.first() == 'admin' %} <li class="nav-item active"> <a class="nav-link" href="{% url 'home' %}">Dashboard</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'products' %}">Products</a> </li> {% endif %} </ul> </div> <span class="hello-msg">Hello, {{request.user}}</span> <span><a class="hello-msg" href="{% url 'logout' %}">Logout</a></span> </nav> However, with this I am getting following error:- Traceback (most recent call last): File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/template/smartif.py", line 175, in translate_token op = OPERATORS[token] KeyError: 'request.user.groups.first()' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vineet/projects/env-cosgrid/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/vineet/projects/Multi-tenant/other/accounts/decorators.py", line 39, in wrapper_function return view_func(request, *args, **kwargs) File "/home/vineet/projects/Multi-tenant/other/accounts/views.py", line 36, … -
Django and Amazon S3
Hi everybody I'm trying to deploy my website and I'm using AWS S3 to store the images that a user upload. Anyway when I run my website the images don't show up and if I use the inspector I keep having a 404 error. I don't know what I'm doing wrong. Hope someone can help me, thanks! And if I open the image in another tab I get this: This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>6F8B0E05F6191EDA</RequestId> <HostId> kwKWtzyw9qjLigGQY/QLLBQjfpVmGDKwlt1fUd4Q1pA+LnZ12prqUri7q1MGpc8oAihXFZU08TA= </HostId> </Error> The bucket region is UE (London) eu-west-2 This is the CORS configuration I used: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> -
Django - Can´t show images | Problem with static folder setting
I have created a Static folder with img folder. It has a image: dog.jpg euskaraz>euskaraz>static>img>dog.jpg HTML template: {% load static %} <!doctype html> <html lang="en"> <head> </head> <body> <img src="{% static 'img/dog.jpg' %}"> </body> </html> settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Where is the problem? Thanks! -
How can i order my votes by vote count? Django
so i made it that my books will show in my admin but i dont know how to order the books(in the admin) by votes and not by last voted. I found some answers here on overflow but i wasnt able to integrate them by myself. Here are my files: admin.py from django.contrib import admin from .models import Vote admin.site.register(Vote) apps.py from django.apps import AppConfig class SurveyConfig(AppConfig): name = 'survey' forms.py from django import forms from .models import Vote class VotingForm(forms.Form): chosen_books_options = forms.MultipleChoiceField(choices=[], label='Book Name', required=False, widget=forms.SelectMultiple( attrs={ 'class': 'form-control' } )) other_book_name = forms.CharField(label='Other', max_length=100, required=False, widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Did we miss something?' } )) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) unique_books_names = Vote.objects.order_by('book_name').values_list('book_name', flat=True).distinct() self.fields['chosen_books_options'].choices = [(book_name, book_name) for book_name in unique_books_names] models.py from django.db import models, transaction class Vote(models.Model): book_name = models.CharField(max_length=200) count = models.IntegerField(default=0) def __str__(self): return '%s: %d votes' % (self.book_name, self.count) @classmethod def bulk_vote(cls, book_names): with transaction.atomic(): for book_name in book_names: if len(book_name) == 0: continue if Vote.objects.filter(book_name=book_name).exists(): Vote.objects.filter(book_name=book_name).update(count=models.F('count') + 1) else: Vote.objects.create(book_name=book_name, count=1) views.py from django.shortcuts import render from .forms import VotingForm from .models import Vote def index(request): if request.method == 'POST': form = VotingForm(request.POST) if form.is_valid(): chosen_books_options = form.cleaned_data.get('chosen_books_options', … -
Django massmailer - TemplateDoesNotExist
I am trying to setup up the django massmailer app for use in my project. However, several templates seem to be missing. For instance, from the admin page, some (but not all) models give an error when I click on them. Any suggestions on how to fix or debug the issue would be much appreciated. Not sure if this an issue with the app or my setup. -
CRUD operation within multi step form
I am not sure what is the exact name of what I am about to describe. Nevertheless, I am trying to replicate something like below picture. Where a client is able to add, delete and adjust as many users as he wants while seeing overview in the table below. I thought the best way to go about is to create a view of a form that is called when you 'Add new user'. Thereafter, you would have a view with the table below where you just loop through users to show information you want (User, Amount, Edit...). My question is how to go about it when I want to keep these created users separate from each client. In another words, if you and I both create users on the app, I do not want to show you users I created and vice versa. Is storing this in session a viable way or are there any better and more efficient approaches?enter image description here -
What is the best model to mysql - django - android?
I'm do my personal project. The project is 1. sign up at android. 2. android send sign up information to mysql 3. when sign in at android, request information. 4. server receive login request, server get login data from mysql 5. when server get login data, server compare login data 5-1. if login data and request information right, send correct 5-2. if login data and request information wrong, send wrong i designed model like this mysql - django - android but i don't have any idea how to code this this is my practice code. model.py from django.db import models class FidoAccount(models.Model): Name = models.CharField(max_length=10) CrewId = models.CharField(max_length=100) Company = models.CharField(max_length=10) Code = models.CharField(max_length=100) def __str__(self): return self.Name views.py from django.views import View from django.http import HttpResponse, JsonResponse from .models import FidoAccount from django.core.serializers import serialize from django.shortcuts import render import json class SavetoDB(View): def get(self, request): # 값을 받아온다(db에서) faccount = FidoAccount.objects.all().order_by('-id') #object가 쿼리셋 data = json.loads(serialize('json', faccount)) return JsonResponse({'Information': data}) def post(self, request): if request.META['CONTENT_TYPE'] == "application/json": request = json.loads(request.body) faccount = FidoAccount(Name = request['Name'], CrewId = request['CrewId'], Company = request['Company'], Code = request['Code']) else: faccount = FidoAccount(Name=request.POST['Name'], CrewId=request.POST['CrewId'], Company=request.POST['Company'], Code=request.POST['Code']) faccount.save() # db에 저장. return HttpResponse(status=200) class … -
int() argument must be a string, a bytes-like object or a number, not 'object'
after I save the data, i just want to select V_insert_data and get its id. How do i solve this problem? any ideas? V_insert_data = StudentsEnrollmentRecord( ..... ) V_insert_data.save() enrollment = StudentsEnrollmentRecord.objects.filter(id = V_insert_data) return render("",{"enrollment":enrollment}) and i get this error -
Django notify user about an event and require a response
I am developing a food ordering web app with Django. When a user submits an order, i want the restaurant to be notified about this order and either accept it or reject it. In both cases, i need to notify the user if his order was accepted or not. I've come across django notifications and django channels but i don't know which one i should choose. Any help would be appreciated. Thank you! -
getting error : Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused) in django
I have uploaded my site to aws, created mysql database, i checked the connection which is working, put the same connection under settings.py, but i am still getting error Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused), can anyone please help me how to resolve this issue ? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '****', 'HOST': '*****.rds.amazonaws.com', 'USER': 'admin', 'PASSWORD': '*****' } } error : (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") Request Method: GET Request URL: http://ec2-54-157-178-122.compute-1.amazonaws.com/ Django Version: 3.0.6 Exception Type: OperationalError Exception Value: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") Exception Location: /home/ubuntu/env/lib/python3.6/site-packages/pymysql/connections.py in connect, line 630 Python Executable: /home/ubuntu/env/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/django-bhuriyo', '/home/ubuntu/env/bin', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/env/lib/python3.6/site-packages'] Server time: Sun, 24 May 2020 13:30:46 +0000 -
How to define a case insensitive Foreign Key relation in Django Models.py?
My models.py looks like this: class UserRoles(models.Model): userId=models.TextField(db_column='user_id',primary_key=True) loginId=models.TextField(db_column='login_id', unique=True) userRole=models.TextField(db_column='user_role') class Assets(models.Model): user = models.ForeignKey(UserRoles,db_column='User',to_field='loginId',on_delete=models.PROTECT) In my views.py, whenever I make an Object: object = Assets.objects.all(); The join between Assets and UserRoles is made automatically on the Foreign Key value. However, the field 'user' is in uppercase and 'loginId' is in lowercase. Thus, only the rows with numeric values in loginId are fetched. How can I change the relation between the Foreign Key to be case-insensitive? Something along the lines of select * from Assets inner join UserRoles on lower(Assets.user) = UserRoles.loginId; Note that I cannot make changes in the actual database itself (which is in Postgres if relevant). -
Django: assertEquals with visually equal result with QuerySet
Can anybody explain me why these have the same values, but don't compare equal? Having a bit of a hard time to understand that. And what would be the best way to make them be "equal"? Inspection using ipdb: ipdb> expected_value {'author': 'john', 'id': 1, 'title': 'Yesterday', 'body': 'All my troubles seemed so far away', 'tags': <QuerySet ['Music', 'Lyrics']>} ipdb> response {'author': 'john', 'id': 1, 'title': 'Yesterday', 'body': 'All my troubles seemed so far away', 'tags': <QuerySet ['Music', 'Lyrics']>} Pieces of code: class TestPost(TestCase): def test_serialize(self): user = User.objects.create(username="john", password="12345678", email="john@exemplo.com") tag1 = Tag.objects.create(value="Music") tag2 = Tag.objects.create(value="Lyrics") post = Post.objects.create(author=user, title="Yesterday", body="All my troubles seemed so far away") post.tags.add(tag1) post.tags.add(tag2) expected_value = { "author": user.username, "id": user.id, "title": post.title, "body": post.body, "tags": post.tags.all().values_list("value", flat=True), } response = post.serialize() self.assertEqual(expected_value, response) and the Django model that I was testing class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False,) title = models.CharField(blank=False, null=False, validators=[MinLengthValidator(3)], max_length=50) body = models.CharField(blank=False, null=False, validators=[MinLengthValidator(5)], max_length=1000) tags = models.ManyToManyField("Tag") def serialize(self): return { "author": self.author.username, "id": self.id, "title": self.title, "body": self.body, "tags": self.tags.all().values_list("value", flat=True), } -
Django admin.py ValueError when trying to save manytomany field
I am trying to create a model with a manytomany field in Django, and using the default admin.py interface I am getting a ValueError: needs to have a value for field "id" before this many-to-many relationship can be used. I understand that you need to save the instance before a many-to-many field can be populated because it is a separate table, however I am not manually saving but instead relying on admin.py. I have a separate model in my app that has a many-to-many field that saves normally in admin.py so I am unsure where the problem is My models code is: class CaseFeature(models.Model): """Case-specific history features""" case = models.ForeignKey( Case, on_delete=models.CASCADE, related_name="features", db_index=True) feature_name = models.ForeignKey( CoreFeature, on_delete=models.PROTECT, db_index=True) response = models.TextField("Patient Response", max_length=500) clerking_text = models.TextField(max_length=400) tooltip = models.CharField(max_length=200, blank=True) important = models.BooleanField() answered_clarifying_qs = models.ManyToManyField(CoreClarifying, blank=True) def clean(self): # Make sure answered_clarifying are valid for this symptom if self.answered_clarifying_qs not in self.feature_name.clarifying_qs: raise ValidationError(_('Answered clarifying Qs do not match this symptom')) def __str__(self): return f"{self.case} - {self.feature_name}" My admin.py is: (nothing changes when I comment this out I still get a value error) class CaseFeatureAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': forms.Textarea(attrs={'rows':5})} } ... admin.site.register(CaseFeature, CaseFeatureAdmin) -
JQuery overriding update value on one slider when another is added and uniquely defined
I am really new to using JQuery and Javascript in general (experimental economist trying to keep up with the times) and I am trying to put 10 sliders on an HTML page that will each record and visually show an updated value for each slider within some text. For the sake of simplicity, let us say there are only 2 sliders then I have the code below: HTML: {% extends "global/Page.html" %} {% load otree static %} {% block title %} Belief Task {% endblock %} {% block styles %} <link href="{% static "vickrey_auction/jquery-ui/jquery-ui.min.css" %}" rel="stylesheet"> <style type="text/css"> .rank-slider { margin: 1.5em auto; width: 70%; } .rank { text-align: center; } </style> {% endblock %} {% block content %} <p> Below is your task to report your beliefs that you will occupy each rank within your group. In order to make in absolutely clear what you are reporting to us, there is a corresponding statement below each slider saying what your choosing means given the instructions. </p> <div class="form-group required"> <label class="control-label" for = "id_a_rank1"> Please submit a probability for each rank (from 0% to 100%):</label> <div class="controls"> <input type="hidden" name="a_rank1" id="id_a_rank1" value="0"> <div class="rank-slider"></div> <div class="rank">You think the probability … -
Annotate count default to 0 (ZERO) in Django
I have the following code in views.py context['postns'] = {d['status__count'] for d in Post.objects.filter(author=user,status="NOT STARTED").order_by('status').values('status').annotate(Count('status'))} when i have post with the legend "NOT STARTED", the code is working and counting the number of post, but if there are no post, is not showing any value. How can i make that code default to "0" if no data is posted? -
Elastic Beanstalk unable to install packages with postgresql
i'd like to deploy my django web server by aws EB. but when i refresh my eb by "eb deploy"it's not working. In error, postresql part set in EB is wrong (in my guess), so I captured that part. 2020/05/24 12:29:49.626792 [ERROR] Error occurred during build: Yum does not have postgresql96-devel available for installation 2020/05/24 12:29:49.626815 [ERROR] An error occurred during execution of command [app-deploy] - [PreBuildEbExtension]. Stop running the command. Error: EbExtension build failed. Please refer to /var/log/cfn-init.log for more details. 2020/05/24 12:29:49.626820 [INFO] Executing cleanup logic i don't know my problem. here is my package.config packages: yum: postgresql96-devel: [] gettext-devel: [] -
django ForeignKey with Choices - setting default value
I have a membership model that has three choices. I set the default of those choices in the membership model. However, I have a User model that has a ForeignKey relationship to the Membership model and when I try to set default='Personal' I get a ValueError. ValueError: Field 'id' expected a number but got 'Personal'. models.py MEMBERSHIP_CHOICES = ( ('Enterprise', 'enterprise'), ('Premium', 'premium'), ('Personal', 'personal'), ) class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Personal', max_length=30) annual_monthly_price = models.DecimalField(max_digits=5, decimal_places=2) monthly_monthly_price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.membership_type class CustomUser(AbstractUser): username = None first_name = models.CharField(max_length=255, unique=False, verbose_name='first name') last_name = models.CharField(max_length=255, unique=False, verbose_name='last name') email = models.EmailField(max_length=255, unique=True) user_team = models.ForeignKey('Team', on_delete=models.SET_NULL, null=True, blank=True, related_name='userteam') team_leader = models.BooleanField(default=False) team_member = models.BooleanField(default=False) user_tasks = models.ManyToManyField('Task', through='UserTasks') # user types membership_type = models.ForeignKey(Membership, on_delete=models.SET_DEFAULT, default='Personal') # Abstract User fields active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) I've tried clearing the migrations and deleting the database. The only way I've gotten this to work is by using: on_delete=models.SET_NULL, null=True inside the membership_type model field of CustomUser but I want the default for the user to be "Personal" when they sign up. -
Multiple databases¶ in Django and how to use them in model.py files
DATABASES = { 'default': { 'NAME': 'user_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_user', 'PASSWORD': 'superS3cret' }, 'customers': { 'NAME': 'customer_data', 'ENGINE': 'django.db.backends.mysql', 'USER': 'mysql_cust', 'PASSWORD': 'veryPriv@ate' } } how to create router.py and where to create. explain.. how to use it. This is link https://docs.djangoproject.com/en/3.0/topics/db/multi-db/ -
Use of Trigram Similarity in Python shell
Context: I was tinkering with Trigram Similarity functionality in Python SHELL but every time I kept on getting the ff traceback: HINT: No function matches the given name and argument types. You might need to add explicit type casts. What I have already done: imported the pg_trgm extension: from django.contrib.postgres.search import TrigramSimilarity, TrigramDistance created extension pg_tgrm in local postgres database and IT WORKED THERE install the Trigram extension using migration Question: Is using trigram similarity in Python shell ever allowed or plausible in the first place? -
how to assign bulk profile to users in django
Am creating a custom command And this command I want to add user profile to all the users who are company So did this companys = Users.objects.filter(is_company=True) Already I have created the users without assigning a profile to each of them Now I I want to use a for loop to loop over each of the users and create a profile for that user But the challenge now is am getting a UNIQUE CONSTRAINTS FAILED I get stuck on the first user class Command(BaseCommand): def add_arguments(self, parser): return super(Command, self).add_arguments(parser) def handle(self, *args, **kwargs): users = User.objects.all().filter(is_company=True) seen = set() for com_users in users: print(com_users) for company_detail in open('filenames/company_name.txt', 'r'): country = generate_countrys() name_email_tagline_address = company_detail.split('-') name = name_email_tagline_address[0] tagline = name_email_tagline_address[1] address = name_email_tagline_address[2] user = com_users department = generate_department() account_type = generate_account_type() date_added = generate_date_added() company_to_save = company.CompanyProfile.objects.create( user=user, name=name, tagline=tagline, account_type=account_type, country=country, joined_date=date_added, address=address, confirmed=True, department=department ) company_to_save.save() seen.add(users) self.stdout.write(self.style.SUCCESS('Jobs Generated Successfully...')) Is there a way to implement this? -
Django authenticate method giving me None if enter even correct username and password
I am trying to login with django authenticate but I am getting None, I have seen many tutorials they are doing in the same way only but it is getting success for them but when I try I am getting None please suggest me your answers and ideas. Registration is working fine for me, it is saving the data, only problem in login. models.py from django.contrib.auth.models import User from django.db import models class extendeduser(models.Model): mobile = models.CharField(max_length=15) user = models.OneToOneField(User,on_delete=models.CASCADE) views.py from django.contrib.auth.models import User from django.shortcuts import render from Home.models import extendeduser from django.contrib.auth import authenticate,login def Login1(request): if request.method == 'GET': return render(request, 'login.html') else: print(request.POST['un'],'**********',request.POST['pwd']) username = request.POST['un'] password = request.POST['pwd'] user = authenticate(username=username,password=password) print(user,'***********') if user is not None: login(request,user) return render(request, 'Dashboard.html') else: return render(request, 'login.html') def index(request): if request.method == 'GET': return render(request,'home.html') else: user = User.objects.create_user(username=request.POST['un'],password=request.POST['pwd']) mob = request.POST['mob1'] euser = extendeduser(mobile=mob,user=user) euser.save() return render(request, 'login.html') login.html <form class="main-css" method="post" action="/home/login/"> {% csrf_token %} <div class="form-group"> <label for="user">Username</label> <input name="un" id="user" class = "form-control"> </div> <div class="form-group"> <label for="pawd">Password</label> <input name="pwd" id="pawd" class="form-control"> </div> <br> <div class="form-group"> <input type="submit" class="btn btn-primary btn-block"> </div> </form> signup.html <form class="main-css" action="/home/" method="post"> {% csrf_token %} <div … -
OSError at /media/<MultiValueDict: {}>
Django: I am trying to Upload Images from a User Form and save it to my Database. but I am getting an error which is OSError at /media/ [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'E:\pritish\myweb\myweb\media\' These are my Code : My Form (HTML) <form action="/python/contact/" method="POST">{% csrf_token %} <h3 class="my-4" style="font-family: 'Acme';">Contact Me :</h3> <div class="form-group my-4"> <label for="exampleFormControlInput1">Name</label> <input type="text" class="form-control" id="exampleFormControlInput1" name='name' placeholder="Enter your name" required> </div> <div class="form-group my-4"> <label for="exampleFormControlInput1">Email address</label> <input type="email" class="form-control" id="exampleFormControlInput1" name='email' placeholder="Enter your email" required> </div> <div class="form-group my-4"> <label for="exampleFormControlInput1">Phone Number</label> <input type="tel" class="form-control" id="exampleFormControlInput1" name='phone' placeholder="Phone Number"> </div> <div class="form-group-sm"> <label for="exampleFormControlTextarea1">Enter your query</label> <textarea class="form-control" id="exampleFormControlTextarea1" name='desc' rows="3" required></textarea> </div> <div class="form-group"> <label for="exampleFormControlFile1">Example file input</label> <input type="file" class="form-control-file" id="exampleFormControlFile1" name="file"> </div> <button type="submit" class="btn btn-primary my-4">Submit</button> </form> At the very last I am taking an Image input models.py class Contact(models.Model): msg_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, default="") email = models.CharField(max_length=100, default="") phone = models.CharField(max_length=30, default="") desc = models.CharField(max_length=10000, default="") image = models.ImageField(upload_to="python/images", default="") def __str__(self): return self.name views.py def contact(request): messages.warning(request, "Hello Aliens") if request.method == 'POST': name = request.POST.get('name', '') email = request.POST.get('email', '') phone = request.POST.get('phone', '') desc = … -
Post data while mapping between two fields in Django
I'm trying to post data as well as map data between two fields in the database. My Model class Category(models.Model): name = models.CharField(max_length=40) class Expense(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") description = models.CharField(max_length=200) total_amount = models.IntegerField() class Expense_Details(models.Model): expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name="payment") user = models.IntegerField() amount = models.FloatField() type = models.CharField(max_length=100) ---->type is owe or lend I'm trying to post data in the database as well as map the amounts between users who lend money from whom so when I try to get money. My post request is in the following form. { “description”: “lunch at the burj al arab”, “category”: 1, “total_amount”: “105”, “owe”: [ { “user_id”: 1, “amount”: 10 }, { “user_id”: 2, “amount”: 95 } ], “lend”: [ { “user_id”: 3, “amount”: 10 }, { “user_id”: 4, “amount”: 95 } ] } I want to map one user with another such that the users with the same amount are people between whom transactions occurred. i.e user_id-> 1 own $10 which was lend by user_id -> 4 and I can query between them and find users settlements. I have made post request but I'm unable to map between users. How can I achieve this? -
Django data to HTML top 10 list
im reffering to this Video. I was wondering how it is possible to display the top 10 most voted books on a HTML website. I dont even know how to really approach that problem, im fairly new. thx for reading