Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it possible to create a api which a particular website can access only and no other website can access it?
Let me explain in detail I've 2 servers hosted and one of them for Back-end and other is for Front-end. Back-end server : 127.0.0.1:8000 (just for explaining) Front-end server : 127.1.1.1:9000 User requests UI from Front-end server and if he wants to create an account on my website he needs to send POST request to 127.0.0.1:8000/create-account/ and this works fine but if I open console of other website or make use of Postman, I'm able to achieve the same results. So I want to prevent this thing and only allow anyone to create account from my website only. Methods which I've tried I've used windows.location() and sent it to server and then verify if domain name matches. But in this method everyone can just pass it simply via fetch() I've used allow only IP address, But if I push my website in production Other visitors get 403 error. I develop back-end with help of Django and rustlang -
Django Access Foreign Key Tables Data in InlineFormset
I am using formsets to create a feedback page but I am not able to access foreign key table values in django template. I have this models below that are for a feedback system. Models.py class FeedbackForm(amdl.AagamBaseModel): feedback_form_id = models.AutoField(primary_key=True) subject_teacher = models.ForeignKey(MapMySchoolUserSubject, models.DO_NOTHING) feedback_form_date = models.DateField() feedback_form_status = models.BooleanField() class Meta: db_table = 'feedback_form' class FeedbackFormQuestion(amdl.AagamBaseModel): feedback_form_question_id = models.AutoField(primary_key=True) feedback_form = models.ForeignKey('FeedbackForm', models.DO_NOTHING) feedback_question = models.ForeignKey('FeedbackQuestion', models.DO_NOTHING) class Meta: db_table = 'feedback_form_question' class Feedback(amdl.AagamBaseModel): feedback_id = models.AutoField(primary_key=True) feedback_form_question = models.ForeignKey('FeedbackFormQuestion', models.DO_NOTHING) map_myschool_user_standard_section = models.ForeignKey(MapMySchoolUserStandardSection, models.DO_NOTHING) feedback_rating = models.IntegerField() feedback_comments = models.TextField(blank=True, null=True) feedback_date = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'feedback' class FeedbackQuestion(amdl.AagamBaseModel): feedback_question_id = models.AutoField(primary_key=True) question_text = models.TextField() feedback_question_credit = models.IntegerField() question_group = models.ForeignKey('FeedbackQuestionGroup', models.DO_NOTHING) class Meta: db_table = 'feedback_question' class FeedbackQuestionGroup(amdl.AagamBaseModel): feedback_question_group_id = models.AutoField(primary_key=True) question_group = models.TextField() description = models.TextField() class Meta: db_table = 'feedback_question_group' The Feedback model is the main model where the rating of feedback is given by students. As the rating is per question there is one row per question that is in foreign key with the FeedbackFormQuestion which is the relationship (many-to-many) between FeedbackForm and FeedbackQuestion that make up a feedback form. Other models are just for analysis and graphs. This is the view … -
How to prevent user login from multiple devices in Django REST?
I am working on a subscription based platform, where user buys a subscription plan and then he/she can get access to the content. Tech Stack: React in Frontend and Django REST Framework in Backend I want to find a way to prevent user login from multiple devices or multiple tabs from a browser. There should be one session per user. I have researched about it but could not find anything suitable. Some are using session authentication scheme to store the user session and adding middlewares and prevent multiple logins. But i am using JWT token Authentication scheme. I am storing JWT token in front end. How should i implement in such case which not having session authentication? Any leads? -
Django TypeError: force_authenticate() missing 1 required positional argument: 'self'
Test case setUp() that first creates a user and the try's to force authenticate the user but a wired error occurs... TypeError: force_authenticate() missing 1 required positional argument: 'self' class PrivateUserApiTest(TestCase): """ Test API that require authentication """ def setUp(self): self.user = create_user( email="test@test.com", password="testpass", name="testName" ) print(self.user) self.client = APIClient self.client.force_authenticate(user=self.user) # <-- -
How to convert a string to python object?
So, I have got this piece of string: [{'id': 45, 'user_id': 2, 'cart_item_id': UUID('0fdc9e75-3d9c-4b89-912b-7058e1233432'), 'quantity': 1}] Note:It is python string str And i want to convert it to list of dict in python Can anyone please help me out -
Postman with Django REST and AngularJS
I have a Django REST framework API which is accessed with a AngularJS frontend. If I had a Django App called models, I could simply request its data in Postman simply by sending a GET to the URL localhost:8000/models/. But since everything is routed through AngularJS and every Django App has multiple Controllers, that doesn't work. The GET on localhost:8000/models/ returns just the index.html, the entry point of the AngularJS. So how can I achieve to send GET, POST etc. to the API? BTW: I managed to get an X-CSRFToken by sending POST to http://localhost:8000/api/auth/login/ with login and password keys ans values. That URL was included in the Django Projects urls.py as urlpatterns. No such urlpattern for the App models, or any other Django App, though. -
How to hit external API's to check if a user is autthorized to take action and use permission_required decorator in Django
We have a external system where we are defining the roles and permissions on the basis of the user id. We want to customize the permission_required decorator to hit that external system to check for permissions. Is it possible to do in Django?? Let's say I have a API(isAuthorized) which takes user id, token and action which the user is trying to perform and returns True or False depending the user has access or not for that specific action. I am using Django 3.1.7 -
How to include a dropdown query into a HttpResponse view
I would like to convert to excel contents of a model after passing a filter from the dropdown selection . Here is the view. def ConvertToExcelView(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow([('name'), ('adm'),('form'),('stream') ]) for member in Marks.objects.filter(student__school__name=request.user.school).values_list('student__name', 'student__adm', 'student__klass__name', 'student__stream__name': writer.writerow(member) response['Content-Disposition'] = 'attachment; filename="members.csv"' return response Is there a way I can incorporate this into the view???? query = request.GET.get('view_classes') if query: queryset = (Q(student__klass__name__icontains = query)) return render(request,'students_marks.html',all_mark_results) Please ask for more clarifications incase I'm not clear with this. -
I am begginer in Djangio forgive me if it is stupid question. What actually do order_by() in Django?
I read documentation they are saying order_by() return a new QuerySet. but When I print Question.objects.order_by('-pub_date') where Question is class name in models.py it print queryset object. I am confused that is order_by() actually return a new Queryset or aactually execute a query ? please explain what is happening internally during execution in Django in below code? from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) and also please explain line 4 in above code? -
DataFrame to django response
i want my processed dataframe save as .xlsx or .csv. i have tried to fix this error but its notworking. i have follow this step form : Pandas CSV to Django Response but my output getting like this: my query: my view donwload: `def convert(fuzz): df1 = pd.DataFrame(fuzz) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=export.csv' df1.to_csv(path_or_buf=response) print (df1) return response` my view pandas process: def fuzzy(excel): df=pd.DataFrame(excel) NameTests = [name for name in df["NameTest"] if isinstance(name, str)] data = {'Matching': [], 'Score': []} for Name in df["Name"]: if isinstance(Name, str): match = process.extractOne( Name, NameTests, scorer=fuzz.ratio, processor=None, score_cutoff=50) if match: data['Matching'].append(match[0]) data['Score'].append(match[1]) df1 = pd.DataFrame(data) return df1 -
django did not return a httpresponse object when using ajax
ValueError: The view question.views.add_comment didn't return an HttpResponse object. It returned None instead. im using ajax to send data to my view, the goal is to post comments without refreshing the page my View def add_comment(request): if request.method == 'POST': comment_form = CommentCreateForm(request.POST) print(comment_form) if comment_form.is_valid(): user_comment = comment_form.save(commit=False) result = comment_form.cleaned_data.get('content') user = request.user.username user_comment.author = request.user user_comment.save() return JsonResponse({'result': result, 'user': user}) my template $(document).on('click', '#newcomment',' #newcommentinner', function(e){ e.preventDefault(); let button = $(this).attr("value"); // let slug = $('#commentform').attr("data-question") let csrftoken = $('[name="csrfmiddlewaretoken"]').val(); let patch = "{% url 'question:add_comment' %}" console.log($("#commentform").serialize()) var placement = "commentform" if (button == "newcommentform") { var placement = "newcommentform" } $.ajax({ type:'POST', url:patch, data:{ 'data': $("#" + button).serialize(), 'csrfmiddlewaretoken': csrftoken, }, cache:false, success: function(json) { console.log(json) }, error: function(xhr, errmsg, err){ } }) }); -
How to add environment variables to command line in Django runserver
I would appreciate it if you could help me. I want to add some environment variables to command line as following: python manage.py runserver myvar=myvar_value I use the in views.py request function, In fact the servers do different works I want to make a flag with to determine if the is equal 1, runs some functions in views file and if is 0, runs some other function. -
CSS can't read static files in Django Project
Django can't upload images from the static folder.Here is the file with settings settings.py `STATIC_URL='/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'static') ]` File where i call statics styles.css ` {% load static%} .bg-holder-login{ background-image: url("{% static '/img/plot1.png' %}"); width: 100%; height: 100px; background-repeat: no-repeat; background-size: cover; }` In html template i call static files and everything works easily -
Can I filter choices for Django models.ForeignKey?
I have a ManyToMany relationship with models Vehicle and Accounts and an associative entity of Assignment which gets the PKs of both table as FK. Now the Accounts table has a field of is_driver which takes a Boolean value because by default all accounts are commuters but some can be a Driver. Is there a way to set my model to filter only Accounts with is_driver == True? -
Django get_user_model().objects.create() password is not getting hashed
I have a test case which first creates a user and then try's to authenticate the created user with Django authenticate() method but looks like password is not getting hashed and therefore it fails to retrieve the token... ill share any code related to this section that i think had to do something with the process. Custom user model manager: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """ Creates and saves a new user """ if not email: raise ValueError("Users must have an email address.") user = self.model( email=self.normalize_email(email), **extra_fields ) # Set password this way makes a hashed password user.set_password(password) user.save(using=self._db) return user app/settings.py: AUTH_USER_MODEL = "core.User" # 'User' is the name of custom user class user/serializers.py: class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ["email", "password", "name"] extra_kwargs = { "password": { "write_only": True, "min_length": 5, } } def create(self, validated_data): """ Create a new user with encrypted password and return it """ user = get_user_model().objects.create( email=validated_data["email"], name=validated_data["name"] ) user.set_password(validated_data["password"]) print(f"from serializer: {user.password}") user.save() return user and at last my test case, user/tests/test_user.py: #... def test_create_token_for_user(self): """ Test that a token is created for the user """ payload = { … -
Saving a model with inlines in Django
This seems like a very easy problem, but I really can't figure out what's going on. I have some problems understanding the saving process on the Django admin site. This is the situation, simplified as much as possible: models.py import uuid from django.conf import settings from django.db import models class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=settings.IS_DEV) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Order(BaseModel): [various properties and functions] class Article(BaseModel): [various properties and functions] class PaymentOperation(BaseModel): [various properties and functions] admin.py from django.conf import settings from django.contrib import admin from models import Order, Article, PaymentOperation class BaseModelAdmin(admin.ModelAdmin): readonly_fields = ['created', 'modified'] if not settings.IS_DEV: readonly_fields.append('id') class ArticleInline(admin.TabularInline): fields = ['id', ...] readonly_fields = ['id', ...] can_delete = False extra = 0 max_num = 0 [more code] class PaymentOperationInline(admin.TabularInline): fields = ['id', ...] readonly_fields = ['id', ...] can_delete = False extra = 0 max_num = 0 [more code] class OrderAdmin(BaseModelAdmin): readonly_fields = BaseModelAdmin.readonly_fields + [...] fieldsets = [...] inlines = [ArticleInline, PaymentOperationInline] [more code] class ArticleAdmin(BaseModelAdmin): readonly_fields = BaseModelAdmin.readonly_fields + [...] fieldsets = [...] [more code] This is the main structure, but I'm not really sure if it's enough to generate the problem. I didn't want to clog the question with … -
Display the signup time of the User ( member since )
I am building a Blog WebApp and I am trying to implement a Feature. What i am trying to do :- I am trying to display the Date or Time of user's signup (Like stack overflow does (member since 2 months)) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') time = models.DateTimeField(auto_now_add=True) @receiver(post_save,sender=User) def post_save_create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance,time=instance) I tried to search but i found nothing. Any help would be much Appreciated. Thank You in Advance -
Is there a way to show a webpage while the application is building?
I would love to know if there's a way to show a webpage when I push changes to heroku to prevent this huge page reload every time and to prevent problems that could be caused. -
How to create a square image with Pillow?
I have a Django project which allows images to be uploaded. Currently, the uploaded images are only being resized and compressed. Also, because I am using an S3 server for static files the images are first saved in a memfile and then in the server. The problem is that the current setup only works in production when using the S3 server. When running the app locally, the images do not get resized or compressed. I would also like to remove the current resize method and instead fill the image to be a square. For example, if the height is larger than the width, fill the image width with white padding to create a square and resize it to 500x500. Any transparent areas on the image should also be filled with a white background. If anyone can help me with this, I would really appreciate it. models.py def save(self, *args, **kwargs): instance = super().save(*args, **kwargs) self.product.save() return instance if self.image: memfile = BytesIO() img = Image.open(self.image) if img.mode != 'RGBA': img = img.convert('RGBA') if img.width > 700: ratio = img.width / img.height height = 700 / ratio output_size = (700, height) img.thumbnail(output_size, Image.ANTIALIAS) img = ImageOps.exif_transpose(img) img.save(memfile, optimize=True, quality=90, format='PNG') default_storage.save(self.image.name, … -
i am making a test module in Django and it is giving giving me different value all the time
I am making an application to take the online test I am using python random function this is my code. un is the key d is the dictionary of sampling and un. the answers which I am adding from my keyboard are getting stored in a proper order but when I am checking it with the right answers the sampling data is getting changed in the backend on its own and again I am seeing sampling data on my terminal this is my link to Github repository def test(request): n=request.user if Profile.objects.filter(username=n).first().marks == 0: #only those can give test who has 0 marks que=Cpp.objects.all() questions=[] un=['a','b','c','d','e','f','g','h','i','j'] for q in que: if q not in questions: questions.append(q) else: continue sampling = random.sample(questions, 10) print(sampling) correctAnswers=[] for j in sampling: correctAnswers.append(j.ans) print(sampling) d = dict(zip(un,sampling)) answers=[] if request.method=="POST": answers.append(request.POST['a']) answers.append(request.POST['b']) answers.append(request.POST['c']) answers.append(request.POST['d']) answers.append(request.POST['e']) answers.append(request.POST['f']) answers.append(request.POST['g']) answers.append(request.POST['h']) answers.append(request.POST['i']) answers.append(request.POST['j']) marks=0 print(answers) for i in range(0,10): if correctAnswers[i]==answers[i]: marks=marks+1 Profile.objects.filter(username=n).update(marks=marks) return redirect("profile") return render(request,"code/test.html",{'questions':d}) i am printing my sampling twice and it is showing me two different values can anyone help me with this that why is the value of my sampling changing?? this is my HTML file: <form method="POST"> {% csrf_token %} {% … -
HTTP method’s error: 401 (Unauthorized) on React & Django(DRF)
I completed manipulating authentication with token by referring this article, and then I’m trying to create a crud function such creating post, displaying posts, etc… . However, I have an error when I fetched the url which displays posts(IE, fetching url I defined as “index” method on views.py of app for auth manipulation), I have 401 error even though I can access by using url of the backend without any error even on terminal. I found some config codes which are related to authentication and permission for manipulation of authentication with token on settings.py causes this error, since when I delete these codes, the crud function works. But obviously authentication function no longer works (index method on views.py retrieve only token, another informations are filled blank) by this solution. //fetch method on frontend try{ const res = await fetch(`${base_url}/accounts/current_user/`,{ method:'GET', headers:{ Authorization:`JWT ${localStorage.getItem('token')}` } }) const data = await res.json(); setUsername(data.username); console.log(data) }catch(err){console.log(err)}; //fetch posts on frontend const getProblems = async() =>{ const res = await fetch(base_url+'/problems/index'); const data = await res.json(); setProblems(data); } //views.py on app for auth manipulation @api_view(['GET']) def get_current_user(request): serializer = GetFullUserSerializer(request.user) print(serializer.data) return Response(serializer.data) //settings.py(related to auth, cors): REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), … -
“Invalid data. Expected a dictionary, but got list.” How to send a post request to JSON field?
I am using the Django rest and React. In the backend I get this data with this serializer: class PreviewSerializer(serializers.Serializer): rules = serializers.JSONField() Views.py: data = request.data serializer = PreviewSerializer(data=data) if serializer.is_valid(): rules = serializer.data['rules'] I test it in the postman, with a JSON [{"a":"b"},{"b":"c"}] and it works well. In the frontend I need to make a POST request with the data now: fetch(`endpoint`, { method:'POST', headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', "Accept": "application/json", }, body: JSON.stringify(rules) }) rules data I send is a list with objects (I get it from redux store) ~ looks like: [{id: 1, name: "demo", type: "Google Analytics", schema: {…}, runBeforeImports: false}] so I stringify it and looks like: [{"id":1,"name":"demo","type":"Google Analytics","schema":{"field":"custom_label_0","value":"jknm","query":"","mongoQuery":""},"runBeforeImports":false}] But it gives error: ["Invalid data. Expected a dictionary, but got list."] How I might configure data to be posted properly? Indeed why it is expecting a dictionary when it is a JSON field? Thanks in advance -
django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") Always getting this error
Windows 10 Dockerfile:- FROM python:3.8 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apt-get install default-libmysqlclient-dev RUN pip install -r requirements.txt RUN pip install mysqlclient RUN mkdir /app WORKDIR /app COPY ./app /app docker-compose.yml :- version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app - /tmp/app/mysqld:/run/mysqld command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8002" depends_on: - db links: - db db: image: mysql:8 restart: always ports: - "3306:3306" environment: - MYSQL_DATABASE='music' - MYSQL_USER='music' - MYSQL_PASSWORD='music' - MYSQL_ROOT_PASSWORD='rootmusic' volumes: - /tmp/app/mysqld:/var/run/mysqld - ./db:/var/lib/mysql requirements.txt :- Django>=2.1.3,<2.2.0 djangorestframework>=3.9.0,<3.10.0 pymysql mysqlclient==1.4.6 django-mysql==3.4.0 Django-settings.py :- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ.get("MYSQL_DATABASE"), 'USER': os.environ.get("MYSQL_USER"), 'PASSWORD': os.environ.get("MYSQL_PASSWORD"), 'HOST': 'db', 'PORT': '3306', } } when using the command docker-compose up i am getting the error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") Used in django host - '127.0.0.1' also tried using 'localhost'. But same error is comming again. Just using Docker to run my django-mysql appliation. Not sure if sockets are involved and how. I have been looking for a solution since last two days. Kindly help. -
django How to optimize sql statement?
my code: i use django orm dynasty_li = ["USA", 'US', 'JPN'] data={} for dynasty in dynasty_li: data[dynasty]=People.objects.filter(dynasty=dynasty).order_by("-create_time")[:100] if use sql dynasty_li = ["USA", 'US', 'JPN'] data={} for dynasty in dynasty_li: sql="select * from people group by dynast='{dynast}' order by create_time DESC" data[dynasty]=query(sql) I think it should be group by, but it is impossible to extract the top N from the bottom based on each dynasty I improved my sql statement SELECT a.id,a.name,a.dynasty,a.create_time FROM people a left OUTER join people b on (a.dynasty=b.dynasty and a.id<b.id) GROUP BY a.id HAVING count(*)<4 ORDER BY dynasty,create_time But the execution time is relatively long, there are only less than 10,000 pieces of data, and the execution time is 10s How to be more pythonic? -
paginate_queryset() got an unexpected keyword argument 'view'
while running the below code getting the "paginate_queryset() got an unexpected keyword argument 'view'" error after adding pagination views.py class UsersList(ListAPIView,LimitOffsetPagination): permission_classes = (permissions.IsAuthenticated, IsVerified,permissions.IsAdminUser) @swagger_auto_schema( query_serializer=PaginationSerializer, responses={status.HTTP_200_OK: UserOutputSerializer(many=True)}, operation_id="list_users", ) def get(self, request, *args, **kwargs): qs = User.objects.filter(is_verified=True, is_active=True).order_by('user_name') results = self.paginate_queryset(qs, request, view=self) users = UserOutputSerializer(results, many=True) return self.get_paginated_response(users.data) urls.py path('list_users/',UsersList.as_view(),name='list_users'),