Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to relate a Google OAuth2 authenticated user with a customer in django?
I have a problem registering users with Google, since the users are related to the customer and I don't know how to make that relationship with a registered user through Google OAuth2. I made the relationship of a user with a customer, but without using user authentication by Google. Now I want to do the same relationship, but for a user who signed in via Google OAuth2. Here is my code: signIn.html <form action="{% url 'signIn' %}" method="POST"> {% csrf_token %} <div class="mb-3"> <a href="{% provider_login_url 'google' method = 'oauth2' %}">Sign in with google</a> </div> </form> views.py def signIn(request): if request.method == "POST": form = SignInUserForm(request.POST) if form.is_valid(): formSave = form.save() Customer.objects.create( user = formSave, name = formSave.username, email = formSave.email ) user = form.cleaned_data['username'] key = form.cleaned_data['password1'] credentials = authenticate(username=user, password=key) login(request, credentials) messages.success(request, ("Successful!")) return redirect('store') else: form = SignInUserForm() context = {'form': form} return render(request, 'caliza/signIn.html', context) urls.py urlpatterns = [ path('accounts/', include('allauth.urls')), path('logout', LogoutView.as_view()), ] models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'customer', null = True, blank = True) name = models.CharField(max_length = 80, null = True) email = models.CharField(max_length = 50, null = True) def __str__(self): return self.name settings.py INSTALLED_APPS = … -
why is my search function return an error Related Field got invalid lookup: category
My search function works fine but it throws me an error every time i try to search an existence post in my website. when i deleted ForeignKey in the Question model under category field the error is gone. please how can i filter that category that have a ForeignKey the error: FieldError at /index/ Related Field got invalid lookup: category my models: class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=False) def __str__(self): return str(self.name) 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.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True, max_length=200) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Question, self).save(*args, **kwargs) def __str__(self): return str(self.title) the views: 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__category__icontains=query) ) unread_notifications = Notification.objects.filter(user=request.user, is_read=False).count() paginator = Paginator(list_of_question, per_page=1) return render(request, 'index.html', {'unread_notifications':unread_notifications,'list_of_question':list_of_question, 'paginator':paginator}) my form: <form action="" method="GET"> <input placeholder="Search By Category" type="text" class="form-control" name="q"> </form> -
"Error": "strptime() argument 1 must be str, not None" [closed]
When I tried to check this API using postman, I got the following error ({"Response": "Failure", "Response_status": "Invalid data provided", "Error": "strptime() argument 1 must be str, not None"})....I am new to python So I dont have any idea about this error @api_view(['POST']) def getExerciseDetailByuser(request): permission_classes = (permissions.IsAuthenticated,) if request.method == 'POST': try: value=request.user profileData = tbl_user_profile.objects.get(userid=str(value.userid)) loginData = MyUsers.objects.get(userid_id = profileData.userid) except Exception as e: return HttpResponse(status=403,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'User not found'})) try: if str(loginData.roleid_id) == '3': listData={} try: listLevelData = [] received_json_data=json.loads(request.body) exerciseStr=received_json_data.get('exerciseid') date=received_json_data.get('date') date=datetime.strptime(date, '%d/%m/%Y').strftime('%Y-%m-%d') userweight=tbl_weight_log.objects.filter(date__lte=date,userid_id=value.userid).order_by('-date') if userweight: userweight=userweight[0].weight else: userweight=tbl_weight_log.objects.filter(userid_id=value.userid).order_by('-date') if userweight: userweight = userweight[0].weight -
How to add google OAuth with multiple users in django while creation
I am working in Django and I am making a school management system where I am giving students and teachers to login and register via google OAuth . Here are my models from django.db import models class Student(models.Model): first= models.CharField(max_length = 100 , blank = False , null = False) last = models.CharField(max_length = 100 , blank = False , null = False) user = models.OneToOneField(User , on_delete = models.CASCADE) class_studying = models.ForeignKey("SchoolClass") ... class Teacher(models.Model): first= models.CharField(max_length = 100 , blank = False , null = False) last = models.CharField(max_length = 100 , blank = False , null = False) user = models.OneToOneField(User , on_delete = models.CASCADE) classes_teaching = models.ManyToManyField("SchoolClass") salary = models.DecimalField(max_digits =6 , decimal_places = 2) ... I am using google Oauth with django-allauth package to register , login users via google OAuth . Here I only have the ability to create only one type of user via google OAuth using signals . Either I can create a student , or either I can create a teacher . But I want to create a way so that I can register a teacher as well as a student via the same OAuth . I have tried various ways … -
Checking if user enters the correct account number (Django)
I'm trying to check if a user is entering their correct account number. Would I apply logic in forms, models, or views.py? I was thinking views, because I'll need the request to get the submitting user's account number to compare. Thanks for your help! -
Plot using Django,Rest Api and Plotly
I am trying to plot using Rest API in Django with the help of plotly but I am not able to plot. for repo_info in repositories: repo_names.append(repo_info['MeterReading_DateTime']) repo_stars.append(repo_info['ACT_IMP_TOT']) data_plots = [{'type' : 'bar', 'x':repo_names , 'y': repo_stars}] layout = {'title': 'MDM Data','xaxis': {'title': 'Date and time'},'yaxis': {'title': 'Total Import'}} fig = {'data': data_plots, 'layout': layout} #offline.plot(fig, filename='Most_Popular_JavaScript_Repos.html') return render(request, "index.html", context={'fig': fig}) -
django form infinity loop
i got infinity loop from this this is my html :i want to show form input in my html and i got infinite loop from the loop {% extends 'main.html'%} {% block content %} <h1>project form</h1> <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> <a class="backButton" href=""><i class="im im-angle-left"></i></a> <br> <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <!-- Input:Text --> <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <input class="btn btn--sub btn--lg my-md" type="submit" value="Submit" /> </form> </div> </div> </main> {% endblock %} this is my form, there's 6 field that i want to show from django.forms import ModelForm from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title','description','featured_image','demo_link','source_link','tags'] but when i put some text on the loop i got 100 loop -
Django rest Nested serializers not returning other fields for CRUD operation
I'm trying to implement CRUD operation with nested serializer with multiple data models so that I can write all field at once when I call the API endpoint. I use mixins from REST framework https://www.django-rest-framework.org/api-guide/generic-views/#mixins I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to see the Course models field in REst api ui. How can I do CRUD operation with using mixins ? How to display Data from two model without creating new model in Django? use of mixins class defined in Django rest framework models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) Serializers.py class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = "__all__" class HomeworkSerializer(serializers.ModelSerializer): class Meta: model = Homework fields = __all__ class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" class All_Serializer(serializers.ModelSerializer): students = serializers.SerializerMethodField() homeworks = serializers.SerializerMethodField() courses = serializers.SerializerMethodField() def get_students(self, obj): students … -
I want to upload a file from outside to a Django web app
Is it possible to upload files to a web app created with Django from outside? Ideally, "http://xxx.xxx.xx.xx:8000/ {parameter1, parameter1}" I want to register data by http communication like this. I'm trying to implement it using the django rest framework, but it's difficult. Is it correct to use the django rest framework? -
Django Ckeditor integrate with React
enter image description here Ck editor used in backend Django to upload files. So it properly formatted the data. It can useful for the Django templates, but now i have to print that data in React but i got that data in form of below! Now can't able to use data in list format! -
How to host django project on live server [closed]
After IP Aliasing, Can I run Django project on multiple IP address. Can anyone guide me how to host Django project on multiple IP address on single machine. -
How to make a database query in django by an url in javascript without making a return
i am trying change my status to 0 to 1 without intrupting the user this function make sure that the user has read a specific portion, while clicking the read more the pargraph opens and also the status should change in the background without intrupting the user this is my views.py @csrf_protect def status(self, request, pk): view = View.objects.get(id=pk) view.status = 1 view.save() my models.py class View(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=True) status = models.CharField(max_length=2, null=False, default=0) my urls.py from django.urls import path from dashboard.views import status urlpatterns = [ path('status/<int:pk>', status, name="status"), ] in my template i am calling the urls using javascript document.location.href ="{%url 'status' data.id %}" but while calling this function "ValueError at /status/2 The view dashboard.views.status didn't return an HttpResponse object. It returned None instead." error show up and when i give it an httpresponse like this @csrf_protect def status(self, request, pk): view = View.objects.get(id=pk) view.status = 1 view.save() return HttpResponse("") or return HttpResponse(status=200) it redirects to an empty page with 200 written in it,the status does change but it intrupts the user can anyone help me fix this -
how to validate the hostel code model field with api in django?
def ran_gen(size, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) class StudentRoom(models.Model): user_id = models.OneToOneField(StudentProfile, on_delete=models.CASCADE, null=True, blank=True) property_room_id = models.ForeignKey(PropertyRoom, on_delete=models.CASCADE, max_length=50, blank=True, null=True) student_hostel_code = models.CharField(max_length=6, default=ran_gen(6), editable=False) note = models.CharField(max_length=50, blank=True, null=True) allocated_date = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.student_hostel_code) -
How to limit Gmail API and MSGraph email API to specific email subjects
I've built a CRM webapp with Django for a specific lead heavy industry. It's working for both gmail and outlook users. Through MsGraph and Google API, the user is able to give authorization via Oath2 to the app to access their inboxes. The app then grabs and parses emails from various sources. Each lead source always sends the lead emails with same subject. This makes the lead emails easy to identify from the users inbox. Unfortunately, the subject of EVERY email that comes in has to be searched to find the desired lead emails. Unfortunately, Identifying by sender isn't an option, and wouldn't change the issue. Each email would still have to be searched. I have a couple of colleagues beta testing right now. As I think about taking on new users that may be outside of my colleagues, I am starting to think the webapps unrestricted access to a user's inbox via the available scopes isn't the best approach for trying to attract new users. I would be suspicious of any 3rd party program wanting to access all of my emails, even if just searching for specific emails. I use Google's watch() and MsGraphs subscriptions to do this while … -
React/Django App: Need to update a field in a put route, with a custom function in the backend, before saving with a serializer
I'm trying to change the content of a field with my own function. I'm using a simplified function that adds commas between each word. I want to be able to send my comma-fied sentence to the frontend but I don't know how to do that with the serializer that was given in Django documentation. I can't find any examples online of someone trying to do this online. I also need to do this in the backend because some of my other custom functions need access to a specific python library. Here is my api > views.py @api_view(['PUT']) def accentLine(request, pk): data = request.data line = Lines.objects.get(id=pk) if data['accent'] == 'shatner': shatnerLine = line.content.replace(' ', ', ') line.translation = shatnerLine line.save() serializer = LineSerializer(instance=line, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Here is my api > models.py class Lines(models.Model): # userId = models.ForeignKey(Users, on_delete=models.CASCADE) script = models.ForeignKey(Scripts, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=50, null=True) content = models.TextField(max_length=5000, null=True) accent = models.CharField(max_length=50, default='english') translation = models.TextField(max_length=5000, null=True) updatedAt = models.DateField(auto_now=True) Here is my api > serializers.py from rest_framework.serializers import ModelSerializer from .models import Lines class LineSerializer(ModelSerializer): class Meta: model = Lines fields = '__all__' -
Deserialize a Array Choice Field in Django
I have an array of choice fields. I want the human-readable text as a response instead of just numbers. How to deserialize an array choice field in Django Rest Frameworks? Response "categories": [ 1, 2 ], Expected Response "categories": [ "Carpentry", "Interior" ], class ChoiceArrayField(ArrayField): def formfield(self,**kwargs): defaults = { 'form_class': forms.TypedMultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) return super(ArrayField, self).formfield(**defaults) Model.py categories_choices = ( (1,"Carpentry"), (2,"Interior"), (3,"Furniture"), (4,"Plumber"), (5,"Electrican"), (6,"Construction"), (7,"Painting"), (8,"Flooring"), (9,"Yard Settings") ) categories = ChoiceArrayField( base_field = models.CharField(max_length=32,choices=categories_choices, null=True,blank=True), default=list, null=True, blank=True ) Serializer.py class ProfileSerializer(serializers.ModelSerializer): phone_number = serializers.IntegerField(source='phone.phonenum') id = serializers.IntegerField(source='phone.id') class Meta: exclude = ('phone',) model = ProfileModel -
Detect New Entries in Database Using Python
I'm currently trying to make a twitter bot that will print out new entries from my database. I'm trying to use python to do this, and can successfully post messages to Twitter. However, whenever a new entry comes in it doesn't update. How would I go about implementing something like this, and what would I use? I'm not to experienced with this topic area. Any help or guidance would be appreciated. -
Why I cannot run server as the first time - Django project?
I do everything as the same as the django documentation, but the result is not as expected. Here is my exception when runserver -
I have created a contact us app and booking app for my website but I still having an issue
What I want is that the sender be the email provided in email field and de reciever must be the website owner Here is my view contact/views.py SPEEDING UP DJANGO EMAIL class EmailThread(threading.Thread): def init(self, email): self.email = email threading.Thread.init(self) def run(self): self.email.send(fail_silently=False) CONTACT US VIEW def contact_us(request): # Contact Us & Booking Table if request.method == 'GET': return render(request, 'contact.html', {"values": request.POST}) if request.method == 'POST': contact_name = request.POST['name'] contact_email = request.POST['email'] contact_subject = request.POST['subject'] contact_message = request.POST['message'] # ========== saving entries into database ====================== # Let's save our datas in database contact = Contact() # here he call our Contact Class # and then we can use its propriertes contact.contact_name = contact_name contact.contact_email = contact_email contact.contact_subject = contact_subject contact.contact_message = contact_message if len(contact_message)<20: messages.error(request, "Contenu du message trop court pour être envoyé. Veillez réessayer svp!") return render(request, 'contact.html') contact.save() # All our entries will be now saved in our database # ========== end saving entries into database ====================== # ============ Let's send user infos and request through email message = f"NAME: {contact_name}\n\n\n\nMESSAGE:\n{contact_message}" to_mail = settings.EMAIL_HOST_USER email = EmailMessage( contact_subject, message, contact_email, to_mail ) EmailThread(email).start() # Here we called our speeding email class :) messages.success(request, "Message sent successfully!\n \ … -
Heroku Django Gunicorn Error H18 (Request Interrupted) errors
I'm using Django with Gunicorn on heroku. And I make https requests via post to my backend sending some files (which don't need to be stored), locally everything works fine. But on heroku when I send small files (<13kbytes) it works, but for larger files I get Error H18 (Request Interrupted). I couldn't understand the reason for the error, if it's from heroku itself, if it's from the body of the request to be large or from gunicorn. What would be the best way to find out the possible cause of this, any ideas? -
How to get the value of manytomany field as a list in Django queryset
class Subject(models.Model): name = models.CharField(max_length=100, blank=True, null=False) category = models.CharField(choices=TYPE_CHOICES, null=True, max_length=50) setting = models.ManyToManyField(Contact) class Contact(models.Model): name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=50, blank=True) id subject_id contact_id 1 66 13 2 66 28 3 71 13 4 71 28 5 98 13 6 98 28 7 98 37 8 20 13 Subject.objects.values('id', 'setting') -> [{'id': 66, 'setting': [13, 28]}, {'id': 71, 'setting': [13, 28]}, {'id': 98, 'setting': [13, 28, 37]}, {'id': 20, 'setting': [13]}] I was wondering how to get the value of manytomany field as a list in Django queryset. The queryset above is the result I want, but I get the output as below. How can I get the value of manytomany field into a list? Subject.objects.values('id', 'setting') -> [{'id': 66, 'setting': [13]}, {'id': 66, 'setting': [28]}, {'id': 71, 'setting': [13]}, {'id': 71, 'setting': [28]}, {'id': 98, 'setting': [13]}, {'id': 98, 'setting': [28]}, {'id': 98, 'setting': [37]}, {'id': 20, 'setting': [13]}] -
How to use serilaizers for django dashboard to fill up the information
create a django application having the functionality of register, login and logout and dashboard screen having profile information (name, email, date of birth, phone number). Connect the app with postgresql database. Note: use serializer for filling up the information. -
how to filter a set of locations during a createview to select one or more locations
I'm stuck on how to approach the design of this problem - or even how to search for answers. I'm still a bit new with Django. The goal is to have a user select one or more locations (libraries in my problem) from a list of locations. I'd like the user to be able to type in an address and then have the list of locations filter based on distance between the locations. I envision the list of locations to be selection field. I'm assuming there will be an input field for the distance (canned choices or just a whole number) and a button to apply the filter. I know how to get the user's location (as a postal address) converted to lat/long using py-geocoder. I have the lat/long of each library. I know how to calculate the distance between two points (py-haverstine or maybe geometry-distance). Where this seems squirrely is the mechanics of filtering the list. How would I do the "filter" action (submit) versus the "save" action if I'm using a model based view? So far, when I hit the server, I've been processing the form as a submission, not a portion. Or would this be better done … -
Bootstrap-Select not updating on mobile
I am using Bootstrap-select for multi-select items with Django. It works fine on desktop, but when the native mobile drop-down is enabled, the selected values of the dropdown do not populate. HTML <!-- start product brand info --> <div class="row"> <div class="col-md-6 col-xs-*"> <div> <label for="id_brand-name" class="form-label">Products</label> </div> <select multiple class="form-control selectpicker mb-3" id="id_brand-name" name="brand-name" mobile="true" multiple required> {% for product in products %} <option value="{{product.id}}" id="optiion">{{ product.brand.name | title }} - {{product.name | title}}</option> {%endfor%} </select> <div class="invalid-feedback"> Select at least one product. </div> </div> </div> <!-- end product info --> <script> //Enble native drop down on mobile window.onload = function () { $('#id_brand-name').selectpicker({ container: 'body' }); if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { $('#id_brand-name').selectpicker('mobile') }}; </script> No matter how many items are selected, the selector always shows Nothing selected. When the data is posted, it is apart of the form though. -
I am getting null value in column "user_id" violates not-null constraint, how can I get foreign key data to register on my comment form?
This my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, name, email, password, **other_fields): if not email: raise ValueError('Users must have an email adress') email = self.normalize_email(email) user = self.model(name=name, email=email, password=password) user.set_password(password) user.save() return user def create_superuser(self, name, email, password = None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(name=name, email=email, password = password, is_superuser=True) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=355, unique=False) is_superuser = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return str(self.id) I have a foreign key on my comment model, I tested this on django admin and it works fine, but with my comment form, the foreign key isn't populating, i just get "null value in column "user_id" violates not-null constraint", I dont know what im doing wrong class Comment(models.Model): comment = models.CharField(max_length=250) user = models.ForeignKey(UserAccount, on_delete=models.CASCADE) def __str__(self): return str(self.user.id) serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model from rest_framework.serializers import ModelSerializer from accounts.models import Comment User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('id', 'name', 'email', 'password') I am reffering my foreign key user as a …