Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - 'User' object has no attribute 'payments'
I have been spending quite a lot of time trying to understand this error I got. From models.py class Company(models.Model): name = models.CharField(max_length=100, unique=True, default="") email = models.CharField(max_length=100, unique=True, default="") password = models.CharField(max_length=100, unique=True, default="") bsb = models.IntegerField(default=0) account = models.IntegerField(default=0) sign_up_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Payment(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="payments") name = models.CharField(max_length=100, unique=True, default="") bsb = models.IntegerField(default=0) account = models.IntegerField(default=0) created_date = models.DateTimeField(auto_now_add=True) paid_date = models.DateTimeField(default=datetime.now() + timedelta(days=36500)) status = models.IntegerField(default=0) and from serializers.py from rest_framework import serializers from .models import Payment, Company class PaymentSerializer(serializers.ModelSerializer): company = serializers.ReadOnlyField(source='company.name') class Meta: model = Payment fields = ['company', 'name', 'bsb', 'account', 'created_date', 'paid_date', 'status'] class CompanySerializer(serializers.ModelSerializer): payments = serializers.PrimaryKeyRelatedField(many=True, queryset=Payment.objects.all()) class Meta: model = Company fields = ["name", "email", "password", "payments", "bsb", "account", "sign_up_date"] As you can see, I have included the related_name as "payments" for company attribute in Payment class. But when I go to http://localhost:8000/bill_payer/resources/company I got the following error: AttributeError: 'User' object has no attribute 'payments' I have verified that my Company class do indeed have the payments class through manage.py shell. Any idea? I am new. Here's views.py in case it is important: class PaymentList(APIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, request): payments … -
Got AttributeError when attempting to get a value for field `email` on serializer `UserViewSerializer`
I am trying to attribute Likes to the articles but i don't know why i am getting this error. Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class LikeUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='userlikes') profile = models.ForeignKey(User,on_delete=models.CASCADE,null=True) created = models.DateTimeField(auto_now=True) Serializers.py class UserViewSerializer(serializers.HyperlinkedModelSerializer): userlikes = UserSerializer(many=True) class Meta: model = User fields = ('id','email','username','userlikes',) I defined everything right,no typo or so. -
how to execute Python script including Argparse, CV2 on web?
I am creating a webpage by using this face swap Python code. But I don’t know how to execute the command on the web application created with Django. https://github.com/wuhuikai/FaceSwap Here is a concept of the webpage: enter image description here To execute the python script, need to type like this as explained. python main.py --src imgs/test6.jpg --dst imgs/test7.jpg --out results/output6_7.jpg --correct_color However, wondering if it is possible to execute on the web application with a trigger button. Thank you for your help in advance. #! /usr/bin/env python import os import cv2 import argparse from face_detection import select_face from face_swap import face_swap if __name__ == '__main__': parser = argparse.ArgumentParser(description='FaceSwapApp') parser.add_argument('--src', required=True, help='Path for source image') parser.add_argument('--dst', required=True, help='Path for target image') parser.add_argument('--out', required=True, help='Path for storing output images') parser.add_argument('--warp_2d', default=False, action='store_true', help='2d or 3d warp') parser.add_argument('--correct_color', default=False, action='store_true', help='Correct color') parser.add_argument('--no_debug_window', default=False, action='store_true', help='Don\'t show debug window') args = parser.parse_args() # Read images src_img = cv2.imread(args.src) dst_img = cv2.imread(args.dst) # Select src face src_points, src_shape, src_face = select_face(src_img) # Select dst face dst_points, dst_shape, dst_face = select_face(dst_img) if src_points is None or dst_points is None: print('Detect 0 Face !!!') exit(-1) output = face_swap(src_face, dst_face, src_points, dst_points, dst_shape, dst_img, args) dir_path = … -
django channels async consumer blocking on http request
I have the following async consumer: class MyAsyncSoncumer(AsyncWebsocketConsumer): async def send_http_request(self): async with aiohttp.ClientSession( timeout=aiohttp.ClientTimeout(total=60) # We have 60 seconds total timeout ) as session: await session.post('my_url', json={ 'key': 'value' }) async def connect(self): await self.accept() await self.send_http_request() async def receive(self, text_data=None, bytes_data=None): print(text_data) Here, on connect method, I first accept the connection, then call a method that issues an http request with aiohttp, which has a 60 second timeout. Lets assume that the url we're sending the request to is inaccessible. My initial understanding is, as all these methods are coroutines, while we are waiting for the response to the request, if we receive a message, receive method would be called and we could process the message, before the request finishes. However, in reality, I only start receiveing messages after the request times out, so it seems like the consumer is waiting for the send_http_request to finish before being able to receive messages. If I replace await self.send_http_request() with asyncio.create_task(self.send_http_request()) I can reveive messages while the request is being made, as I do not await for it to finish on accept method. My understanding was that in the first case also, while awaiting for the request, I would be … -
Store a list of values in Django keys with a single submit
I can get the values of all fields as below in the views.py if request.method == 'POST': teacher_get = request.POST.get('teacher') department_get = request.POST.get('department') subject_get = request.POST.get('subject') semester_get = request.POST.get('semester') answers = [v for q, v in request.POST.items() if q.startswith('question_')] Now I want to store these values in the Student class which most of its fields are foreign key. class Student(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) semester = models.ForeignKey(Semester, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=1) For example, a student login to the form page and start answering questions, at the end when he/she clicks submit button, All questions have their answer. In other words, after submission I have for example 15 Student objects which each object belongs to a specific question. My form looks like this: <form action="{% url 'question'%}" method="POST"> {% csrf_token %} <select name="teacher"> {% for teacher in teacher %} <option value="{{ teacher.name }}">{{ teacher.name }}</option> {% endfor %} </select> </div> <div> <select name="department"> {% for department in department %} <option value="{{ department.name }}">{{ department.name }}</option> {% endfor %} </select> </div> <div> <select name="semester"> {% for semester in semester_choices %} <option value="{{ semester.0 }}">{{ semester.1 }}</option> {% endfor %} … -
How commit transaction.atomic()
I have view with atomic transaction. @transaction.atomic def my_view(request): try: with transaction.atomic(): conn = connect_to_db conn.execute("some raw sql query") #do some another stuff except Exception as e: #handle errors # here need to commit transaction I'm not sure, how can I commit transaction, after try catch block. Any help appreciate -
how to restrict other people than admin to access specific url in django?
hello guys so i have this django project which has 2 application inside it one is the website that only admin have access and one is call back server, currently right now only the feature inside of website i know to restrict people to access it because i make condition where it need to login and is an admin to access it, but the login page i have not done anything to restrict other people to access it so i need you guys help how can i restrict other people that not admin to access the login page? , here's my code for now hope it help. view.py (dashboard) def loginscreen(request): if Account.objects.count() <= 0: return redirect("setup_superadmin") elif request.user.is_authenticated and request.user.gambar != '': return redirect("mikrotikadmin/dashboard") else: if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) if user is not None: get_account_admin = Account.objects.get(username=username) user.is_online = True user.save() login(request,user) if get_account_admin.gambar != '': return redirect("mikrotikadmin/mikrotiklogin") else: messages.error(request,"account blum lengkap") return redirect("admin_info") else: messages.error(request,"account tidak ada") return redirect("/") else: return render(request,"login.html") url.py (dashboard) urlpatterns = [ path("",views.loginscreen), path("logout",views.logoutscreen,name="logout"), path("setup_superadmin",views.setup_superadmin_server,name="setup_superadmin"), path("admin_account",views.akun_admin,name="admin_account"), path("admin_info",views.halaman_isi_info_admin,name="admin_info"), path("akun_manager",views.akun_manager,name="akun_manager"), ]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Detecting Django/Python None value inside JS code
Actually, it is a question of best practice and elegance. Imagine I have JS code like this: my_js_func() { let var_coming_from_backend = {{ some_var || '' }} if (...) { } } What is the most proper way to check some_var is None? Currently, I am doing that this way: let var_coming_from_backend = {{ some_var|default:'' }} if (var_coming_from_backend == '') { } But it seems like junk code to me. -
Django: Insert image to PostgreSQL (PgAdmin4)
Im currently working an e-shop. So my idea is to store images with Django models in PgAdmin4. As i saw in older posts methods like bytea('D:\image.jpg') and so on just converts the string constant to its binary representation. So my question is if there is a newer method to store the actual image, or if it is possible to grab the image via a path? models.py image = models.ImageField(null=True, blank=True) PgAdmin4 INSERT INTO product_images( id, image) VALUES (SERIAL, ?);// how to insert image? -
exclude option in selectField (ForeignKey)
i have a field in my model: myuser = models.ForeignKey(MyUsers, on_delete=models.SET_NULL, blank=True, null=True) in database table "MyUsers" - 10 users. How to exclude some of this 10 users from choise option in form (by id or name)? -
Django order by postgresql range type
Which would be the best way to use django ORM 2.2 to apply this PosgreSQL query? SELECT * FROM my_table ORDER BY lower(range_column); Thanks a lot -
Django Rest Framework JWT: How to change token expiration message
When the JWT token that I'm sending is expired, I'm getting this message... { "detail": "Signature has expired." } Now, I want to change the response with my custom message, like... { "message": "token has expired.", "data": null, "status": 401 } I tried it to do within APIView, but It's not working. -
How to return single object from queryset in Django Rest Framework?
I want to retrieve the title_picture of a Story. When i retrieve the Story I get the the result as a list. However as there is only a single title picture per Story, I want the object directly and not stored as part of a list. // Current Output "title_picture": [ { "id": 9, "isTitlePicture": true, "file": "/media/story_media/1_Bm1qVip.jpeg" } ] // Target Output "title_picture": { "id": 9, "isTitlePicture": true, "file": "/media/story_media/1_Bm1qVip.jpeg" } class StoryRetrieveSerializer (serializers.ModelSerializer): story_media = serializers.SerializerMethodField('get_story_media') class Meta: model = Story fields = ('title', 'story_media') def get_title_picture (self, story): qs = Story_Media.objects.filter(story=story.id, isTitlePicture=True) serializer = Story_Media_Serializer(qs, many=True) return serializer.data My first attempt was to take out the many=True. However than the title picture is not fetched any more and all the data is null. I'am happy for any hint. -
Websocket/REST API - which of them for a large request scenario?
I know that they are two different things and technical approaches, but consider this scenario: i have a third party application that will interface with my own application and every 5 minutes has to push to my services a large JSON (about 3/4MB). My application consists in a Python-Django web application with Gunicorn serving WSGI requests and DAPHNE serving ASGI connections, in front of that i've placed a NGINX as reverse proxy. In the web application i've created basically two endpoints: REST Insert API endpoint Websocket endpoint that exposes a receiver (in order to insert data In my test environment, i've seen that when i try to push the JSON to the websocket endpoint, many times the websockets will get closed with this error message: "HTTP_UPDATE_FAILED Error (-104): Wrong HTTP Code" The WS endpoint in NGINX is configured as below: location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_connect_timeout 15s; proxy_send_timeout 3600s; # ws will open for 1 hour proxy_read_timeout 3600s; proxy_buffers 512 256M; proxy_buffer_size 256M; proxy_pass http://daphne_server; #DNS resolved by internal docker dns server } In order to circumvent the problem, i've tried to reduce the websocket message payload many times up to … -
flake8 ignoring configuration files
Steps I installed flake8: pip install flake8 Created a tox.ini file: [flake8] exclude = */migrations/* Then I ran flake8: flake8 Expected results Only get errors outside migration directories. Actual results I still get errors inside migration directories. When I run the command manually, it works: flake8 --exclude=*/migrations/* I get other errors, but not inside migration folders. Any idea what I could be doing wrong? As far as I can tell I'm simply following the documentation word by word. I'm surprised I didn't find many other threads about this problem. -
how to limit user access to url? [closed]
hello guys so i have this problem i want to ask so i have this django project that inside of it have 2 apps one is the website that only network admin have access and one is a call back server that handle the request of user (because i need the data of user to used in website admin), and because i am still confused to restrict people to get inside the admin login page url other people that's not admin still can access the admin login page, so i want to ask how to restrict people to access this login page? thanks :) -
Display sub menu with django cms
I try to display sub menu with the tag "show_sub_menu". I have many sub menus : Menu1 sub menu1 sub menu2 Menu2 sub menu3 sub menu4 ... If I am on a page contained in menu1 or its sub-menus, I want to display a list with : sub menu1 sub menu2 If I am on a page contained in menu2 or its sub-menus, I want to display a list with : sub menu3 sub menu4 So, I created a new template : {% extends "base.html" %} {% load cms_tags menu_tags sekizai_tags %} {% block title %}{% page_attribute "page_title" %}{% endblock title %} {% block content %} <div class="row"> <div class="col-8"> {% placeholder "content" %} </div> <div class="col-4"> {% show_sub_menu 1 %} </div> </div> {% endblock content %} It's works when I open in the page Menu1 or Menu2 but not when I open the pages "sub menu*". I try with : {% show_sub_menu 0 %} or {% show_sub_menu -1 %} but it doesn't work, nothing is displayed. -
Error in migrations after removing image field and upload_to_path method
I had a field called image in my model. image = models.ImageField(upload_to=get_profile_pic_upload_path) I created the migration for the same and applied it. After a few more migrations and changes, I decided to remove the field. I was able to do that and apply the migration as well. Now I realized I missed deleting the extra upload_to method. When I remove the method from my codebase, I am getting the following error from my initial migration. AttributeError: module 'users.models' has no attribute 'get_profile_pic_upload_path' I see that there a reference to my upload_to method, which is failing. Now as the field has been removed all together this should not happen. What is the best way to handle this? -
Django/Mezzanine - admin: Add "Save and add another to current parent" button
What would be the best way to add the functionaliy to "Save and add another file to current parent" to the admin in Django (/Mezzanine)? So far I've found the template to add the button, but am unsure of how to add a function to do this - while I've reviewed django.contrib.admin.ModelAdmin, as an amateur developer I'm unsure of the best practice for making the tag. I currently think that the basic principles should be to make/import a custom tag that does the below: save() on the item that's currently being created reload the page with the addition of "?parent={{original.pk}}" to the URL. ...but I am unsure on the best way to do this. Any advice would be greatly appreciated! Rich -
Fitler DateTimeField with DateFilter in django-filter
I have a model which has create_date, update_date, release_date DateTimeField. I wish to have the filter to filter these DateTimeField with DateFilter. Here is one way I can do that: class ProductFilter(django_filters.FilterSet): create_date = DateFilter(field_name='create_date', lookup_expr='date') create_date__gt = DateFilter(field_name='create_date', lookup_expr='date__gt') create_date__lt = DateFilter(field_name='create_date', lookup_expr='date__lt') create_date__gte = DateFilter(field_name='create_date', lookup_expr='date__gte') create_date__lte = DateFilter(field_name='create_date', lookup_expr='date__lte') update_date = DateFilter(field_name='update_date', lookup_expr='date') update_date__gt = DateFilter(field_name='update_date', lookup_expr='date__gt') update_date__lt = DateFilter(field_name='update_date', lookup_expr='date__lt') update_date__gte = DateFilter(field_name='update_date', lookup_expr='date__gte') update_date__lte = DateFilter(field_name='update_date', lookup_expr='date__lte') release_date = DateFilter(field_name='release_date', lookup_expr='date') release_date__gt = DateFilter(field_name='release_date', lookup_expr='date__gt') release_date__lt = DateFilter(field_name='release_date', lookup_expr='date__lt') release_date__gte = DateFilter(field_name='release_date', lookup_expr='date__gte') release_date__lte = DateFilter(field_name='release_date', lookup_expr='date__lte') You may see that things get repetitive. Is there any way to encapsulate the logic? P.S. I know I can use Meta.fields like: class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = { 'create_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], 'update_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], 'release_date': ['date', 'date__gt', 'date__lt', 'date__gte', 'date__lte'], } but the filter name will become create_date__date instead of create_date. -
what are the configuration in settings.py to send e-mail using Django from business outlook email (eg .. - office@test.com )
i have been trying to send email using this configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_PORT = 25 EMAIL_HOST_USER = 'office@test.com' EMAIL_HOST_PASSWORD = '********' EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = 'office@test.com' but I am getting error saying that OSError at /product_detail/test/ [Errno 101] Network is unreachable -
dynamically viewing and downloading pdf in django
i want to view and download pdf of some invoices in my ecommerce web.i gave my view function here.unfortunatly i couldnt display any data which i viewd dynamically. def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('reportpdf.html') return HttpResponse(pdf, content_type='application/pdf') class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf=render_to_pdf('reportpdf.html') response=HttpResponse(pdf, content_type='application/pdf') filename="report%s.pdf"%("12341231") content="attachment; filename='%s'" %(filename) response['Content-Disposition']=content return response -
I Want to access the variable of a if statement in the function .Python
def Home(request):#django if request.method == 'POST': city = request.POST.get('search') print(city) URL = f'http://api.openweathermap.org/data/2.5/weather?q={city} -
DJANGO - How to JSON response a dict?
After a lot of process, I got a result of a number _price = 45000. I want to response in a format like this: [{"_price": "45000.0"}] I did this result = {"_price":_price} return json.dumps(result) I got this AttributeError: 'str' object has no attribute 'get' result = list({"_price":_price}) return JsonResponse(result, safe = False) Got this [ "_price" ] result = list({"_price":_price}) return HttpResponse(result) Got this _price -
Django - Why cannot loop through the retrieved model objects?
I'm new to Django, I wanted to loop through all the objects stored in database, but I'm not able to. I don't really understand the problem, I searched the web for problems related, but I still couldn't find any solution, could anyone please help me? The problem encountered is : 'Resume' object has no attribute 'seek' Here is some of the code, I believe the problem is in the first 3 lines: resumes = Resume.objects.all() for i in range(len(resumes)): file = docx2txt.process(resumes[i]) text = [file, jobdesc] cv = CountVectorizer() count_matrix = cv.fit_transform(text) percentage = cosine_similarity(count_matrix)[0][1] * 100 percentage = round(percentage, 2) If I used for i in resumes.iterator(), the problem encountered would be: QuerySet indices must be integers or slices, not Resume. Resume model: class Resume(models.Model): resume = models.FileField('Upload Resumes', upload_to='resumes/', blank=True, null=True) name = models.CharField('Name', max_length=1000, null=True, blank=True) email = models.CharField('Email', max_length=1000, null=True, blank=True) mobile_number = models.CharField('Mobile Number', max_length=255, null=True, blank=True) education = models.CharField('Education', max_length=255, null=True, blank=True) skills = models.CharField('Skills', max_length=10000, null=True, blank=True) company_name = models.CharField('Company Name', max_length=10000, null=True, blank=True) college_name = models.CharField('College Name', max_length=10000, null=True, blank=True) designation = models.CharField('Designation', max_length=10000, null=True, blank=True) experience = models.CharField('Experience', max_length=10000, null=True, blank=True) uploaded_on = models.DateTimeField('Uploaded On', auto_now_add=True) def __str__(self): return self.name