Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Allow more then one serializer_class in one ModelViewSet class Django REST
How do I define more than one serializer_class in one ModelViewSet? I have four functions in one ModelViewSet, and any positions have their serializer. And I want to place four serializer in one serializer_class? -
Page not found error while trying to reset password in Django3
Here i am using Python 3.7 and Django 3.0 Where when user clicks the forgot password an email is sent to the user with a link to reset the password when the user is clicking this link i am getting page not found error Here is my views.py ..... ...... associated_users= ClientUser.objects.filter(email= data) if associated_users.exists(): for user in associated_users: c = { 'email': user.email, 'domain': request.META['HTTP_HOST'], 'site_name': 'your site', 'uid': urlsafe_b64encode(force_bytes(user.pk)), 'user': user.name, 'token': default_token_generator.make_token(user), 'protocol': 'http', } self.request.session['e_data'] = { 'email': user.email, } subject_template_name='core/reset_subject.txt' # copied from django/contrib/admin/templates/registration/password_reset_subject.txt to templates directory email_template_name='core/reset_email.html' # copied from django/contrib/admin/templates/registration/password_reset_email.html to templates directory subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) email = loader.render_to_string(email_template_name, c) send_mail(subject, email, settings.DEFAULT_FROM_EMAIL , [user.email], fail_silently=False) result = self.form_valid(form) messages.success(request, 'An email has been sent to ' + data +". Please check its inbox to continue reseting password.") return result result = self.form_invalid(form) messages.error(request, 'No user is associated with this email address') return result here is my reset_email.html {% load i18n %}{% autoescape off %} {% trans "There has been a request to reset your password for Degree. To reset your password use this link:" %} {% block reset_link %} "{%if secure … -
Django redirect doesn't reach the root url
Looks like redirect(<url>) is adding <url> to the current view url, ignoring urls.py, with respect to the Code below redirecting to "<mydomain>.com/savePersonalEdits/account/" while what I wanted is: "<mydomain>.com/account/" Code: At the end of some Django view function I have: return redirect('account/') urls: path('account/', views.accountSettings), path('savePersonalEdits/', views.saveEdits, name="savePersonalEdits") #name needed for HTML form action url -
How to delete an object with a windows.confirm?
I have a template that lists all the activities of a client. In this template, I have a button to delete any activity I choose. This button has a confirmation to delete through a windows.confirm. But it's not working the way you expect. Sometimes the button works, sometimes it doesn't. {% for servico in object_list %} {{ servico.refferring_funcionario }} {{ servico.get_lista_servico_display }} {{ servico.data_servico }} R$ {{ servico.valor_servico }} <a href="{% url 'servico:editar-servico' servico.id %}" class="btn btn-secondary btn-sm">Edit</a> <a href="" class="btn btn-danger btn-sm" onclick="return myFunction()">Delete</a> {% endfor %} Js <script> function myFunction() { if (window.confirm("Você tem certeza que deseja excluir ?")) { window.location.href="{% url 'servico:excluir-servico' servico.id %}"; } } -
configure urls in django, cmd prints: AttributeError: module 'myapp.views' has no attribute 'index'
i have been trying to run this code but it doesn't show the Hey, Welcome inthe views.py myproject/myapp/views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>Hey, Welcome</h1>") myproject/myapp/urls.py urlpatterns=[ path(" ",views.index, name="index") ] myproject/urls.py urlpatterns = [ path('admin/', admin.site.urls),<br> path(' ', include('myapp.urls') ), ] pls can you help me figure out what im doing wrong, when i run the code, it only shows 'the install worked successfully! congratulation!!' without run the html code that i pass inthe views.py -
share file between admin user and staffusers in django
I have a user_type named a staff_user and Admin here the admin in supposed to share the file with staff_user.On the file_list page of admin we are supposed to have an option called share_with_staff_user when clicked it will display the list of staff_users when selected and shared the file should be displayed on the page of staff_user file page. how can i acheive this. models.py class StaffUserDocument(BaseModel): staffuser = models.ForeignKey(StaffUser, related_name='documents', on_delete=models.CASCADE) uploaded_by = models.ForeignKey('User', related_name='+', null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255) file = models.FileField(upload_to='protected/') class AdminDocument(BaseModel): uploaded_by = models.ForeignKey('User',related_name='+',null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=255, unique=True) file = models.FileField() views.py class AdminDocumentListView(LoginRequiredMixin, TemplateView): template_name = 'admin_documents_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['urlParams'] = self.request.GET context['instanceData'] = {} return context @login_required def staff_user_profile_documents_view(request): staffuser = request.user.person.staffuser data = {'staffuser': staffuser, 'documents': staffuser.documents.all()} return render(request, template, data) -
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 \ …