Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'DeferredAttribute' object is not callable django1.2.5
I'm working on a simple django project, but i face this problem that you see below so, i want a solution because i really got tired I expect the output of that code to be numberone but the actual output is this error : TypeError at /db/ 'DeferredAttribute' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/db/ Django Version: 2.1.5 Exception Type: TypeError Exception Value: 'DeferredAttribute' object is not callable Exception Location: /home/mohammed/Desktop/New life programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa/Abdullah/views.py in db, line 16 Python Executable: /usr/bin/python3 Python Version: 3.6.8 Python Path: ['/home/mohammed/Desktop/New life ' 'programming/python/pythonDjano/Filecorse/NewDjango/MohammedAlaa', '/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/mohammed/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 31 Aug 2019 11:13:18 +0000 #views.py from django.shortcuts import render from django.http import HttpResponse from .models import Product def Home(request): return HttpResponse('Welcome, Mohammed Alaa :)') def htm(request): return render(request,'htm.html',{'hello':"hello Mohammed Abo Alaa again:)", 'days':['wed', 'fri', 'thru'] }) def others(request): return HttpResponse('Welcome, Mohammed Alaa :) form others') def db(request): dat = '' p1 = Product(namee='numberone', pricee=500,Type='m') p1.save() dat = Product.namee() return HttpResponse(dat) -
How copy folder in django custom commands
I want to copy a folder after my command calls. I create my custom command in the following path myapp/management/commands/createshop.py and my code from django.core.management.base import BaseCommand, CommandError import os, shutil class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('mobile', type=str, help='Mobile') parser.add_argument('shopname', type=str, help='Shop Name') parser.add_argument('password', type=str, help='password') def handle(self, *args, **options): src = 'E:/myproject/sample/' dest = 'E:/myproject/shops/shop-' + options['shopname'] shutil.copytree(src, dest) self.stdout.write(self.style.SUCCESS('shop "%s" created successfully' % options['shopname'])) the folder will not copied also there is no error. Am I wrong? how can I call a python command in django custom commands? -
How to import and define choice fields?
how to define and import choice field how can i define choice field in models.when i was try below im getting errorNameError: name 'GENDER_CHOICES' is not defined. from django.db import models from django.contrib.auth.models import class Userprofile(models.Model): gender = models.CharField(max_length=10,choices=GENDER_CHOICES, blank=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) -
Using PATCH or PUT deletes the object - DJango
I'm using Django Rest as my BE server, and have created a Chat object that holds messages and participants, and I manage to create objects as expected using the POST method and get these objects using the GET method - so far so good. But when I try to update the participants by doing a PUT or PATCH requests on the object with different participants, the object just gets deleted (another GET request does not bring that object back as a result). models.py (the messages have foreign key to the Chat object but this is not the issue so i will leave it out): class Chat(models.Model): participants = models.ManyToManyField(Profile, related_name='chats', blank=True) def __str__(self): return str(self.id) serializers.py: class ChatSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="chat_app:chat-detail", lookup_field='id') participants = serializers.HyperlinkedRelatedField(many=True, view_name="user_app:profile-detail", queryset=Profile.objects.all(), lookup_field='id', required=False) messages = MessageSerializer(many=True, required=False, read_only=True) class Meta: model = Chat fields = ('id', 'messages', 'participants', 'url') read_only = ('id', ) views.py: class ChatViewSet(BaseModelViewSet): serializer_class = ChatSerializer permission_classes = (permissions.IsAuthenticated, ) lookup_field = "id" def get_queryset(self): return self.request.user.profile.chats Any ideas? -
FileNotFoundError when opening a file on AWS S3
I use the S3 private repository to store media files. Presigned URLs are used to access files for users. Files are correctly saved and opened by the generated link. models.py class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) filedata = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) created = models.DateTimeField(auto_now_add=True) filetype = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) url_link = models.URLField(default=None, blank=True, null=True) Now I need to make an endpoint on which I will give the necessary file by model id. views.py def view_pdf(request, pk): pdf = get_object_or_404(Documents, pk=pk) file_data = open(pdf.url_link, "rb").read() return HttpResponse(file_data, contenttype='application/pdf') urls.py url('pdf/(?P<pk>\d+)$', view_pdf, name='view_pdf'), When I try to open a file, I get an error FileNotFoundError at /api/v1/files/pdf/90 [Errno 2] No such file or directory: 'https://mysite.s3.amazonaws.com/media/private/fd2a6f39857a4b4799135b41b4fad313.pdf?AWSAccessKeyId=AKIAZTR5wSDFer6YOWPPL5IFOS&Signature=lBUSDRbSAkUOfXzCeA3sc6OpX3PBqo%3D&Expires=15679330600' But then I copy the link and paste it manual in browser all open fine -
class_forms on the same page
I have a class PostCreateView and I want to be able to recognize 2 form_class at the same page When I have tried it said, tupple can not be called when I write like this: form_class = PostForm, CommentView Views.PY class PostCreateView(FormView, LoginRequiredMixin, CreateView, CommentForm): form_class = PostForm model = Post # category = Category.objects.all() def post(self, request, *args, **kwargs): form = PostForm() data = Post.objects.all() Models.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ["Name", "Content"] widgets = { I expect my 2 forms appear on the page without no issue. But only one appears and renders: -
How to check unique while update on django
"I am stuck in this, i have successfully check validation of unique while user is register, but during his profile update how i check the unique email during the update" Anyone can help me on this ? -
adding extra field ('city') to UserRegisterForm Django
When new users register I want to store: fields = ['username', 'email', 'password1', 'password2', 'city'] so I extended UserRegisterForm by adding 'city' to the form. It renders fine in the template and save everything except 'city'. There is no even column 'city' in the new users profile when checking by admin page so looks like its not creating one. I found few similar posts and been following Doc but that didint help. Have tried many different ways but will post two I think mostly sensible ones. EXAMPLE 1 - *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() city = forms.CharField(required=True) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'city'] def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.city = self.cleaned_data['city'] if commit: user.save() return user - *views.py* ... from django.contrib.auth.forms import UserCreationFormfrom from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() print('VALID') username = form.cleaned_data.get('username') messages.success(request, '{} Your account has been created! You can now Log In'.format(username)) return redirect('/login/') else: form = UserRegisterForm() context = { 'form': form, } return render(request, 'users/register.html', context) @login_required def profile(request): return render(request, 'users/profile.html') - … -
The django login screen does not transition from loading to page
I changed the database to postgresql with django. And after migrete, I can't log in when I check my login screen. I also tried to log in to the management screen, but I could not log in. Both have stopped during loading. The user is created by executing createsuperuser. And the user was created when checking the database. I deleted the migrete file or restarted the server, but it doesn't work. If you enter the wrong password, "Your username and password didn't match. Please try again." There is no display of errors, etc., and the server is loading even after stopping. I also did the following command find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete python manage.py makemigrations python manage.py migrate -
maximum recursion depth exceeded while calling a Python object when creating child page of parent page
This is my child code page {% if post.page_set.all %} {% for child in post.page_set.all %} <div> <h5> <a href="" style="margin-left:10px;">{{child.title}}</a>&nbsp;<a href="{% url 'add_child_page' pk=child.pk %}"><i class="fa fa-plus" style="font-size:15px ;color:#2F4F4F;"></i></a> </h5> {% include "makerobosapp/child_code.html" with post=post %} </div> {% endfor %} {% endif %} And this is my homepage where i want to show child post title {% block content %} {% for post in posts %} <div class="post-content"> <h3> <a href="{% url 'post_detail' pk=post.pk %}">{{post.title}}</a>&nbsp;<a href="{% url 'add_child_page' pk=post.pk %}"><i class="fa fa-plus" style="font-size:20px ;color:#2F4F4F;"></i></a> </h3> <p>{{post.content| safe |linebreaksbr}}</p> <div class="date"> <p>published date: {{ post.published_date }}</p> </div> {% include "makerobosapp/child_code.html" with post=post %} {% endfor %} {% endblock %} -
i also download the numpy from pypi umpy atribute error
Traceback (most recent call last): File "C:/Users/Waqar Ahmad/PycharmProjects/Generic_summary/generic_base_summary.py", line 2, in import numpy as np File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core__init__.py", line 97, in from . import _add_newdocs File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core_add_newdocs.py", line 6839, in """.format(ftype=float_name))) File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core\function_base.py", line 467, in add_newdoc _add_docstring(getattr(new, doc[0]), doc[1].strip()) AttributeError: type object 'numpy.float16' has no attribute 'as_integer_ratio' Process finished with exit code 1 -
form.save wont save data and no rows added to database
I have a model as model below: class ProductLeastDiscountLog(LoggableModel): product = models.ForeignKey(ProductType, verbose_name='a', on_delete=models.CASCADE, related_name='least_discount_log') n_weeks = models.IntegerField('a', null=True, blank=True) buy_price = models.BigIntegerField('a a', null=True, blank=True) future_sell_price = models.BigIntegerField('a a', null=True, blank=True) mean_sell_prediction = models.IntegerField('a a a a a', null=True, blank=True) discount_factor = models.FloatField('a a a', null=True, blank=True) least_discount = models.FloatField('a a a', null=True, blank=True) I want to use a model to add objects of this model to DB: class LeastDiscountForm(BaseModelForm): class Meta: model = ProductLeastDiscountLog fields = ('n_weeks','buy_price', 'future_sell_price', 'mean_sell_prediction', 'discount_factor') but after calling form.save db is still empty: def action_view(self, http_request, selected_instances): if http_request.method == 'POST': form = self.modelForm(http_request.POST, http_request.FILES, instance=selected_instances[0], http_request=http_request) print('let me see if form is vaid') if form.is_valid(): print('form is valid') form.save() form = None else: form = self.modelForm(instance=selected_instances[0], http_request=http_request) return render(http_request, 'manager/actions/add_edit.html', {'form': form, 'title': self.form_title}) -
The best way to run Spark application within Django project in Docker Swarm mode
I have a Django project in which I am supposed to exploit Apache Spark ML library. Moreover, I am using Docker in Swarm mode because I want to utilize a cluster of nodes for gaining better performance. What is the best architecture for my goal? I have thought about using pyspark within my Django project, and on request, connect to Spark master container and submit the intended application. The problem is I have not found anything about this approach; thus, I'm not sure if it's possible at all. Another solution might be submitting application using docker exec command. The problem arising here is that I do not have just one python file but a large scale Django project. It doesn't seem feasible too. -
can i do some preprocessing on image and use it whitout save changes?
Recently I wrote a code which reads image from an object storage. then I do some simple image processing on image. but i don't want to save changes on main image, also i don't want to copy image because of performance reasons. I just want to send manipulated image to a vies function in django in order to open it as a data file. is it any way to do this job? this is my function's schema. def watermark_image(image_name): # do some image processing on input image # cv2.imwrite(image_name, image) return image and this is a part of my function view: if request.method == 'GET': new_image = watermark_image(local_path + object_name) # image_data = open(??? , "rb").read() image_data = open(new_image , "rb").read() return HttpResponse(image_data, content_type="image/png") i don't know what should to wirte insetead of this line : image_data = open(new_image , "rb").read() -
Django Front End
I have a few questions. I'm learning Django and I have mastered a large part of BACKEND. Is classic Django with css html and JS sufficient for nice pages? What do I need to master to make these pages look good (html, css, js)? Is it necessary to learn django rest framework and some JS framework (REACT, ANGULAR)? Thank you for your help. -
Advanced filtering in Django ORM. Need a one query solution instead of recursion
I have a question regarding advanced filtering in Django ORM. MODEL: class ClubAgentPlayer(models.Model): club = models.ForeignKey(Club, on_delete=models.CASCADE, related_name='club_agent_players') agent = models.ForeignKey(User, on_delete=models.CASCADE, related_name='agent_club_players') member = models.ForeignKey(User, on_delete=models.CASCADE, related_name='member_club_agents') created_at = models.DateTimeField(auto_now_add=True) Goal is like this: For example I have initial agent_id = 15 and I need to find all agents id of agents that are connected to the initial agent. I know how to do it via recursion. On the small sample is fine but on a bigger sample it would slow down DB drastically. So that I need to pull all data in 1 query. Resulting query set should be [ 15, 19, 22] – agent_id How to read chart: Initial agent has id= 15 (yellow). Members with id [18, 19, 27, 28] attached to this agent(orange). One of this members is an agent himself, number 19 (green). On a next level we have initial agent 19 (green) and he has members [22, 31, 32] attached to him. One of them is an agent himself 22 (red). Next level agent ID=22, his members are [37, 38, 39] . None of them is an agent. So we done here. At the end I need to have id of all connected … -
How to configure ajax request with jquery in django?
So i was doing a django project by following a youtube video.And I got this error "Forbidden (403) CSRF verification failed. Request aborted." everytime when i submit any data in my sign-up.html file. Then i realize i did not configure ajax correctly.So i search online and saw the django documentation of ajax.i made some changes in my html code. still, it did not solve my problem. I am still getting the same result.What is my mistake here.Did i made any mistake while configuring ajax? Its been a while since i am stuck in this problem. Thank you for your time My sign-up.html file: {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Instapic</title> <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}"> </head> <body> <div class="login-clean"> <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div style="display: none" id="errors" class="well form-error-message"></div> <img src="{% static 'assets/img/logo.jpg' %}"> </div> <div class="form-group"> <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4"> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6"> </div> <div class="form-group"> <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6"> </div> <div class="form-group"> … -
I Download Also Numpy From Pypi but its con't work
Traceback (most recent call last): File "C:/Users/Waqar Ahmad/PycharmProjects/Generic_summary/generic_base_summary.py", line 2, in import numpy as np File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy__init__.py", line 142, in from . import core File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core__init__.py", line 97, in from . import _add_newdocs File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core_add_newdocs.py", line 6839, in """.format(ftype=float_name))) File "C:\Users\Waqar Ahmad\Anaconda3\envs\website\lib\site-packages\numpy\core\function_base.py", line 467, in add_newdoc _add_docstring(getattr(new, doc[0]), doc[1].strip()) AttributeError: type object 'numpy.float16' has no attribute 'as_integer_ratio' Process finished with exit code 1 -
Django: Ho to set user name in session and get the user name in other view methods
I'm new to Python and Django. I'm using PHP form for login mechanism and once the login is successful, I'm sending the user name to Django application to carry on with other operations but I'm stuck in finding a best way to store the user name in session so that it can be used in other view methods Below are some of my tries which failed: 1) Storing the user name in a global variable and access throughout the application but when another user login from their machine, user name gets changed in my machine. 2) Storing the user name in Django DB session but another user logs in with different user, it's showing the old user only. 3) I tried storing in the cache but still, it's not working. DB session handler: It works fine when I access in sessionHandler method but it throws key error when i try to access in login method. def sessionHandler(request): userName = request.GET.get('uname') request.session['user'] = userName print("current logged in user: " + request.session['user']) return JsonResponse({'Response': 'success'}) def login(request): uname = request.session.get('user') UserName = {"Name": uname} return render(request, 'login/login.html', UserName) My use case is that any user who logs in their own machine and … -
Django - Inherit CustomQuerySetMixins
I have a class namend CustomQuerySetMixin and I would like a class to inherit from that class. In this class, I want to create a custom Queryset. Here's my code: CustomQuerySetMixin: class CustomQuerySetMixin(models.Model): class Meta: abstract = True objects = CustomQuerySetManager() class QuerySet(CustomQuerySet): pass CustomQuerySetManager and CustomQuerySet: class CustomQuerySetManager(models.Manager): """A re-usable Manager to access a custom QuerySet""" def __getattr__(self, attr, *args): try: return getattr(self.__class__, attr, *args) except AttributeError: # don't delegate internal methods to the queryset if attr.startswith('__') and attr.endswith('__'): raise return getattr(self.get_query_set(), attr, *args) def get_queryset(self): return self.model.QuerySet(self.model) def get_querySet(self): return self.get_queryset() def get_query_set(self): return self.get_queryset() class CustomQuerySet(models.QuerySet): def __getattr__(self, attr, *args): try: return getattr(super().__class__, attr, *args) except AttributeError: return getattr(self.model.QuerySet, attr, *args) My model: class Article(""" Some other mixins """, CustomQuerySetMixin): # Some fields class QuerySet(CustomQuerySetMixin.QuerySet): def my_awesome_function(self): return self When I now try to call that function (using this code -> Article.objects.my_awesome_function()) it throws this error: TypeError: Cannot create a consistent method resolution order (MRO) for bases TaggedQuerySet, CastTaggedQuerySet I know this has to do because in my CustomQuerySetMixin I'm inheriting from models.Model. When I remove this, it throws this error: AttributeError: 'CastTaggedManager' object has no attribute 'not_voted' -
django storages - save absolute path in database?
How can I save absolute paths (like /var/files/.. , or s3://bucket/path) in a table containing file field? Django by default uses MEDIA_ROOT as a prefix, and store relative paths. I use the django-storages package for S3 backend. -
What is the correct way to install and run a django project?
I am very new to Python and Django and trying to find the correct way to set up a basic Django project to start learning it. Following are my Python, Pip, and Django version details - Commands to find the versions - python --version pip --version python -m django --version I used the following commands to create a project and a module inside it - django-admin startproject djangoCrud cd djangoCrud/ python manage.py startapp api I was able to run the project using the following command - python manage.py runserver Then I read that I will need a virtual environment for further development, for which I used the following commands to create and run it - pip install virtualenv virtualenv env . env/bin/activate But when I tried to run the manage.py file after activating the environment, It throws an error - ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? But I can run the manage.py without activating the environment Can someone please guide me what's wrong and how do I fix this? -
I implemented Email settings on settings.py, but it doesn't work when I submit the form
here is my settings.py from .email_info import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = EMAIL_HOST EMAIL_HOST_USER = EMAIL_HOST_USER EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD EMAIL_PORT = EMAIL_PORT EMAIL_USE_TLS = EMAIL_USE_TLS DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I define values on email_info.py EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my id' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_PORT = 587 here is my view.py def sendemail(request): if request.method =='POST': name = request.POST.get("name", "") email = request.POST.get("email","") contact = request.POST.get("contact","") date = request.POST.get("date_time","") address = request.POST.get("address","") subject = '시연 신청(' + name + ')' message = '이름: ' +name + '\n' + '연락처: ' + contact + '\n' + '시연 날짜: ' + date + '\n' + '주소: ' + address + '\n' + '이메일' + email send_mail(subject, message, settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER]) messages.success(request, 'Thank you') return redirect('index') I tested send_mail module at console, and it works, but when I submit the form, it doesn't work. >>> send_mail('test', 'test', 'iuncehiro@gmail.com', ['iuncehiro@gmail.com']) 1 Where do I need to fix some settings? -
Django look css images into wrong directory
I have following settings for static files STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_proj'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root') In the css file I do this #mydiv{ background-image: url('/img/myimg.png'); } And my directory structure project root - static_my_proj - css - img - js I can see from network tab that it looks for the image in static/css/img/myimg.png. However, if I do this then it works. How can I make it without using ../ at the beginning? #mydiv{ background-image: url('../img/myimg.png'); } -
How do I write a Django query that does date math when executed as PostGres SQL?
I'm using Django and Python 3.7. I'm writing a Django query to be run on a PostGres 9.4 db, but having trouble figuring out how to form my expression wrapper so that I add a number of seconds (an integer) to an existing date column. I tried the below hour_filter = ExtractHour(ExpressionWrapper( F("article__created_on") + timedelta(0, F("article__websitet__avg_time_in_seconds_to_reach_ep")), output_field=models.DateTimeField) ), ) but I'm getting the error unsupported type for timedelta seconds component: F Any ideas how I can rewrite my ExpressionWrapper to do the date math inside the PostGres query?