Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 502 bad gateway with Nginx and Uwsgi
I can normally open up my web in the front several hours after deployment,but later , it occurred 502 bad gateway ,it is so wired, my web uses Django and Nginx and Uwsgi, i do research a lot on google,but failed with nothing Here is my configuration: 1.Nginx configuration # mysite_nginx.conf upstream django { server 127.0.0.1:8004; # for a web port socket (we'll use this first) } server { listen 80; server_name www.example.com # substitute your machine's IP address or FQDN charset utf-8; client_max_body_size 75M; # adjust to taste location /media { alias /home/blender_font_project/django_file/Blender_website/media; } location /static { alias /home/blender_font_project/django_file/Blender_website/static; } location / { uwsgi_pass 127.0.0.1:8003; include /etc/nginx/uwsgi_params; } } 2.uwsgi configuration # mysite_uwsgi.ini file [uwsgi] chdir = /home/blender_font_project/django_file/Blender_website module = djangoTest5.wsgi master = true processes = 10 socket = :8003 vacuum = true harakiri=60 daemonize=/home/blender_font_project/uwsgi_file/real3dfont_logfile BTW , i have set Django to DEBUG Ture and i can access my resource by www.example.com/static/example.jpg,but the web page shows 502 I really dont know why , thanks if you offer any help! -
Why celery is giving Database connection error even though database server has connection pooling active
Currently I am facing some problem regarding my web app. I have a web app built with django along with celery for some background task. The workflow is - client uploads an image and then some processing is done in celery task like some api call and some db update. Then client polls for result and if the task is done the result is given as response. I am using DigitalOcean managed postgresql db and using a connection pool. For celery message queue I am using rabbitmq and redis as backend result server. As most of my task is I/O bound I am using gevent for celery so that I can receive concurrent requests without any problem. My server has 2vcpu, 4GB RAM, 25GB SSD. At first when no connection pooling was activated in DB, we stress tested with around 100 image uploaded at the same time and got "FATAL: remaining connection slots are reserved for non-replication superuser connections". After some research found that this was due to db connection limit crossing, So I used connection pooling. Then there was no problem for django. But strangely celery was giving the same error while updating database. My celery command is (from … -
My postgresql database not showing many to many field column but django admin page does. Why?
I hope you got the question from the title itself. After migrating I can select multiple fields from that many to many field in django admin page but when I click on save it saves in the admin page of django but when I check the postgresql database everything that is not many to many field saves but the table lacks many to many field column. -
How to control request object in logging handler
Hi im making a logging module in django i want to save all of the user activity in class Log model here is Log model class Log(models.Model): user = models.ForeignKey("user") ip_address = models.Charfield() visited_view = models.Charfield() for example, when user(testman) visit PostCreateView Log object will create ("testman", '[user_ip_address]', 'visited_view') here is my settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'db_logger': { 'class': 'myapp.utils.logging.LogHandler', }, }, 'loggers': { 'request': { 'handlers': ['db_logger'], 'level': 'INFO', } }, } db_logger will use My Custom LogHandler from myapp.models import Log class LogHandler(logging.Handler): def emit(self, record): if record.name.split('.')[0]=='request': user = recored.request.user ## This is what i want :) Log.objects.create() and In CreateView insert logging command my_logger = logging.getLogger('db_logger') class PostCreateView(CreateView): def get_context_data(self, request, *args, **kwargs): my_logger.warning('test') but I have big problem now because logging.Handler is python lib not django So i can't control request in LogHandler :( How can i control request object in Handler? thank you :) -
user Checkout and guest checkout: best way to use both in Django
Actually I need suggestion about best practice to handle guest checkout and customer checkout. I have a scenario that 1 order can have multipul products (which is not problem). My order table is like class Orders(models.Model): customer= models.ForeignKey(Customer, on_delete=models.CASCADE) order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) ordertime = models.DateTimeField(auto_now_add=True) order_status = models.CharField(max_length=50) is_placed = models.BooleanField(default=False) and then it is linked to product table like this class OrderProduct(models.Model): order=models.ForeignKey(Orders, on_delete=models.CASCADE) activity = models.ForeignKey(ActivityOrganizer, on_delete=models.CASCADE) participants=models.IntegerField(default=0) totalPrice=models.DecimalField(max_digits=10, decimal_places=2) checkIn = models.DateField() language = models.CharField(max_length=50, null=False, blank=False) And my Customer Table is class Customer(models.Model): customerProfile = models.OneToOneField(User, on_delete=models.CASCADE) first_name=models.CharField(max_length=50, null=False, blank=False) last_name=models.CharField(max_length=50, null=False, blank=False) email=models.CharField(max_length=50, null=False, blank=False) mobile_number=models.CharField(max_length=50, null=False, blank=False) profile_image=models.ImageField(null=True, upload_to='CustomerProfile') is_customer=models.BooleanField(default=False) city=models.CharField(max_length=50, null=True, blank=True) gender=models.CharField(max_length=50, null=True, blank=True) verification_key = models.CharField(max_length=100, null=True, blank=True) def __str__(self): return str(self.first_name) Now I want to Enable guest checkouts aswell . then Should I use existing tables of order by allowing Foregin key Null ? Or I should make seprate order tables for this ? What will be best way ? -
make a periodic task run by time user given
i have to build the appication by djano to send mail notification to user , but the user want to set a time to send thier email every at that time they want , i read that celery has periodic task to run but must set time already , so how can i make a periodic task with time given by user using celery ?? class UserMail(models.Model): user_mail = models.EmailField() auto_send_mail = models.BooleanField(default=False) time_set = models.TimeField(blank=True,null=True) time set to get a time given by user when they post in the form -
Django 2.2 - change with of related auto_complete field on admin form
I'm trying to change the field width of a related auto_complete field. So that the selected record is shown a bit wider. <span class="select2 select2-container select2-container--admin-autocomplete select2-container--focus" dir="ltr" style="width: 260px;"> // ... ></span> I created my own form and tried fiddling with widget.attrs (inside the init) but it has zero effect. Which itself is no strange, since these are all span elements rendered. class OrderLineForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.fields['product'].widget.attrs.update({'stytle': 'width: 400px'}) self.fields['product'].widget.attrs.update({'width': 400}) I was also looking which widget is being used, but didn't find it either. Djanog docs do explainThe form.Select is a simple dropdown list, which does not provide auto complete functionality. I also tried changing some css for .select2 class, but seems to gave no effect. -
How to add extra field to django serializer?
I am trying to add an additional field to my serializer but I am getting the following error:- "The field 'provider' was declared on serializer CreateUserSerializer, but has not been included in the 'fields' option." Here is my serializer.py:- class CreateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField() username = serializers.CharField() company = serializers.CharField() provider = serializers.CharField() password = serializers.CharField(write_only=True) company_detail = serializers.SerializerMethodField() branch_detail = serializers.SerializerMethodField() def get_company_detail(self): return {} def get_branch_detail(self): return {} def create(self, validated_data): try: with transaction.atomic(): user = User.objects.create(**validated_data) user_profile = UserProfileModel.objects.create(user=user) user_profile.__dict__.update(**validated_data) user_profile.save() identity = FederatedIdentityModel.objects.create(user=user, oauth_provider=validated_data['provider']) company = CompanyModel.objects.create(user=user, name=validated_data['company']) branch = BranchModel.objects.create(user=user, name=validated_data['company'], company=company) return user except APIException: raise APIException( detail="Failed to register", code=status.HTTP_500_INTERNAL_SERVER_ERROR ) class Meta: model = User fields = ['first_name', 'last_name', 'password', 'email', 'username', 'company_detail', 'branch_detail'] I don't want to add the company and provider fields in the field option as it is not a part of user model. I just want to use them as writable fields so that I can create object for the two models. How can I get rid of the following error? -
Django: ERROR: python setup.py egg_info Check the logs for full command output
I am newbie as developer and have developped a first project in Django I try to deploy my project in a test server (Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-88-generic x86_64)) prepared by a sys admin in my team Each time I try to install dependancies (pip install -r requirements.txt) it fail with the error below: ERROR: Command errored out with exit status 1: command: /home/test/envs/envTbm/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-1uqfxt7j/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-1uqfxt7j/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info cwd: /tmp/pip-install-1uqfxt7j/psycopg2/ Complete output (7 lines): running egg_info creating /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info writing /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-install-1uqfxt7j/psycopg2/pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: b'You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.\n' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I did not understand what could be the problem... -
Django Rest Api Annotate group by Filter showing Error?
This error i am getting while enter http://127.0.0.1:8000/api/student/ this url My Database : posts/models.py ''' from django.db import models class Student(models.Model): lname = models.CharField(max_length=50) fname=models.CharField(max_length=50) def __str__(self): return self.lname ''' posts/serializers.py(webapp) ''' from rest_framework import serializers from . import models class StudentSerializer(serializers.ModelSerializer): class Meta: fields = ('lname','fname',) model = models.Student ''' posts\filters.py(webapp) ''' from django_filters import rest_framework as filters from .models import Student class StudentFilter(FilterSet): total = filters.NumberFilter(name='total') class Meta: model = Student fields = ['lname','fname','total',]#other fields ''' posts\views.py(webapp) ''' from rest_framework import generics from django.db.models import Count from .models import Post,Student,Exam,Sample from .serializers import PostSerializer,StudentSerializer,ExamSerializer,SampleSerializer from django_filters.rest_framework import DjangoFilterBackend #import django_filters.rest_framework from django.db import connection class StudentList(generics.ListAPIView): serializer_class = StudentSerializer def get_queryset(self): return Student.objects.all().values('fname').annotate(total=Count('fname')).order_by('total') ''' posts\urls.py(webapp) ''' from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view()), path('<int:pk>/', views.PostDetail.as_view()), path('student/',views.StudentList.as_view()), path('exam/',views.ExamList.as_view()), path('sam/',views.SampleList.as_view()) ] ''' SampleProject(urls.py) ''' from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('posts.urls')), ] ''' I got output in shell but i could't get the same value in browser (api) -
How to open a file in itertools.islice() function in python?
I am tried some script in that i catch pdf file and then convert that file to txt file . I got type of text file as _io.textIoWrapper . Now i call itertools.isslice() with _io.textIoWrapper object . That produce ValueError: I/O operation on closed file. If file format plain io.textIoWrapper didn't give any error. I tried to open textIoWrapper object but that gives expect only str , bytes or None not TextIoWrapper type views.py def save_file(cls, user, file, file_format, project_id,file1): project = get_object_or_404(Project, pk=project_id) parser = cls.select_parser(file_format) if file_format == 'pdf': path = default_storage.save('text_pdf_file.pdf', ContentFile(file.read())) return_file = convert_pdf_txt(path,file_format) print(type(return_file)) # _io.textIoWrapper file = return_file data = parser.parse(file,file_format) storage = project.get_storage(data) storage.save(user) utils.py class PlainTextParser(FileParser): def parse(self, file,file_format): if file_format == 'plain': file = EncodedIO(file) file = io.TextIOWrapper(file, encoding=file.encoding) while True: batch = list(itertools.islice(file, settings.IMPORT_BATCH_SIZE)) if not batch: break yield [{'text': line.strip()} for line in batch] convert.py import os from docx import Document import pdfplumber as pp import io import unidecode import re def remove_accented_chars(text): text = unidecode.unidecode(text) return text def remove_extra_spaces(line): return re.sub(' +|\t+',' ',line) def remove_special_char(line): return re.sub(r"[^a-zA-Z0-9%.@]+",' ', line) def preprocessing(lines,fileExtension): example_text_file = "ex_txt.txt" for line in lines: if fileExtension == "docx": x=str(line.text) elif fileExtension == "pdf": x … -
Django ModelForm. Select a valid choice. That choice is not one of the valid choices
I have a Model and a ModelForm. The ModelForm has a dependent dropdown list implemented with JQuery. Whenever I try to save the ModelForm in my views, I get an error saying that the choice that I have selected is not valid. Does it have to do with the choices/options to the individual_kata_event, individual_kumite_event, team_kata_event & team_kumite_event dropdowns being added after a choice from the gender dropdown has been selected? In models.py, class Athlete(models.Model): name = models.CharField(max_length=100) gender = models.CharField(max_length=100, choices=GENDER_CHOICES) date_of_birth = models.DateField() feet_height = models.PositiveIntegerField(default=0) inch_height = models.PositiveIntegerField(default=0) weight = models.FloatField(default=0.0, help_text='Weight in kg') club = models.CharField(max_length=100, choices={ ('Arrianna Academy' , 'Arrianna Academy'), ('Bangladesh Shitoryu Karate-do Union' , 'Bangladesh Shitoryu Karate-do Union') }) team = models.CharField(max_length=100, choices={ ('Bangladesh Ansar & VDP' , 'Bangladesh Ansar & VDP'), ('Bangladesh Army' , 'Bangladesh Army') }) individual_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') individual_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kata_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') team_kumite_event = models.CharField(max_length=22, choices=[('', ''), ], default='None') gold = models.PositiveIntegerField(default=0) silver = models.PositiveIntegerField(default=0) bronze = models.PositiveIntegerField(default=0) picture = models.ImageField(upload_to='athlete_images', blank=True) In forms.py, class AthleteForm(forms.ModelForm): class Meta: model = Athlete fields = '__all__' widgets = { 'date_of_birth': forms.DateInput( format=('%m/%d/%Y'), attrs={ 'class': 'form-control', 'placeholder': 'Select a date', … -
convert pandas excel output to json drf django
i have this api. it returns excel header data and i want to dump pandas data to json but its showing error...................................................................... @api_view(['POST', ]) def bulkUploadPolicyMember(request): data = json.loads(request.data['data']) data = decode_data(data) data["uploaded_by"] = request.user.uid data['status'] = 0 data['uploaded_date'] = datetime.datetime.now() data['sheet'] = data['sheet'] if 'sheet' in data and data['sheet'] != '' else None data['docket_id'] = data['docket_id'] if data['docket_id'] != '' else None if data['docket_id'] is None: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) try: doc_obj = InwardDocument.objects.values('insurer_id').get(uid=data['docket_id']) except InwardDocument.DoesNotExist: return CustomeResponse(request=request, comment=DOCKET_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=DOCKET_REQUIRED) policy_file_path = settings.BULK_POLICY_FILE_UPLOAD+'insurers/'+str(doc_obj['insurer_id']) try: if 'file' in request.FILES and request.FILES['file'] != "": policy_file = request.FILES['file'] # check extension if validateFileExtension(policy_file) is True: if (getFileExtByFileName(policy_file) == 'xlsx' or getFileExtByFileName(policy_file) == 'xls') and data['sheet'] is None: return CustomeResponse(request=request, comment=SHEET_NAME_CHECK, message=SHEET_NAME_CHECK, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) policy_file_name = file_save_by_source(request, policy_file_path, policy_file) if policy_file_name != "": data['file_name'] = policy_file_name else: return CustomeResponse(request=request, comment=COULD_NOT_UPLOAD_FILE, message=COULD_NOT_UPLOAD_FILE, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST,validate_errors=1) try: upload_path = settings.MEDIA_URL+policy_file_path+'/'+policy_file_name try: pd_data = pd.read_excel(upload_path).columns except Exception as e: print(e) return CustomeResponse(request=request, comment=BULK_DATA_NOT_FOUND,message=BULK_DATA_NOT_FOUND, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1) except Exception as e: #print(e) return CustomeResponse(request=request, log_data=json.dumps(str(e), cls=UUIDEncoder), message=SOMETHING_WENT_WRONG, data=json.dumps({}, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) else: return CustomeResponse(request=request, comment=ALLOWED_POLICY_FILES, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=ALLOWED_POLICY_FILES) else: print("->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") return CustomeResponse(request=request, comment=POLICY_FILE_REQUIRED, data=json.dumps({}, cls=UUIDEncoder),status=status.HTTP_400_BAD_REQUEST,validate_errors=1, message=POLICY_FILE_REQUIRED) except KeyError: return CustomeResponse(request=request, comment=KEY_MISSING, message=KEY_MISSING, data=json.dumps({}, … -
Django Rest Framework - Envelope a Paginated Response
I want to wrap an paginated response in an envelope. The Result should look like this. { "data": ["datum 1", "datum 2", "datum 3"], "meta": { "some": "meta", "data": "foo", }, "page": { "total": 12345, "count": 3, "from": 3, "to": 6, "next": "http://example.com?page=2", "prev": "http://example.com?page=0", } } The custom page format can be achieved by inheriting from PageNumberPagination. My question is about passing the Metadata. I do not see any way to pass it to the Pagination except some form of in band signaling. Is there a clean(er) way to do this? -
Define FileField upload_to directory in Django model
I have a model Audiopart with field filename = models.FileField(upload_to=get_upload_path, blank=True) and function for generating upload path def get_upload_path(instance, filename): return os.path.join( 'audio', instance.book_id.folder, filename ) So file uploads to directory (for ex. "audio\mybook\a1.mp3"), that's good. And in database in field "filename" stores path "audio\mybook\a1.mp3". Is any way to save in DB just filename "a1.mp3", without "audio\mybook\"? -
how to use django-redis hset operation in redis cache
I am using django 3.0.4 and python 3.6.9. I have to use hset operation to set some values in redis cache. My try: from django.core.cache import caches cache.set(), cache.get() // these operation are working But I am not able to use hset and hget operation using this library. There is no proper documentation about this in Django official docs. Note: I have referred this (Not A copy) -
django: Use different configuration for test database?
Can I specific a different configuration for the test database? Or alternatives simply use a different user in production?(how to manage that as settings file needs to be updated as well?) The testing requirements for postgresql require in my opinion too many privs like create DB and in my case I also need to create an extension upon db creation which means superuser privileges. -
matching query does not exist django heroku
i have deployed my app to heroku.. But when i try to go to the page, i get this error from log: apps.adminview.models.Templates.DoesNotExist: Templates matching query does not exist. This is from my adminview models, as you can see it is created correctly: ... class Templates(models.Model): description = models.TextField(null=True, blank=True) template_name = models.TextField(null=True, blank=True) isSelected = models.BooleanField(default=False) temp_selected = models.BooleanField(default=False) width_field = models.IntegerField(default=0, null=True) height_field = models.IntegerField(default=0, null=True) image_path = models.ImageField( width_field="width_field", height_field="height_field" ) def __str__(self): return "("+str(self.id)+") " + self.template_name Anyone could help me with this? Thank you!. -
Why can't I display more fields in django?
I'm Trying to develop a social website, and I want to display the bio and blood group of the user on their profile page along with their name and email. While the name and email are being Displayed in the profile page, their bio and blood group are not being displayed although I wrote the same code for them as their name and email. Can anyone please help me out? My models.py : from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' my forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() CHOICES = ( ('type', 'AB+'), ('type', 'AB-'), ('type', 'A+'), ('type', 'A-'), ('type', 'B+'), ('type', 'B-'), ('type', 'O+'), ('type', 'O-'), ) bloodgroup = forms.CharField(widget=forms.Select(choices=CHOICES)) bio = forms.CharField() class Meta: model = User fields = ['username', 'email', 'bio', 'bloodgroup', 'password1', 'password2'] my profile.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> <p class="text-primary">{{ user.bio }}</p> <p2 class="text-info">Blood Group - {{ … -
Django raw sql insert query in triple quotation: Django interprets null values from ajax request data as None column
I am working on a Django/React project. Using DRF, I am throwing an API route for performing SQL queries in my PostgreSQL database. But I am having issues with my current code setup. I have setup my INSERT query in the API as raw queries (using cursor) enclosed in a triple quote multi-line string """INSERT...""", then format my values using string formatting %s. In my API, I capture each request body into a variable. Everything works fine if all request data are filled. But, if it is null, Django obviously assigns None to the variable. Now back to my sql query, Django will treat the null %s as None and as a table column instead of a correct null value, thus throwing a ProgrammingError column "none" does not exist. Here are sample codes: React Frontend const [lastName, setLastName] = useState('') const [firstName, setFirstName] = useState('') const [middleName, setMiddleName] = useState('') const [nameExtn, setNameExtn] = useState('') const [sex, setSex] = useState('') const [civilStatus, setCivilStatus] = useState('') const [bloodType, setBloodType] = useState('') const [height, setHeight] = useState('') const [weight, setWeight] = useState('') const newPersonalInfo = (token, data) => { let endpoint = "/jobnet/api/profile/pds/basic/personal/" let lookupOptions = { method: "POST", headers: { 'Content-Type': … -
How do I add my custom field in django filter?
I am creating an API to return posts on a user profile. The posts can be public, friends only or with custom privacy. Here is my filter: posts = Post.objects.filter( Q(created_by=user, privacy='PUBLIC') | Q(created_by=user, privacy='FRIENDS')| Q(created_by=instance, privacy='CUSTOM', custom_list=requested_by.pk)) Here I want to get the 'friends_only' posts if the requested user is friend of the user whose profile I am showing. Problem is I don't have any relation between Post and Friend. I am using a Friend model as shown below: class Friend(models.Model): sender = models.ForeignKey(UserProfile, related_name="sender", on_delete=models.CASCADE) receiver = models.ForeignKey(UserProfile, related_name="receiver", on_delete=models.CASCADE) accepted = models.NullBooleanField(default=None) and Post model as: class Post(BaseModel, models.Model): PRIVACY_CHOICES = [ ('PUBLIC', 'Public'), ('PRIVATE', 'Private'), ('FRIENDS', 'Friends only'), ('CUSTOM', 'Custom') ] text = models.TextField() image = models.ImageField(upload_to="assets/posts/", null=True, blank=True) created_by = models.ForeignKey(UserProfile, related_name="posts", on_delete=models.CASCADE) privacy = models.CharField(max_length=10, choices=PRIVACY_CHOICES) custom_list = models.ManyToManyField(UserProfile, related_name="post_by_friends", blank=True) liked_by = models.ManyToManyField(UserProfile, related_name="likes", blank=True) My question is how can I filter the Post model by providing my condition in filter is_friend = True -
Unable to import Django model into Python shell
I am recently trying to lean APIs using DJango Rest. I have a model to work with: class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question I want work with the model in the python shell, but whenever I do: from polls.models import Poll in python shell, it shows: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. could anyone help? I am also working on a virtual env -
is Django 'app' equal to 'component' in Angular?
Just started learning Django, as an Angular developer can we say that apps in Django are similar to Angular components ? -
How to override default formats in the data and time fields using Django rest framework?
I tried to override the default formats in time and date fields using the Django rest framework but it's not working. So I added to format and input_format parameter in fields. still, I facing that issue. I refer to the many documentation and many StackOverflow answers. Still, it's not working. anyone can help me. How to solve this error Models.py class Showss(models.Model): show_Time = models.TimeField() Serializer.py class ShowSerializer(serializers.ModelSerializer): show_Time = serializers.TimeField(format='%H:%M:%S', input_formats='%H:%M:%S') class Meta: model = Showss fields = '__all__' settings.py REST_FRAMEWORK = { "TIME_INPUT_FORMATS": [("%H:%M:%S"),] } -
How do I auto login after registration in Django?
So, I'm trying to let the user be automatically logged in as soon as he/she registers. Here's my register function. def register(response): if response.method == 'POST': form = RegisterForm(response.POST) if form.is_valid: form.save() return redirect('/main/inputuserinfo') else: form = RegisterForm() return render(response, 'register/register.html', {'form' : form}) As I mentioned, I'd like to log the user in right after he/she registers, then redirect him/her to '/main/inputuserinfo'. But I have no idea on how I can create it. I very much appreciate your help. :)