Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I solve the NameError of a method of class in Python?
I was working on a small program and I am getting this NameError. Error is below: NameError: name 'create_user' is not defined Following is a short program that I wrote: class UserManager(): email = "abc" def create_user(email, password=None): user = (email, password) def create_superuser(email, password): user = create_user( email, password = password ) return ("User is an admin") password = input("Password: ") User = UserManager() print(User.create_superuser(password)) -
502 Bad Gateway for Django App using nginx+gunicorn+supervisor
I have deployed a flask API in port 81 in CentOS server with nginx+gunicorn+supervisor which works fine. But when I try to deploy a Django app in port 80 I get 502 Bad Gateway Error. The code runs fine when I manually enter the following line: sudo /home/pythonteam/ekyc_web/ekyc_web/bin/gunicorn --bind 0.0.0.0:8001 -w 3 wsgi:application Here are my nginx and supervisor config files nginx.conf file server { listen 81; server_name IP/Domain; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8000; } } server { listen 80; server_name IP/Domain; location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:8001; } } supervisord.conf [program:EKYC] directory=/home/pythonteam/EKYC command=/home/pythonteam/EKYC/ekycenv/bin/gunicorn -w 9 wsgi:app user=pythonteam autostart=true autorestart=true stopasgroup=true killasgroup=true stderr_logfile=/var/log/EKYC/EKYC.err.log stdout_logfile=/var/log/EKYC/EKYC.out.log [program:ekyc_web] directory=/home/pythonteam/ekyc_web command=/home/pythonteam/ekyc_web/ekyc_web/bin/gunicorn --bind 0.0.0.0:8001 -w 3 wsgi:application user=pythonteam autostart=true autorestart=true stopasgroup=true killasgroup=true stderr_logfile=/var/log/ekyc_web/ekyc_web.err.log stdout_logfile=/var/log/ekyc_web/ekyc_web.out.log -
how i access url data in django class based views?
i have view just like this: class addcont(CreateView): form_class = MemberShip template_name = 'site/addcont.html' success_url = reverse_lazy('project:home') def get_form_kwargs(self): kwargs = super(addcont,self).get_form_kwargs() kwargs.update({ 'user':self.request.user.id }) return kwargs def form_valid(self,form,**kwargs): member_ship = form.save(commit=False) member_ship.is_current = True member_ship.project = # get data from slug (url) member_ship.save() return super().form_valid(form) and urls.py: path('addcontribution/<slug:slug>/<int:user_id>',views.addcont.as_view(),name='addContribution') how i can access and get data from urls? see this example http://127.0.0.1:8000/addcontribution/lemon-curse-videos/1 def form_valid(self,form,**kwargs): member_ship = form.save(commit=False) member_ship.is_current = True member_ship.project = lemon-curse-videos member_ship.save() return super().form_valid(form) what should i do? -
celery receives a task but never succeeds | Django Celery Task | Django Send Mail
Trying to send an email and print in the console with django send_mail and email backend. But the celery receives a task "[2020-07-05 13:17:51,144: INFO/MainProcess] Received task: orders.tasks.order_created[41df6169-d988-4073-a956-2c2d6c596fd0]" but never succeeds. I have acctached screenshots of flower dashbaord and celery.py file and in the terminal you can also see that the task was received but after that nothing happens. views.py def order_create(request): # ... # launch asynchronous task order_created.delay(order.id) # ... return .... tasks.py @shared_task(bind=True, max_retries=3, default_retry_delay=2*60) def order_created(self, order_id): """ Task to send an email notification when an order is successfully created. """ try: order = Order.objects.get(id=order_id) subject = f'Order no. {order.id}' message = f'Dear {order.first_name},\n\n'\ f'You have successfully placed an order.'\ f'Your order ID is {order.id}.' res = send_mail( subject, message, 'monday.ent9@gmail.com', [order.email] ) except Exception as exc: raise self.retry(exc=exc) celery.py flower dashboard -
Django urls.py SimpleRouters are not auto discovered by swagger docs
Django DRF Swagger docs are not showing the ModelViewSets API endpoints registered as ROUTERS (not urlpattern). In the example below standard docs (rest_framework.documentation) are showing/documenting this "follow_up" API and swagger docs are not, total skip nothing is showing. For urlpatterns all is good, and below code for 'this_is_showing' is being nicely documented: from urls.py file from rest_framework.documentation import include_docs_urls from rest_framework.routers import SimpleRouter from rest_framework_swagger.views import get_swagger_view from . import views schema_view = get_swagger_view(title=MY APP API') router = SimpleRouter() router.register("follow_up", views.FollowUpViewSet) urlpatterns = [ url(r'^this_is_showing/$', views.SomeView.as_view(), name='view'), url(r'docs/', include_docs_urls( title='MVCR Server API Docs', public=True)), # phys & patient api url(r'^swag/', schema_view), ] What am I missing? -
How to check the related objects status from detail view?
Here I want to check whether the question's answers are already voted by the current user or not . For this I tried like this but I think this will not work. I want to do this for some purposes in the template like one is {% if a_voted %}Voted{% else %}Vote{% endif %}. i did it for question but got stuck while doing for the answers. models class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') ans = models.TextField() user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='user_answers') class AnswerVote(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='answer_votes') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_votes_ans') views class DetailQuestionView(LoginRequiredMixin, View): template_name = 'post_detail.html' def get(self, request, **kwargs): question = get_object_or_404(Question, pk=kwargs['pk']) q_voted = question.question_votes.filter(user=request.user, question=question).exists() answers = question.answers.all() a_voted = [True if answer.answer_votes.filter(user=request.user, answer=answer).exists() else False for answer in answers] context = { 'question': question, 'q_voted': q_voted, 'a_voted': a_voted, } -
from google.oauth2 import service_account ModuleNotFoundError: No module named 'google'
I m trying to run my django app on appengine flexible environment. I m struck on Error. from google.oauth2 import service_account ModuleNotFoundError: No module named 'google' here, i m importing service_account, because i m using google cloud storage. So in settings.py i have to write the code below from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR,'My Project..............001.json') ) It is running fine on local virtual environment but not appengine flex env. Extra:- in requirements.txt Package Version ------------------------ --------- asgiref 3.2.10 astroid 2.4.2 cachetools 4.1.1 certifi 2020.6.20 chardet 3.0.4 colorama 0.4.3 Django 3.0.2 django-storages 1.9.1 google-api-core 1.21.0 google-auth 1.18.0 google-cloud-core 1.3.0 google-cloud-storage 1.29.0 google-resumable-media 0.5.1 googleapis-common-protos 1.52.0 gunicorn 20.0.4 idna 2.10 isort 4.3.21 lazy-object-proxy 1.4.3 mccabe 0.6.1 Pillow 7.2.0 pip 19.0.3 protobuf 3.12.2 psycopg2 2.8.5 psycopg2-binary 2.8.5 pyasn1 0.4.8 pyasn1-modules 0.2.8 pylint 2.5.3 pytz 2020.1 requests 2.24.0 rsa 4.6 setuptools 40.8.0 six 1.15.0 sqlparse 0.3.1 toml 0.10.1 typed-ast 1.4.1 urllib3 1.25.9 wheel 0.34.2 wrapt 1.12.1 Thanks. -
Getting error while api with django rest token authorization page not found
I am trying to access a get method API with the token and I check in the Django rest framework token authentication document and I followed the same, I could not find the error, while login with superuser token is generating successfully and using that token trying to access the API but getting error like mentioned below. if anyone suggests me what is the mistake I made. Not Found: /hello/ 'Authorization : token 52de5dee105764e92d5d6c644919b4aafec489ab' [05/Jul/2020 12:36:15] "GET /hello/%20'Authorization%20:%20%20token%2052de5dee105764e92d5d6c644919b4aafec489ab' HTTP/1.1" 404 2429 Not Found: /hello/ 'Authorization: Token 52de5dee105764e92d5d6c644919b4aafec489ab' [05/Jul/2020 12:39:05] "GET /hello/%20'Authorization:%20Token%2052de5dee105764e92d5d6c644919b4aafec489ab' HTTP/1.1" 404 2419 Not Found: /hello/ "Authorization: Token 52de5dee105764e92d5d6c644919b4aafec489ab" [05/Jul/2020 12:39:43] "GET /hello/%20%22Authorization:%20Token%2052de5dee105764e92d5d6c644919b4aafec489ab%22 HTTP/1.1" 404 2413 #Setting.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # <-- And here ], } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'atoken', ] #URLS.PY from django.contrib import admin from django.urls import path from rest_framework.authtoken.views import obtain_auth_token from atoken import views urlpatterns = [ path('admin/', admin.site.urls), path('api-token-auth/', obtain_auth_token), path('hello', views.HelloView.as_view(), name='hello'), ] #VIEWS.PY class HelloView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): content = {'message': 'Hello, World!'} return Response(content) #While login with superuser got the token mentioned bellow { "token": "52de5dee105764e92d5d6c644919b4aafec489ab" } #so Added in the usr like bellow `enter code here` … -
Django Model Some problems
I'm Shimul, I've been working with Django for about 1 year - but I'm having a project problem with a problem - When I create a model - e.g. class postmodel(models.Model): title = models.CharField(max_length=255) **blog_slug** = models.SlugField(max_length=255,unique=True) Then I migrated the model - after migrating my [blog_slug] I want to delete. When I migrate the model again - and then an error occurs in the database. The error is that the field named [blog_slug] was not found, What can be done to avoid this problem - -
How can a Java client constantly check the data from the api built with Django?
I just built an Django API for my Java code. I already know how to fetch and retrieve data from tables in my PostgreSQL. The thing is that I want to listen for the data and add them constantly. I want to retrieve data constantly when a data is added to the table from the Java code. How is that possible? I did not find any solutions yet.. -
django error message not showing for invalid login
I have used auth to perform login functionality in Django. Whenever I enter the invalid password it does not show error message. '''code''' (login.html) {% extends 'base.html' %} {% block content %} <h2>Log in</h2> <form method="post" > {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% if field.errors %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} {% endif%} </p> {% endfor %} <button type="submit">Log in</button> </form> {% endblock %} **urls.py** from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('ecomm.urls')), path('accounts/', include('django.contrib.auth.urls')), ] -
django thread-safety, request object is overridden
Hello all and thank you for reading. in my application, the request object is needed to be accessed again. test case: two different users two different browsers accessing the same path almost at the same time result: seems like the second request is overriding the request object. is there a way to prevent this from happening? urls.py path('match', view_match.match, name='match'), view_match.py def match(request): print('BEFORE {}'.format(request.user.id)) user = my_app.user.get(request.user.id) print('AFTER {}'.format(request.user.id)) The output BEFORE 1 BEFORE 2 AFTER 2 AFTER 2 Django version: 3.0.7 Thank you very much I appreciate the help. Shay -
/reset_password/ [04/Jul/2020 22:18:44] "GET /reset_password/ HTTP/1.1" 302 0 /
i am not accessing below urls before login please tell me how i access before login because forgot password is always used in login template but in my template is not worked please tell what can i do /reset_password/ [04/Jul/2020 22:18:44] "GET /reset_password/ HTTP/1.1" 302 0 / occcure its issue template.html <a class="m-auto" href="/reset_password">Forgot password</a> urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset.html"), name="reset_password"),** -
How to host a django blog website using AWS Lambda?
I Have Created a blog website using Django and now I want to deploy it on Aws lambda. How can I launch it and get my website running -
Saving Image File in particular directory in Django Rest Framework
I am using Python PIL library in Django Rest Framework for building qr code and saving it to static directory. def generate_qr(self, name): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=15, border=5 ) qr.add_data(name) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') img.save(settings.STATIC_ROOT+"/asset-tags/name.png") return(name+ '.png') But while saving it throws an error saying /usr/app/static/name.png : no file or directory. I am creating new file so how can it find the image in given folder. Any Help will be appreciated. Thanks. -
django rest m2m serialization problem with urls
I am trying to nest the post model inside the serialization of the user model in the django rest framework: example json for post: { "title": "Hi", "image": "http://127.0.0.1:8000/p/IMG.JPG", "created_at": "2020-07-05T02:15:43.181441Z", "description": "asdfjlk", "user": "john", "likes": [], "tags": [] } example json for user: { "firstName": "John", "lastName": "", "username": "john", "profile_picture": "http://127.0.0.1:8000/p/john_profilePicture.jpeg", "pictures": [ { "title": "Hi", "image": "/p/IMG.JPG", "created_at": "2020-07-05T02:15:43.181441Z", "description": "asdflkj", "user": "john", "rings": [], "tags": [] } ] } Nested Serialization Method class UserSerializer(serializers.ModelSerializer): posts = serializers.SerializerMethodField() class Meta: Model: User fields = [... 'posts'] def get_posts(self, obj): posts = obj.user.all() # response = PostSerializer(posts, many=True).data return response The problem lies in the url for the image of the post. In the post view, it shows the full url for the image, whereas in the user view, it only shows the url extension. I've been prefacing my api calls with my localhost which is kind of a bootleg solution but can anybody help with a long term / more practical solution? Thank You! -
Django: How to sort Query set based on another function outside of class
I am trying to sort my Post objects based on a function that gets the score of every object. My score function is: def score(up, down): return up - down And I was trying to get the QuerySet by using: Post.objects.all().annotate(score=score('up','down')).order_by('-score') However, this does not seem to be working. and I get various errors. I researched and it seems you cannot use any functions other than the ones provided by Django Database functions. What would be the most efficient way to do this and how can I achieve the queryset sorted based on each objects score? -
Problem setting up uwsgi with Django website with a virtual env
!!! no internal routing support, rebuild with pcre support !!! uWSGI running as root, you can use --uid/--gid/--chroot options setuid() to 1000 your processes number limit is 5568 your memory page size is 4096 bytes detected max file descriptor number: 2560 lock engine: OSX spinlocks thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on 127.0.0.1:8000 fd 4 uwsgi socket 0 bound to TCP address 127.0.0.1:62444 (port auto-assigned) fd 3 Python version: 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53) [Clang 6.0 (clang-600.0.57)] !!! Python Home is not a directory: /Portenv !!! Set PythonHome to /Portenv Python path configuration: PYTHONHOME = '/Portenv' PYTHONPATH = (not set) program name = '/Portenv/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/Portenv/bin/python' sys.base_prefix = '/Portenv' sys.base_exec_prefix = '/Portenv' sys.executable = '/Portenv/bin/python' sys.prefix = '/Portenv' sys.exec_prefix = '/Portenv' sys.path = [ '/Portenv/lib/python38.zip', '/Portenv/lib/python3.8', '/Portenv/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00000001136aadc0 (most recent call first): <no Python frame> I have tried some other stack overflow answers but I'm very new to Django and some … -
How to sum as Total django admin pemk_0_10 + pemk_11_20 + pemk_21_30 + administrasi + pemeliharaan + denda?
How to sum as Total django admin pemk_0_10 + pemk_11_20 + pemk_21_30 + administrasi + pemeliharaan + denda? enter image description here -
How to use shufflejs in django framework
I'm trying to achieve shuffle animation for my select tag here is my page: my index.html: <div class="container text-dark"> <select class="custom-select" id="type"> <option selected value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <div class="card-deck one"> <div class="card"> <div class="card-body"> <h4 class="card-title">1</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">2</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">3</h4> </div> </div> </div> <div class="card-deck two"> <div class="card"> <div class="card-body"> <h4 class="card-title">4</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">5</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">6</h4> </div> </div> </div> <div class="card-deck three"> <div class="card"> <div class="card-body"> <h4 class="card-title">7</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">8</h4> </div> </div> <div class="card"> <div class="card-body"> <h4 class="card-title">9</h4> </div> </div> </div> This is my scrip tag: <script> $(document).ready(function () { $(".one").show(); $(".two").hide(); $(".three").hide(); $("#type").change(function () { var val = $(this).val(); if (val == "one") { $(".one").show(); $(".two").hide() $(".three").hide(); } else if (val == "two") { $(".one").hide(); $(".two").show(); $(".three").hide(); } else if (val == "three") { $(".one").hide(); $(".two").hide(); $(".three").show(); } }); }); </script> So when I choose the Two value in select tag it will appear 4 5 6 and I want to do the animation like shuffle.js https://vestride.github.io/Shuffle/ Can someone show me how can I do that … -
Loading new data with AJAX if there are new data in Django model fields
View: def user_messages(request): time_now = datetime.datetime.now() user = request.user if request.method == "POST": if 'read' in request.POST: un = request.POST.get('read') Messages.objects.filter(id=un).update(is_read=True) else: sender = request.user receiver_name = request.POST.get('msg_receiver') receiver = User.objects.get(username=receiver_name) msg_content = request.POST.get('msg_content') Messages.objects.create(sender=sender, receiver=receiver, msg_content=msg_content) inbox = Messages.objects.filter(receiver=user).order_by('-timestamp') outbox = Messages.objects.filter(sender=user).order_by('-timestamp') context = {'inbox': inbox, 'outbox': outbox, 'time_now': time_now} return render(request, 'accounts/messages.html', context) Whenever there is a new message in inbox, I want AJAX to update the div with the new message <div id="inbox"> <h6>Inbox</h6> {% for message in inbox %} <ul> <li title="{{ message.sender.username }}"> {{ message.sender.first_name }}: {{ message.msg_content }} {% if message.is_read == False %} <form action="{% url 'messages' %}" method="POST"> {% csrf_token %} <button value="{{ message.id }}" name="read">mark as read</button> </form> {% endif %} {% if message.is_read == True %} <button onclick="reply()">Reply</button> {% endif %} </li> <small>-{{ message.timestamp }}</small> <hr> </ul> {% endfor %} </div> I loop through the inbox and print out the messages. But whenever there is a new message, the user has to refresh the page see the changes. I want Ajax to update only the div asynchronously. How I use Ajax to see if the inbox.count has increased and if increased, then add the new data to the list? -
How to convert pdf file into json file using python
I have a task I have a pdf file which contain 6 pages invoice including tables now I want to convert that pdf file into json . I don’t have idea how to do that and this is my interview task -
Django forms: initial field value not working with @staticmethod vs unbound function
I'm using Django 2.2 forms and I'm trying to understand why the below two snippets have different behaviors. Why does passing a @staticmethod to initial in the form field (snippet A) not have the same result as passing an unbound function (snippet B)? Snippet A: class BankUpdateForm(forms.Form): @staticmethod def yesterday(): return date.today() - timedelta(days=1) from_date = forms.DateField(initial=yesterday) to_date = forms.DateField(initial=date.today) Snippet B: def yesterday(): return date.today() - timedelta(days=1) class BankUpdateForm(forms.Form): from_date = forms.DateField(initial=yesterday) to_date = forms.DateField(initial=date.today) Snippet B will work as intended and show the correct initial field value. Snippet A will only print the function's str. -
How to save calculated form field values in Django model
In my Django application I am doing background calculations on form field values as available at the start of the form rendering. The form field values derive from a number of models. The values so calculated are displayed in the form in an html table that are basically comprised of numerical values. I have a table in the database where the above calculated values are to be saved. Is there a way in Django to directly post the calculated values in the model? I have been checking on SO and various other resources on the net but can't get anything on the issue. Following is a screen grab of the form to make the situation clear: The values that I want to save in the model are encircled (in red). -
django admin page customization
This is what I did in my models.py folder class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField() digital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True, blank=True) def __str__ (self): return self.name But am getting this as my result in my django admin page And I want to display the products by their name PRODUCT Product object (2) Product object (1) 2 products