Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Matching Query Doesn't Exists in Django?
I will Perform following this POST request in my views.py file if Medicine.objects.filter(medicine_name=m.medicine_name).exists(): if existing > 0: m.save() Medicine.objects.filter(id=p_key).update(no_of_medicine=existing) return Response({"message": "Successfully Recorded"}) else: return Response({"message": "Not much Medicine Stored"}) else: return Response({"message": "Medicine is not Stored"}) The code is working fine if Medicine Exists . if Medicine not exists give me above Exception . Please anyone can help me -
how can i filter my model to get user answer for a current question
I have two models the Answer model and the Question model. when user post the question i want another user to be able to post an answer in the current question similar to stack overflow, i know using this method: MyModel.objects.all() will returns all the answers from all question to a each question, that's is not what i want. How can i do this in Django please ? my model class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100, blank=False, null=False) body = RichTextField(blank=False, null=False) category = models.CharField(max_length=50, blank=False, null=False) def __str__(self): return str(self.user) class Answer(models.Model): user = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, null=False, blank=False, on_delete=models.CASCADE) def __str__(self): return str(self.user) i want to pass user's Answer into this viewQuestion view my view def viewQuestion(request, pk): question = Question.objects.get(id=pk) context = {'question':question} return render(request, 'viewQuestion.html', context) class My_Answer(LoginRequiredMixin, CreateView): model = Answer fields = ['answer'] template_name = 'answer.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.user = self.request.user return super (My_Answer, self).form_valid(form) -
How can I host Django with celery on cpanel?
I am confused if I can host my django with celery project on cpanel.If yes, How? -
django multiple table query
I have a form for filling out lessons that I want to limit who the students can select as their teacher to only confirmed connections. I have three models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) class Lesson(models.Model): user = models.ForeignKey(User, related_name='fencer', on_delete=models.SET_NULL, null=True, blank=True) teacher = models.ForeignKey(Fencer, related_name='instructor', on_delete=models.SET_NULL, null=True, blank=True) lesson_date = models.DateField(default="1900-01-01") title = models.CharField(max_length=100, null = True, blank=True) description = models.TextField(null=True, blank=True) class Connection(models.Model): student = models.ForeignKey(User, related_name='student', on_delete=models.CASCADE, blank=True) teacher = models.ForeignKey(User, related_name='teacher', on_delete=models.CASCADE, blank=True) student_accepts = models.BooleanField(default=False) teacher_accepts = models.BooleanField(default=False) @property def connected(self): if self.student_accepts == True and self.teacher_accepts == True: return True else: return False My form so far is: class LessonForm(ModelForm): class Meta: model = models.Lesson #fields = () fields = '__all__' def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['teacher'].queryset = Users.objects.filter() # the best I have so far How do I filter the User model based on the link made in the Connection model? Maybe I'm overcomplicating this or is there a better way? Thank you in advance -
Django import export - ManyToManyfield
I have a ManyToMany field in my models. I want to import data and enter into that field. My Resources.py:- class ClinicResource(resources.ModelResource): language = fields.Field(column_name='language',attribute='language', widget=ForeignKeyWidget(Language, 'code')) country = fields.Field(column_name='country',attribute='country', widget=ClinicCountryForeignKeyWidget(model = Country, field ='name')) clinic_languages = fields.Field(widget=ManyToManyWidget(ClinicLanguages, field='name')) class Meta: model = Clinic fields = ('code', 'name', 'city', 'score') exclude = ('id',) import_id_fields = ('code', 'name', 'city', 'score', 'language', 'country') my Models.py:- class Clinic(models.Model): code = models.CharField(max_length= 10, blank= False, null= False) name = models.CharField(max_length= 256, blank= False, null= False) slug = models.SlugField(null= True, blank= True) # country = models.CharField(max_length= 256, blank= False, null= False) city = models.CharField(max_length= 256, blank= False, null= False) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allcliniccountry', blank= True, null=True) score = models.FloatField(blank= False, null= False, default= 2, validators=[MinValueValidator(min), MaxValueValidator(max)]) language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='allclinicslanguage', blank= True) # about = models.TextField(blank= True, null= True) clinic_languages = models.ManyToManyField(ClinicLanguages, related_name='clinic_language', blank= True) about = tinymce_models.HTMLField(blank= True, null= True) created= models.DateTimeField(auto_now=True) status = models.CharField(max_length= 30, choices= SIZE_CHOICES, default= 'pending', blank= False, null= False) NOTE THE clinic_languages field, this is what I want to import -
Install grpcio via pip: "legacy-install-failure"
I want to install grpcio with pip(version 1.35). But I get this error: note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> grpcio I tried to install python-dev or wheel, but it did not work. My python version = 3.10 Ubuntu = 22.04 -
Django does not create foreign key in sqlite table
I use sqlite in a Django project. I created a model called Employee, and then Education, but I forgot to add a foreign key to Employee. When I found the problem, I added the foreign key: class Education(models.Model): employee=models.ForeignKey(Employee, on_delete=models.CASCADE), But when run manage.py makemigrations, it says nothing changed. So I tried to delete the sqlite database file, delete all migrations and tried to create a new database. It still say nothing changed! the sqlite database file is created, with 0 size! What is happening to django? -
Django-How can I upload image to a Model, without that field being present in the ModelForm
I am trying to build an image steganography application and for the encoding part I have a form with two fields, one for image and one for the message that is to be encoded. The encoding part takes place in a views.py, but I do not seem to manage how to upload the encoded image in the ImageModel in order to use it later for the decoding part. 1. If I include image_e in the form as a hidden field, I get an error that it needs to be submitted 2. If somehow the form is being submitted, the model contains only the two fields present in the form, 'image' and 'message', and for 'image_e' i get None or the default if i have that option 3. Right now, if I fill the form I get the defaults for all the fields I actually only need 'image_e' stored, but I thought that if I inherit all of the fields from the model it would be easier. I am a beginner in Django and this is my first more complex application. models.py class Image(models.Model): image = models.ImageField(upload_to='images', default='default.png') message = models.CharField(max_length=200, default=1) image_e= models.ImageField(upload_to='encoded', blank=True) forms.py class EncodeForm(forms.ModelForm): #method= forms.CharField(label='How would … -
Django models - how to assign as ForeignKey
My lab has a models.py as below: class Book(models.Model): isbn = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=100) published_year = models.IntegerField() total_qty = models.IntegerField() current_qty = models.IntegerField() max_duration = models.IntegerField() author = models.ForeignKey(Author, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.PROTECT) def __str__(self): return self.name class BookCopy(models.Model): class Status: AVAILABLE = 1 BORROW =2 LOST = 3 barcode = models.CharField(max_length=30, unique=True) buy_date = models.DateField(null=True, blank=True) status = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.PROTECT) def __str__(self): return self.barcode class User(models.Model): username = models.CharField(max_length=30, unique=True) fullname = models.CharField(max_length=100, null=True) phone = models.CharField(max_length=10, null=True) def __str__(self): return self.fullname class BookBorrow(models.Model): class Status: BORROWING = 1 RETURNED = 2 borrow_date = models.DateField() deadline = models.DateField() return_date = models.DateField(null=True) status = models.IntegerField() book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT) book_name = models.ForeignKey(Book, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT) And i wrote the api for borrow_book function like below: @csrf_exempt def muon_sach(request): body = request.POST username = body.get('username') barcode = body.get('barcode') user = User.objects.filter(username=username).first() bookcopy = BookCopy.objects.filter(barcode = barcode).first() if not user: return HttpResponse(json.dumps({ 'error':"Nguoi dung khong ton tai" })) if not bookcopy: return HttpResponse(json.dumps({ 'error':"ma sach khong ton tai" })) book_borrow = BookBorrow() # resp = [] book_borrow.user = user book_borrow.book_copy = bookcopy book_borrow.borrow_date = datetime.now() book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration) book_borrow.status = BookBorrow.Status.BORROWING book_borrow.book_name … -
How to display a list of search results in Django 4
I'm writing a Django app to manage sales leads. From the template that lists a page of leads, I want to give the user the ability to search all leads using first name and last name as the search criteria. When I type in a last name and press enter, the page flickers but remains on the same page rather than the template I created to list the search results. My views, urls, and templates are below. What have I missed? views.py class LeadsListView(ListView): model = Lead template_name = 'leads/list.html' context_object_name = 'leads_list' paginate_by = 10 def get_queryset(self): return Lead.objects.order_by('id') class LeadsSearchResultsView(ListView): model = Lead context_object_name = 'search_results' template_name = 'leads/search_results.html' paginate_by = 10 def get_queryset(self): query = self.request.GET.get('q') return Lead.objects.filter( Q(last__icontains=query) | Q(first__icontains=query) ) urls.py from django.urls import path from .views import LeadsListView, LeadsDetailView, LeadsCreateView from .views import LeadsSearchResultsView app_name = 'lead' urlpatterns = [ path('', LeadsListView.as_view(), name='list'), path('<int:pk>/', LeadsDetailView.as_view(), name='detail'), path('', LeadsCreateView.as_view(), name='create'), path('', LeadsSearchResultsView.as_view(), name='search_results'), ] The template that (successfully!) lists the leads, list.html: {% extends 'base.html' %} {% block content %} <nav aria-label="Page navigation example"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ page_obj.previous_page_number }}" aria-label="Previous"> <span aria-hidden="true">&laquo;</span> <span class="sr-only">Previous</span> </a> </li> {% … -
How can I print the url to the order id field of my django form?
I am doing a simple form site with Django. This is what my sites url is looks like: mysite.com/register/12345678 I want to print the part after the register (12345678) to the order id field. When someone goes this mysite.com/register/87654321 url then i want to print it. How can i do that? These are my codes.(Currently using Django 1.11.10) forms.py from django import forms from .models import Customer from . import views class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') widgets = { 'order_id': forms.TextInput(attrs={'class':'orderidcls'}), 'full_name': forms.TextInput(attrs={'class':'fullnamecls'}), 'company': forms.TextInput(attrs={'class':'companycls'}), 'email': forms.TextInput(attrs={'class':'emailcls'}), 'phone_number': forms.TextInput(attrs={'class':'pncls'}), 'note': forms.Textarea(attrs={'class':'notecls'}), } views.py from django.shortcuts import render from olvapp.models import Customer from olvapp.forms import CustomerForm from django.views.generic import CreateView,TemplateView def guaform(request,pk): form = CustomerForm() if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) else: print('ERROR FORM INVALID') theurl = request.get_full_path() orderid = theurl[10:] return render(request,'forms.py',{'form':form,'orderid':orderid}) customer_form.html {% extends 'base.html' %} {% block content %} <h1>REGİSTRATİON</h1> <form class="registclass" method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-default">REGISTER</button> </form> {% endblock %} urls.py from django.conf.urls import url from django.contrib import admin from olvapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^thanks/$',views.ThankView.as_view(),name='thank'), url(r'^register/(?P<pk>\d+)',views.guaform,name='custform'), ] -
in Django : Why nothing happens when I try to connect with YouTube API and search the top 10 videos about whatever subject
I've just started my first app with Django by following a video on YouTube. The app is a students dashboard with 8 tools and features to help the student to make note, search for help, save books, etc. When I follow the steps I get stuck in the YouTube search section but not from the admin side but from the actual YouTube template that has a crispy form and a search button. The program is supposed for searching the top 10 videos about anything as a result and show in the same template I created (youtube.html) and some information like title, description, duration, etc. when I try to click the search button nothing happens. #This is the view.py page in the dashboard app : from typing import Generic from django.http import HttpResponseRedirect from django.shortcuts import redirect, render from django.shortcuts import render from . forms import * from django.contrib import messages from django.urls import reverse from django.views import generic from django.views.generic.detail import DetailView from youtubesearchpython import VideosSearch # the youtube function def youtube(request): if request.method == "POST": form = DashboardForm(request.POST) text = request.POST['text'] video = VideosSearch(text,limit=10) result_list = [] for i in video.result()['result']: result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['channel']['name'], … -
Python Django error "Select a valid choice. That choice is not one of the available choices."
I am relatively new to Django so I am likely doing something obviously wrong but I cant seem to figure out what exactly. I have a model called Report and this has a number of fields including a foreign key relationship to my Plot model. In my Report model form I have extra fields that are not part of the model but are used to filter/search for the correct plot. I am using javascript to fetch these values on change of the respective field. First the user selects a developer from a list (this is configured as a ModelChoice field and is populated on initialisation using a query set), this then populates a list of developments owned by the developer, they then select the desired development, this yields all plots that are part of that development, finally they select the desired plot. When the form is submitted I receive "Select a valid choice. 37d86254-29c5-456d-8264-f47e893ae789 is not one of the available choices." for both the development and plot_id fields. My aim is to use the plot_id value (plot pkid) to obtain an instance of the respective plot in the view and store this in the report.plot foreign key relationship as per … -
Django 4: Product.objects.get(id=1) returns an error "DoesNotExist" but I already have 7 products listed
I already have 7 products listed in my DB and I can check them by Product.objects.all() but when I do Product.objects.get(id=1) or pass any id as a parameter it returns me this error: meanwhile, this is what I am doing: [views.py file] here If I use Product.objects.all() it returns me all my 7 products listed in DB but if I use Product.objects.get(id=id) it retuns me the error def update_product(request, id): product=Product.objects.get(id=id) #As far I understood, here the actual problem starts. context = { "product": product } return render(request, "myapp/updateProduct.html", context) [urls.py file] from django.contrib import admin from django.urls import path from . import views app_name = "myapp" urlpatterns = [path('', views.index), path('products/', views.products), path('products/<int:id>', views.product_details, name='product_details'), path('products/add', views.add), path('products/update/<int:id>', views.update_product, name='update_product'), ] [updateProduct.html file] {% extends 'myapp/base.html' %} {% block content %} <main class="box-container"> <div class="title"> <h1>Update Your Product</h1> </div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Name" required> <input type="number" name="price" id="price" placeholder="Price" required> <!-- <input type="text" name="description" id="description" placeholder="Description"> --> <textarea spellcheck="true" name="description" id="description" placeholder="Description" cols="30" rows="10" required></textarea> <input type="file" accept="image/*" name="upload" id="upload" required> <input type="submit" name="Add Product" value="Add Product"> </form> {% endblock %} -
get_object_or_404 and .get(id=pk) is not working when i try to access my model in to some view
i'm trying to access my model using both method but one of them is not working in my view. i want when a user click on {{question.title}} in my home page to be able to see all the content of the post in vewQuestion template. but both method is not working in app. is anybody who can help me please. my urls path('view/<int:pk>/', views.viewQuestion, name='viewQuestion'), the both method my_list = get_object_or_404(Question, id=pk) list_of_question = Question.objects.get(id=pk) the url <a href="{% url 'viewQuestion' question.id %}" style="text-decoration: none;"> the home template <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title">{{question.user}}</p> </div> <div class="card-body"> <a href="{% url 'viewQuestion' question.id %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <p>Category: {{question.category}}</p> </div> </div> </div> {%endfor%} </div> </div> the viewQuestion template <div class="container"> <div class="row justify-content-center"> <h1>{{question.title}}</h1> <hr> </div> <br> <h3 style="font-family: arial;">{{question.body}}</h3> <hr> <br> <h5>{{question.user}}</h5> </div> the views @login_required(login_url='login') def index(request): query = request.GET.get('q', None) list_of_question = Question.objects.all() if query is not None: list_of_question = Question.objects.filter( Q(title__icontains=query) | Q(category__icontains=query) ) context = {'list_of_question':list_of_question} return render(request, 'index.html', context) def viewQuestion(request, pk): my_list = get_object_or_404(Question, id=pk) list_of_question = Question.objects.get(id=pk) answers = Answer.objects.filter(post_id=list_of_question) context = {'list_of_question':list_of_question, 'answers':answers, 'my_list':my_list} return … -
How to assign a database model to a user
from django.db import models from datetime import datetime from django.contrib.auth.models import User class News(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) headline = models.CharField(max_length=100) content = models.CharField(max_length=1000000) time_created = models.DateTimeField(default=datetime.now, blank=True) i kept on trying this method but i keep getting an error" django.db.utils.OperationalError: no such column: blog_news.user_id " -
Django Form processing files
So I have the following code: # the view class UpdateDateView(LoginRequiredMixin, UpdateView): model = Date form_class = DateForm template_name = 'app/form/date_edit_form.html' def save_photos(self, date) -> None: photos = self.request.FILES.getlist('photo') current_photos = self.request.FILES.getlist('custom-photo-name') # this is not working for photo in photos: Photo.objects.create(date=date, photo=photo) def form_valid(self, form): date = form.save() self.save_photos(date) return super().form_valid(form) # the form class DateForm(forms.ModelForm): photo = forms.ImageField(required=False) class Meta: model = Date exclude = ('user',) # the Edit form <form action="{% url 'app:edit-date' date.slug %}" method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-container"> ... <tr> <th><label for="id_photo">Image:</label></th> <td> <input type="file" name="photo" accept="image/*" id="id_photo" multiple> </td> </tr> <div class="current-photos"> {% for photo in date.photos.all %} <div class="photo-wrapper-{{ forloop.counter }}"> <img src="{{ photo.photo.url }}" width="200px"><a class="delete-photo" id="{{ forloop.counter }}">Delete</a> <input type="file" name="custom-photo-name" value="{{ photo }}" class="hide" id="photo_{{ forloop.counter }}"> </div> {% endfor %} </div> </div> <div class="buttons"> <input type="submit" value="Save" class="create-button redirection no_decoration"> <a href="{% url 'app:date_details' date.slug %}" class="redirection no_decoration">Back</a> </div> </form> # js (jquery) $('.delete-photo').on('click', function() { const id = $(this).attr('id'); const div_class = `.photo-wrapper-${id}`; $(div_class).remove() }); I have a CreateView and UpdateView. The ImageField is not required, it is optional. Let's assume I have created a new date with photos. Then I wanted to edit its pictures (delete … -
Add Django Rest Framework Login Button to Browsable API when Using Third Party Auth Library (django-rest-knox)
The login button is missing from my browsable API. I am using django-rest-knox for token authentication. My urls.py contains: urlpatterns = [ path('admin/', admin.site.urls), path(r'', include(router.urls)), path('auth/', include('knox.urls')) ] And to allow for using BasicAuthentication on the login view itself I have this in my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'knox.auth.TokenAuthentication', ) } I had a little dig into DRF code on github and this is the template tag: @register.simple_tag def optional_login(request): """ Include a login snippet if REST framework's login view is in the URLconf. """ try: login_url = reverse('rest_framework:login') except NoReverseMatch: return '' In the browsable API, the login button is only shown when the exception is not thrown. But I don't know how to get that reverseMatch. Can I rename my login URL? Or override the template tag? Or some other way to get me a login button? Thanks. -
How to implement only client to graphql subscriptions in a website with only front code?
I am coding a only front end site using Django. to query data to a DataBase I use AJAX to my Django and Django requests a third party GraphQL. so far all works perfect. But now I need to alert the users on updates to a table. the third party has setup subscriptions. I know is working because I made a view with the play ground, execute the subscription and on updates, the playground shows the update. So how can I implemente those subscriptions to my site so on updates I can do console.log(subscriptionUpdateMsg) ? I have been looking for about 3 days and I have found many docs whith info, but they require node.js or other servers, the problem is that I already have all on Django server as I was required. and some other sites works with but I get error failed: Error during WebSocket handshake: Unexpected response code: 500 This is what the code creates, and is working: screenshot here Here is the working code with the playgroun in my site: <html> <head> <style> html, body { height: 100%; margin: 0; overflow: hidden; width: 100%; } </style> <link href="//cdn.jsdelivr.net/npm/graphiql@0.11.11/graphiql.css" rel="stylesheet" /> <script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script> <script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script> <script src="//cdn.jsdelivr.net/npm/graphiql@0.11.11/graphiql.min.js"></script> … -
Fixing django inspectdb after importing postgresql sample database
Context: I'm playing around with setting up a DRF project using the postgresql sample database located here: Postresql Sample DB Problem: The sample database is already set up with intermediate tables film_category and film_actor. When using manage.py to inspectdb it generates these intermediate tables explicitly (FilmCategory and FilmActor) and they serve no purpose in the code as they only contain the ids for the two related fields. If I were to create them using the Django ORM I could just declare: class Film(models.Model): ... actors = models.ManyToManyField(Actor, related_name='films') Django creates these tables "behind the curtain" so they take up no space in my code. I attempted to just set up a ManyToManyField like so: actors = models.ManyToManyField(Actor, db_table='film_actor', related_name='films') categories = models.ManyToManyField(Category, db_table='film_category', related_name='films') When attempting to migrate, however, this fails giving me the following error: psycopg2.errors.DuplicateTable: relation "film_actor" already exists I don't think I want to create this ManyToManyField without explicitly telling it which db_table to use because I believe that would generate an entirely new intermediate table and I lose access to all the data already stored in those intermediate tables in the original sample database. I was able to get it to work without errors and the … -
Post field not returned by __str__
My question is similar to Display field other than __str__ but slightly different. The example in the link seems to only change the options in the dropdown, and not what gets posted when you select them. I am trying to make a dropdown that populates with a users first and last name. The issue I am having is that my People model that I am querying has a __str method that returns a users badgenumber, not their first and last name. The code posted below works to populate the dropdown options with the users names. When you select one from the list it even fills the field in with the correct info. But when you submit the post it is still posting the badgenumber associated with the first/last name you pick, not their first and last name. How do I get it to post something not returned by the __str method? forms.py class InitiatorSelect(forms.ModelChoiceField): def label_from_instance(self, person): return person.fullname initiator_name = InitiatorSelect( label="Initiator", queryset=baws.models.People.objects.filter(distributor=True), required=True, widget=local_fields.ListTextWidget(attrs={ "force": "true", "dvalue": "true", "autocomplete": "off", "class": "form-control" }), -
makemigrations - No changes detected -Django
I am new to Django, and im trying to create a company profile for user to fill up. when i make migrations, i got the following error which is no changes detect. heres the model.py class Company(models.Model): name = models.CharField(max_length=100) about = models.TextField(gettext_lazy('about'), max_length=500, blank=True) role = models.CharField(max_length=100) address=models.CharField(max_length=100) contact=models.CharField(max_length=100) def __str__(self): return f'{self.user.username} Profile' I didnt create anything in other .py file only model and i have another class which is profile in the same model.py as company. Do correct or lmk if i make any mistake, thanks! -
Django form not correctly updated
I've made a Django site with dinamically generated forms. The site is based on Leaflet.js as frontend, a JS library for web mapping. I cloned the form from the HTML in the JS script, to bind the form as a pop-up of every geographical feature. My idea is to update this popups/forms, as the user were updating data in the field, for example inputting data about a feature ("This house is abandoned", "This tree is very big", just stupid examples). The problem is that the AJAX query is not sending the correct data, but the empty form present in the HTML document. How I can refer the updated form to send the data? The POST request is correctly sent, but comes empty, since it's just sending the empty form. My AJAX query: $(document).on('click', '#submitButton', function(e){ e.preventDefault(); $.ajax({ type : "POST", headers: {'X-CSRFToken': csrf_token}, url: "update_note/", data: { id: $('#id_id').val(), note_heading: $('#id_note_heading').val(), note_des: $('#id_note_des').val(), dataType: "json" }, success: function(json){ $('#form_pop').val(''); // remove the value from the input console.log(json); // log the returned json to the console console.log("success"); // another sanity check }, failure: function() { console.log('error') } }); return false }); How I bind the hidden form in the HTML to … -
Django Authentication method is not working
I am trying to use the default Django from django.contrib.auth authenticate() method to authenticate if the user exists. I am doing this right after the user registers. The user registers and their username, email, and password is inputted into the database then they are taken to the login page but it is not working. Here is my views.py from django.shortcuts import render,redirect from .models import Student from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def index(request): if request.method == "POST": fname = request.POST.get('fname') lname = request.POST.get('lname') pnumber = request.POST.get('pnumber') email = request.POST.get('email') password = request.POST.get('password') student = Student(fname = fname, lname = lname, pnumber = pnumber, email = email, password = password) student.save() user = User.objects.create_user(fname, email, password) user.save() return render(request, ('SignUpPage.html')) def loginUser(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) return redirect('mainPage') else: return render(request, ('LoginPage.html')) return render(request, ('LoginPage.html')) def mainPage(request): return render(request, ('MainPage.html')) Here is my urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('login', views.loginUser, name="login"), path('mainPage',views.mainPage, name='mainPage') ] Here is my html code <!DOCTYPE html> … -
Django processing form input name
I have changed the input's name attribute to some custom name, but the view calls form_invalid method. Why my Form isn't saving (validating)? html: <tr> <th><label for="id_photo">Image:</label></th> <td> <input type="file" name="custom_photo_name" accept="image/*" required id="id_photo" multiple> </td> </tr> the line in view: self.request.FILES.getlist('custom_photo_name') Doesn't the self.request.FILES takes the values according to name attribute?