Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error -Undefined variable: 'ModelSelect2Widget'
Happy New Year I am New to this field. I am working on Dependent Dropdowns for which i took reference from- https://django-select2.readthedocs.io/en/latest/extra.html on replicating the same With the following Code - Forms.py- class AddressForm(forms.ModelForm): class Meta: model=City country = forms.ModelChoiceField( queryset=Country.objects.all(), label=u"Country", widget= ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'city': 'cities'}, ) ) city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'country': 'country'}, max_results=500, ) ) Getting Error-Undefined variable: 'ModelSelect2Widget' I also installed - INSTALLED_APPS=[ 'django_select2', 'django_q', ] Kindly Help Me in the same Thanks in Advance -
Problem with reading excel file using pandas in webapp
I am reading an excel file using pandas in my web app based on Django. It works perfectly fine on my system and on one of the instances I had launched on AWS EC2 servers. But when I tried to launch another instance, I am encountering several issues. Pandas is reading the rows and columns beyond the occupied range, with all the values NaN. dat1 = pd.read_excel('Data/Warm Up Cool Down Protocols.xlsx',sheet_name=None) warm_up = curr_WUCD[0] cool_down = curr_WUCD[1] #I am finding the warm_up cool_down values through a separate function WU_Exercise_df = dat[warm_up] CD_Exercise_df = dat[cool_down] I tried adding these lines but that too doesn't work: WU_Exercise_df = WU_Exercise_df.dropna(how='all') CD_Exercise_df = CD_Exercise_df.dropna(how='all') Could you please help me resolve this issue, and help me learn the cause of these disparities. I tried reconciling the versions of pandas and Django on all three places, and the same problem remains with two of those working perfectly fine while the third one giving this problem. -
Django: Map CreateView to an existing form template
I'm pretty new to Django and as an intern backend-developer, I'm asked to make a CreateView for a user to create a shop on the website. I need to make it so that it "maps" to a template my frontend colleague made, with all the fields and the styling already there. I only know how to make simple CreateViews that basically generates a form for you. But here I don't want it to do that, I want to use the already existing styled fields in the template, but I'm having a hard time finding how to do that. Here's my model (I haven't included all the lines for readability reasons, but I'll do if needed): class Dealer(models.Model, CloneMixin): dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL) published = models.BooleanField(null=True,blank=True, default=True) informed = models.BooleanField(null=True,blank=True, default=False) objectid = models.CharField(null=True,blank=True,max_length=100) language = models.ForeignKey(Language, null=True, blank=True,on_delete=models.SET_NULL) name = models.CharField(null=True,blank=True,max_length=100) street = models.CharField(null=True,blank=True,max_length=100) number = models.CharField(null=True,blank=True,max_length=100) city = models.CharField(editable=False,null=True,blank=True,max_length=100) phone = models.CharField(null=True,blank=True,max_length=100) email = models.CharField(null=True,blank=True,max_length=100) users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers') isowner = models.BooleanField(null=True,blank=True, default=False, editable=False) created = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated = models.DateTimeField(auto_now=True, blank=True, null=True) Here's my form: class ShopCreateForm(forms.ModelForm): class Meta: model = Dealer fields = ["name", "email", "phone", "street", "number", "description"] And here's my view (You can … -
How to cause child class to save when parent class is saved?
Is there a way to call the save method of a Child class when the Parent class is saved? I have a field some_other_value on the Child class that is updated whenever the Child is saved, and this is based off a value some_value on the parent class. However, when I save the Parent class, it doesn't update the Child class since the child's save method isn't called. I was thinking of some sort of post_save signal, but thinking whether this would cause some sort of recursive loop. class Parent(models.Model): some_value = models.IntegerField(default=0) class Child(models.Model): some_other_value = models.IntegerField(default=0) def save(self, *args, **kwargs): self.some_other_value = self.some_value * 2 super().save(*args, **kwargs) -
Django STATIC_URL always points to local directory
I want to serve the static content generated by django in a different host with nginx. The server with the files has the name 'static-server' and I can't access it with django. The static file looks like this: STATIC_URL = 'http://static-server/static/' But the error log gives the following path: "GET /http:/static-server/static/admin/css/base.css HTTP/1.1" 500 145 Why is django looking for the files in local? How can I avoid this? -
Django hiding an item if object == None
In my template i'm trying to hide a paypal button if the email item is None. {% if object.email == None %} <h1>Nothing here </h1> {% else %} <form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="business" value="{{ object.email }}"> </form> {% endif %} After testing by not entering the email in my form, the button still shows and the 'Nothing here' is not showing. -
Global variable doesn't work inside django views
I wanted to use some dummy data in my django views to work with templates. When posts variable is outside home function all im getting is empty body. Although when i move it inside everything displays as it should. from django.shortcuts import render posts = [ { 'author': 'Kamil', 'title' : 'Post 1', }, { 'author': 'Tomek', 'title' : 'Post 2', }, ] def home(request): context = { 'posts' : posts } return render(request, 'blog_app/home.html', context) Here is also my html <!DOCTYPE html> <html> <head> <title></title> </head> <body> {% for post in posts %} <h1>{{ post.title }}</h1> <p>By {{ post.author }}</p> {% endfor %} </body> </html> -
django email does not work and don't sent email
I am following this tutorial [enter link description here][1] the aim to verify email after users register to the system. here is the code. serializers.py class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=68, min_length=6, write_only=True) default_error_messages = { 'username': 'The username should only contain alphanumeric characters'} class Meta: model = User fields = ['email', 'username', 'password'] def validate(self, attrs): email = attrs.get('email', '') username = attrs.get('username', '') if not username.isalnum(): raise serializers.ValidationError( self.default_error_messages) return attrs def create(self, validated_data): return User.objects.create_user(**validated_data) my view.py class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = User.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://' + current_site + relativeLink + "?token=" + str(token) email_body = 'Hi ' + user.username + \ ' Use the link below to verify your email \n' + absurl data = { 'email_body': email_body , 'to_email': user.email , 'email_subject' : 'Verify your email' } Util.send_email(data) return Response(user_data , status=status.HTTP_201_CREATED) my utils.py class EmailThread(threading.Thread): def __init__(self, email): self.email = email threading.Thread.__init__(self) def run(self): self.email.send() class Util: @staticmethod def send_email(data): email = EmailMessage( subject=data['email_subject'], body=data['email_body'] , to=[data['to_email']]) EmailThread(email).start() and the settings.py EMAIL_USE_TLS = True EMAIL_HOSTS = "smtp.gmail.com" EMAIL_PORT = … -
how to add values to a ManyToManyField
I have the following model that has a field called who_can_see and I don't know how to add data to this filed nor the type of data (dictionary, array...) #modles.py class Author(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) author = models.ForeignKey(Author, on_delete=models.CASCADE) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) #🔴 who_can_see = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='tweet_user', blank=True) def __str__(self): return self.title you can see here where i add the 🔴, I am trying to who_can_see= [author, payload["who_can_see"]] so I expected the field who_can_see to be an array but when I make the POST request i got 500 error @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_book(request): print({"request.data": request.data}) payload = request.data user = request.user try: author = Author.objects.get(id=payload["author"]) book = Book.objects.create( title=payload["title"], description=payload["description"], added_by=user, author=author, # who_can_see= [author, payload["who_can_see"]] # 🔴 ) serializer = BookSerializer(book) return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
Django: Link data from 2 Querysets
Im new to django and im currently making an admin panel where i can view user orders. I have two model fields OrderItem model class OrderItem(models.Model): customer_id = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) order_id = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) Users model class Users(AbstractBaseUser): name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=255) views.py def admin_panel(request): orders=OrderItem.objects.all().order_by('-customer_id') context={ 'orders':orders, } return render(request, 'index.html', context) index.html {% for order in orders %} <tr> <td>{{order.order_id}}</td> <td>{{order.customer_id}}</td> <td>{{order.date_added}}</td> <td>{{order.product_id}}</td> <td>{{order.quantity}}</td> <td><span class="label label-success">COMPLETED</span></td> </tr> {% endfor %} In my views.py , instead of every customer id, how i get the actual name of the customer, based on User model? -
Wrong URL for email confirmation in django
I'm using django with celery to async email confirmation after sign up. Email's detail that I send is: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, {{ SITE_URL }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} before using celery I was using {{ domain }} and it was working. but now it's not working so I defined a context_processor {{ SITE_URL }}. it's working in other pages in site but when it sends email it's like this: Hi TestUser12, Please click on the link to confirm your registration, /active/Mjg/afy780-593977afb79b0da93fad09e8458d29c8/ -
django The requested URL was not found on this server
i am deploying django project on apache2 server digital ocean there is no error when apache is restart but this is the error i am getting Not Found The requested URL was not found on this server. Do i need index.html or this is permission issue ? -
Implement Reminder Functionality For Events in Python Django
I have implemented an event module in our Django application using Google Calendar API, and I have set the reminder time on events, now I have to want to get the reminder notification before starting the event in my application, But the delivery mechanisms only available by Google API are Pop-up. These are supported on mobile platforms and on web clients. Email sent by the server. And they have not provided any of these types of functionality that I can get reminders from Google Calendar to our application. I have tried from push notifications of Google Calendar API but it has different functionality. Solution: I have another option to achieve this using celery beat and can write cron job but it may costly to check from the database after the specific time interval that, is there time matched with event reminder then push the notification. If the events data is on large scale it was a hectic job. I'm looking for the best solution or any third party tool which is providing the reminder functionality. -
How can i create an email change form in django?
I'm using django-allauth to handle authtentication in my project. I'm now trying to add a an email change system. Allauth has an email settings page but it has a lot of features that i don't need, such as multiple emails. What i'm looking for is a simple way to just set a new email, use an email message to confirm it and that's it. Is there any way to do this with allauth or do i have to create my own system? -
Setting up celery beat task to run on multiple weekdays
I have a task that I'd like to run on Tuesdays, Wednesdays and Thursdays only. I have it setup as follows: 'schedule': crontab( day_of_week='2,3,4', hour=19, minute=0) The task appears to run only on Tuesday though. Is the above the accepted way of specifying the weekdays or should it be 'tue, wed, thu'? -
How to extend user model in django rest framework?
I am working in a django rest framework project. I have created a login, register, logout and reset password viewsets. serializers.py from rest_framework import serializers from django.contrib.auth.models import User from django.contrib.auth import authenticate # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') # Register Serializer class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password':{'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], validated_data['email'], validated_data['password']) return user # Login Serializer class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self,data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") class ChangePasswordSerializer(serializers.Serializer): model = User old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) api.py from rest_framework import generics, permissions, status from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer, LoginSerializer, ChangePasswordSerializer from django.contrib.auth.models import User # Register API class RegisterAPI(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) # Login API class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1], "message": "" }) # Get … -
Django [myurl] took too long to respond
Something that I never seen before happened with my project, I made a research and tried different ways to fix it but with no success. I have a django server assign to 192.168.2.81:7575 where I received triggers from another platform. Now, when I run python3 manage.py runserver 0.0.0.0:7575 I got nothing but 192.168.2.81 took too long to respond. When I run into localhost it works but this is not what I need. I checked my allowed hosts in settings.py and it seems to be fine: ALLOWED_HOSTS = ['192.168.2.81', '127.0.0.1'] I researched some solutions, one of them to deactivate the virtualenv, done but without success. I tested the website using curl curl http://192.168.2.81:7575 and I got no error so my connection is not broken. Also I check if obtaining the correct ip address with ifconfig and looks fine. I think I'm missing something but can't find what because I get confused it was working correctly before? Can someone say what I'm missing? -
Read Data From Zkteco WL20 Device Over TCP protocol(wifi) using python
conn = None zk = ZK('192.168.10.77', port=4370, timeout=5, password=0, force_udp=False, ommit_ping=False) try: conn = zk.connect() print(conn.get_serialnumber()) print(conn.get_time()) conn.poweroff() print('--- sizes & capacity ---') conn.read_sizes() print(conn) print('--- Get User ---') users = conn.get_users() conn.delete_user(uid=32) print(users) print(conn.get_firmware_version()) print(conn.get_device_name()) print(conn.get_attendance()) # try: # conn = zk.connect() # conn.disable_device() # print(zk.set_user(29, 'MehranAbc', 0, '', '1', '29')) # zk.enroll_user('26') # conn.enable_device() # except Exception as e: # print("Process terminate : {}".format(e)) # conn.disable_device() conn.disable_device() print('Firmware Version: : {}'.format(conn.get_firmware_version())) # print '--- Get User ---' users = conn.get_users() print(conn.get_users()) for user in users: privilege = 'User' if user.privilege == const.USER_ADMIN: privilege = 'Admin' print('+ UID #{}'.format(user.uid)) print(' Name : {}'.format(user.name)) print(' Privilege : {}'.format(privilege)) print(' Password : {}'.format(user.password)) print(' Group ID : {}'.format(user.group_id)) print(' User ID : {}'.format(user.user_id)) conn.test_voice() conn.enable_device() except Exception as e: print("Process terminate : {}".format(e)) finally: if conn: conn.disconnect() return Response({"success": False}) get_users() function not getting any data.. Connection is build also I can create employee using python but while getting user it create issue give empty list. -
React/Redux/Django: why the login is undefined?
I created a login and register form for my posts app (CRUD) by using react, redux and django. Im getting this error --> Warning: Failed prop type: The prop login is marked as required in Login, but its value is undefined. Also, the value of login is undefined, i don't know what i missed (see below pic) auth.js (action) import axios from "axios"; // managing authentication based action types import { USER_LOADED, USER_LOADING, LOGIN_SUCCESS, LOGOUT_SUCCESS, REGISTER_SUCCESS, } from "./actionTypes"; // check token & load user export const loadUser = () => (dispatch, getState) => { dispatch({ type: USER_LOADING }); axios .get("http://localhost:8000/api/auth/user", tokenConfig(getState)) .then((res) => { dispatch({ type: USER_LOADED, payload: res.data, }); }) .catch((error) => console.log(error)); }; // login user export const login = (username, password) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body const body = JSON.stringify({ username, password }); axios .post("http://localhost:8000/api/auth/login", body, config) .then((res) => { dispatch({ type: LOGIN_SUCCESS, payload: res.data, }); }) .catch((error) => console.log(error)); }; // Register user export const register = ({ username, password, email }) => (dispatch) => { // Headers const config = { headers: { "Content-Type": "application/json", }, }; // Request Body … -
How to create a post(or call it an article) and choose who can see it
I created the following model, with an author who is the user that created it and Title and description, with few other fields. from django.db import models from django.conf import settings from django.utils import timezone # Create your models here. class Author(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) author = models.ForeignKey(Author, on_delete=models.CASCADE) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) # 🔴 who_can_see who_can_see = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='tweet_user', blank=True) def __str__(self): return self.title now I want to filter books based on who_can_see and auther @api_view(["POST"]) @csrf_exempt @permission_classes([IsAuthenticated]) def add_book(request): print({"request.data": request.data}) payload = request.data user = request.user try: author = Author.objects.get(id=payload["author"]) book = Book.objects.create( title=payload["title"], description=payload["description"], added_by=user, author=author, who_can_see=payload["who_can_see"] # 🔴 ) serializer = BookSerializer(book) return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_201_CREATED) except ObjectDoesNotExist as e: return JsonResponse({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND) except Exception: return JsonResponse({'error': 'Something terrible went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(["GET"]) @csrf_exempt @permission_classes([IsAuthenticated]) def get_books(request): user = request.user.id # books = Book.objects.filter(added_by=user) books = Book.objects.filter(who_can_see=user, added_by=user) # 🔴 after i created this user who are not logged in can see the all private books. serializer = BookSerializer(books, many=True) return JsonResponse({'books': serializer.data}, safe=False, status=status.HTTP_200_OK) -
Why are password fields not rendering in the registration page? Django
I'm creating a form but the fields to input passwords are not appearing. I can only see the values to input first name, last name and email address. Please any help I would really appreciate it. The code works as following: First there is a model in where there are the 5 values that I want to be printed. Then the form values are printed individually in the HTML code. HTML code: <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-5 d-none d-lg-block bg-register-image"></div> <div class="col-lg-7"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Create an Account!</h1> </div> <form class="user" method="POST"> {% csrf_token %} <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.first_name }} </div> <div class="col-sm-6"> {{ form.last_name }} </div> </div> <div class="form-group"> {{ form.email }} </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> {{ form.password1 }} </div> <div class="col-sm-6"> {{ form.password2 }} </div> </div> <button type="submit" class="btn btn-primary btn-user btn-block"> Register Account </button> <hr> <a href="index.html" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Register with Google </a> <a href="index.html" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Register with Facebook </a> </form> <hr> <div class="text-center"> <a class="small" … -
How to use the two fields as many to many fields in another table?
Be Patient! Am new to the python and Django ,and am trying to implement feedback form for customer,each customer has unique question set.there are three tables such question,answer,customer info. when user submit the question it should be in the answer table, there i wanted to map question and answer choices.oHow to do that? my models.py ```import uuid from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from django.db.models import Max from django import forms class Questions(models.Model): fields = ['question', 'field_type', 'answers'] field_choices=(("radio" ,"radio"), ('checkbox', 'checkbox'), ('text', 'text')) question=models.TextField(verbose_name='question',blank=False,null=False,default='') # field_type = models.TextField(verbose_name='field_type', blank=False, null=False,choices=field_choices,default='Domain') # field_type = models.TextField(verbose_name='field_type', blank=False, null=False, default='') field_type = models.TextField(verbose_name='answer_choices', blank=False, null=False,choices=field_choices,default='') answer_choice = models.TextField(verbose_name='answer_choices', max_length=128,blank=True, default='') # def __str__(self): # return self.question class Customer(models.Model): Cust_id=models.CharField(verbose_name='Cust_id',editable=False,max_length=128,blank=False,null=False,default='',db_index=False) # id = models.CharField(primary_key=True, editable=True, max_length=10,default='') Domain=models.CharField(verbose_name='Domain',max_length=128,blank=False,null=False,default='') name = models.CharField(verbose_name='Name', max_length=128, blank=False, null=False,default='') Address = models.CharField(verbose_name='Address', max_length=128, blank=False, null=False,default='') Cust_Address2 = models.TextField(verbose_name='Cust_Address2', blank=False, null=False, default='') Cust_City = models.TextField(verbose_name='Cust_City', blank=False, null=False, default='') # city_code = models.TextField(verbose_name='city_code', blank=False, null=False, default='') city_code = models.ManyToManyField('Locations',related_name='City_code',default='',db_index=True) sublocation=models.CharField(verbose_name='sublocation', max_length=128, blank=False, null=False,default='') sublocation_code=models.CharField(verbose_name='sublocation_code', max_length=128, blank=False, null=False,default='',db_index=False) Country = models.TextField(verbose_name='Country', blank=False, null=False, default='') question=models.ManyToManyField('Questions',related_name='customer_question',default='') # class Meta: # indexes = [ # models.Index(fields=['Cust_id', 'Domain','name','Address','Cust_Address2','Cust_City','city_code','sublocation','Country','question']), # models.Index(fields=['Cust_id'], name='Cust_id_idx'), # models.Index(fields=['Domain'], name='Domain_idx'), # models.Index(fields=['name'], name='name_idx'), # models.Index(fields=['Address'], name='Address_idx'), # models.Index(fields=['Cust_Address2'], … -
Unable to get repr for <class 'django.db.models.query.QuerySet'> when query'ing python 2 class
Django has following build in class: @python_2_unicode_compatible class ResetPasswordToken(models.Model): I'm writing a test and want to check if there is a reset password token in db for a specific user. So I do: token = ResetPasswordToken.objects.filter().all() Hower python has problems with this: Unable to get repr for <class 'django.db.models.query.QuerySet'> I think this is because I am using python 3 and above the model there is a '@python_2_unicode_compatible'? How can I do this correctly? Thanks -
when i refresh the page the form data automatically adding due to GET method when i remove it it show doesn't return httpresponse obj
How can I use is_valid() with POST method to get inputs from user in my views.py ? I also use return redirect() and HttpResponseRedirect(), but it doesn't work. @login_required def about(request): data = userdata.objects.all() form = student(request.POST) if request.method == 'POST' or 'GET': if form.is_valid(): name = request.POST.get('name') email = request.POST.get('email') password = request.POST.get('password') fm = userdata(name=name, email=email, password=password) fm.save() form = student() else: form = student() return render(request, 'about.html', {'form': form, 'data': data}) -
uwsgi - Main process exited, code=exited, status=1/FAILURE
django - 2.2.12 nginx - 1.14.0 (Ubuntu) uWSGI - 2.0.18 (64bit) uwsgi.ini [uwsgi] base = /home/ubuntu/myApp project = myApp home = %(base)/venv chdir = %(base)/%(project) module = %(project).wsgi:application master = true processes = 1 threads = 2 socket = /tmp/%(project).sock chmod-socket = 666 vacuum = true env = DJANGO_SETTINGS_MODULE=myApp.settings.development logto = %(base)/logs/uwsgi.log pidfile2=/tmp/uwsgi.pid socket-timeout = 10 listen = 1024 uwsgiLog compiled with version: 7.4.0 on 16 December 2019 07:55:54 os: Linux-5.4.0-1032-aws #33~18.04.1-Ubuntu SMP Thu Dec 10 08:19:06 UTC 2020 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 2 current working directory: /home/ubuntu/myApp detected binary path: /usr/local/bin/uwsgi uWSGI running as root, you can use --uid/--gid/--chroot options *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** chdir() to /home/ubuntu/myApp/myApp writing pidfile to /tmp/uwsgi.pid your processes number limit is 3675 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) Listen queue size is greater than the system max net.core.somaxconn (102). VACUUM: pidfile2 removed. systemctl status uwsgi Jan 04 17:35:16 uwsgi[4194]: [uWSGI] getting INI configuration from /home/ubuntu/Myapp/uwsgi.ini Jan 04 17:35:16 systemd[1]: uwsgi.service: Main process exited, code=exited, …