Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can python class variable be used as both class and instance variable?
I am very confused after working with Django Framework and the model of Djano Framework class User(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_address = models.EmailField(max_length=50, unique=True) def __str__(self): return self.first_name As we can see first_name, last_name, and email_address are created as class variables but in the dunder str() method they are used with the self as instance variables So my question is wheter in Python variables declared as class variables can be used as both "Class Variables" and "Instance Variables". Thank You in advance and thanks for reading my question. -
Django rest ModelViewSet create fails
I have two models with following relationship: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) ... # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) I have defined serializers as following (I am directly creating a User while creating a Reader for a specific Library): class ReaderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') email = serializers.CharField(source='user.email') password = serializers.CharField(source='user.password') class Meta: model = Reader #fields = '__all__' depth = 1 fields = ('id', 'username', 'email', 'password', 'phone', 'address', 'dob', 'which_library') def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) user.set_password(user_data['password']) user.save() reader = Reader.objects.create(user=user, **validated_data) return reader And I am writing a ModelViewSet as following: class ReaderViewSet(viewsets.ModelViewSet): serializer_class = ReaderSerializer def get_queryset(self): readers = Reader.objects.filter(which_library=self.kwargs.get('library_id')) return readers URL: router.register(r'readers/(?P<library_id>[0-9]+)', ReaderViewSet, base_name='readers') my GET call is successful and I get all the readers in a specific Library. I am doing a POST call with following JSON data: { "username": "three", "email": "three@gmail.com", "password": "5647", "phone": "836365", "address": "sample6 address", "which_library": "2" } and also by removing "which_library" but both give me error: IntegrityError at /api/readers/2/ (1048, "Column 'which_library_id' cannot be null") What am I doing wrong? -
How to safely count dictionary keys in python
I'm writing a django application where I will get a dictionary from the user that can be of variable size. I want to have a limit for how big the dictionary can be, i.e. how many (key, value) pairs it can hold. I want it to be no bigger than 200. I suspect that if I do: if len(user_dict)>200: raise ValidationError("dict has too many (key, value) pairs") python will have to count the whole dict. If the dict is huge, because of a malicious user, this will eat unnecessary processing power. Or does the dict keep track of how many objects it holds, meaning len(user_dict) is a simple lookup operation? What is the best way to solve this problem? I was thinking something like: i=0 for key in user_dict.keys(): i += 1 if i>200: raise ValidationError("dict has too many (key, value) pairs") -
Django - How to work with `auth_permission` Model
Django make its own permission models, like auth_permission. I want to add new permission doing this by code. How I normally add something to a table from .models import Model mdl, succeeded = Model.objects.get_or_create( field=value, field=value ) mdl.save() But to call the auth_permission Model, I have to import the model first. Only I can't find how this Model is called. So do one of you guys know what to import to call this Model? -
How to make frontend structure on Django?
How to build ordinary frontend structure using Django (Python 3)? What should I do to place, for example, gulp, Bower, SASS, React.js here? -
Django - error but no ValidationError at Imageupload, if no image is choosen
first of all, I'm new to django.I try to implement an avatar to my user model. Everything is working as expected so far, apart from one little thing: If i want to upload a new avatar to my profile, there is a "chosse File" and a "Upload" (submit) button. If I choose a file and press the Upload button, the avatar changes correctly and everything is fine. But when I don't choose a file and press "Upload", the Validation error: "Please select a file" pops up. If I don't use a default avatar in my model it works. But when I have activated the default avatar in my model , there is no "Please select a file" pop-up and following error occurs: Thank you for your help ! error Exception Type: FileNotFoundError at /account/aaa/avatar Exception Value: [Errno 2] No such file or directory: 'avatars/default_avatar.png' My default_avatar.png is located at src/media/avatars/defaultt_avatar.png The problem occurs in this line: File "/.../src/account/forms.py" in save28. im = Image.open(self.cleaned_data['image']) models.py class Profile(models.Model): def get_image_path(instance, self): return 'avatars/{}/{}'.format(instance.user, instance.user) ... image = models.ImageField( _('avatar'), storage=OverwriteStorage(), upload_to=get_image_path, default=os.path.join("avatars", 'default_avatar.png') ) views.py class ChangeAvatarView(UpdateView): model = get_user_model() template_name = 'account/change_avatar.html' form_class = ChangeAvatarForm slug_field = "username" slug_url_kwarg = 'username' … -
How can I do Server Side Rendering of reactJS app with Python/Django as backend?
I have created the reactjs app using create-react-app and have used react-route-dom for routing. I have used Python/Django Rest Framework for the backend. Now I am facing issues like I can't post every page with the different previews and titles on social media platforms. Also, I have read the CSR(Client Side Rendering) is not good for SEO. -
Django .save(using='...') correct database name
My Django settings.py contains the following: DATABASES = { 'default': { # several settings omitted 'NAME': 'myproject', 'HOST': 'localhost', }, 'other': { 'NAME': 'other', 'HOST': 'else.where', } } I now want to fetch some objects from the other DB and save it to default like so: things = Thing.objects.using('other').raw('SELECT code,created FROM other.otherapp_bigthing WHERE created>...') # 'code' is a unique string in other and PK of the Thing model for t in things: t.save(using='default') This gives me ProgrammingError: (1146, "Table 'other.myapp_thing' doesn't exist") which is a correct observation, however, by the documentation of the using parameter I expected the records to be saved to myproject.myapp_thing. Why is the database name still taken from the other configuration when I explicitly advised it to use default? -
django unable to connect mysql server on aws
my django version is 2.0.1, i would like to connect with mysql. Database which is located on a amzon ec2 I get this error when I'm running the Django server : this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'graph', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'hostname', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } -
Django new session for each browser tab
I have a problem with Django session and i have no idea how to solve it. Basically i store some data in the session dictionary in one view function, and calculate some thing in a second function using the values from the first view. Now if someone opens up two tabs, fills in the data in one and submits it, fills the second tab and submits it, the session dictionary will be the same for both tabs. I hope i phrase myself right. Simple explanation: def a(request): request.session["q"] = request.POST.get('q') def b(request): while True: print(request.session["q"]) So lest assume function a is rendering an index page, and getting a value from there. On a button push in this index page function b is called. Now if i open two tabs, input 1 in to the index page and submit i ll see a lot of 1 in the terminal. Now i open up another tab, input 2, submit, the printing will change. What i would like to do is to keep separate sessions (separate information to come in and go out) from my server to the user on different tabs of a browser. I am sorry if i phrase myself wrong, … -
How can i use SearchFilter in django with mongoengine?
thanks for Rahul Gupta's help i can use filter in django with mongodb,but the search is not worked,can u help me to see what's wrong with my code? I mean the url http://127.0.0.1:8000/pokemon/?id=009 is ok. but url http://127.0.0.1:8000/pokemon/?search=009 is not worked, how can i use the search function in django while i'm using mongoengine # views.py from rest_framework_mongoengine.generics import * from rest_framework import filters class PokemonViewSet(MongoModelViewSet): """ API endpoint that allows pokemon to be viewed """ queryset = Pokemon.objects.all() serializer_class = PokemonSerilizer my_filter_fields = ('id', 'name_cn', 'name_en') filter_backends = (filters.SearchFilter,) search_fields = ('=id', 'name_cn', 'name_en') def get_kwargs_for_filtering(self): filtering_kwargs = {} for field in self.my_filter_fields: # iterate over the filter fields field_value = self.request.query_params.get(field) # get the value of a field from request query parameter if field_value: filtering_kwargs[field] = field_value return filtering_kwargs def get_queryset(self): queryset = Pokemon.objects.all() filtering_kwargs = self.get_kwargs_for_filtering() # get the fields with values for filtering if filtering_kwargs: queryset = Pokemon.objects.filter(**filtering_kwargs) # filter the queryset based on 'filtering_kwargs' return queryset -
Url could not be found in Django
I have an ajax call as follows: function getBodyHeights(seats_id) { $('[data-body-length]').html(gettext("Body length")); $('[data-weights]').html(gettext("Weights")); $('[data-wheel-drive]').html(gettext("Wheel drive")); $('[data-transmission]').html(gettext("Transmission")); $('[data-trim]').html(gettext("Trim Level")); $.ajax({ type: 'GET', url: '/master/heights/' + seats_id + '/', success: function (data) { removeActiveClass(); $('#content').html(data) }, error: function (error) { $('#body-heights-error').removeClass('hidden').html(error.responseText) } }) } In root folder I have: urlpatterns = [ .... url(r'^master/', include('master.urls')), ... ] In the master folder in urls.py I have it as follows urlpatterns = [ .... url(r'^heights/(\d+)/$', views_data.body_heights, name='heights'), ... ] But when I try to execute the ajax call on click i get an error: -
Most efficent way for get last n records for each model
i got 3 models like class Business(models.Model): name = models.CharField(max_length=30) ... class Dude(models.Model): ... class PhoneNumber(models.Model): dude = models.ForeignKey(Dude) date = models.DatetimeField() business = models.ForeignKey(Business) I want to get last 3 phone numbers of each dudes and this is how i getting it; response=list() for dude in Dude.objects.all(): temp_dude = dict() temp_dude['name_label'] = str(dude.name) temp_dude['phones'] = list() for phone_number in PhoneNumber.objects.filter(dude=dude).order_by("-date")[:3] temp_phone = dict() temp_phone['date_added'] = phone_number.date.timestamp() temp_phone['business_label'] = str(phone_number.business.name) temp_dude['phones'].append(temp_phone) response.append(temp_dude) but its hitting database at least 2 time for every dude and consuming lots of cpu. what is the most efficent way for getting same response with django orm? -
django-Jquery operation with lists (One value instead of several)
I have a next code in html: {% for m in mortgages %} <input id ='mortgages_counter' name='mortgages_counter' type='hidden' value='{{ m.MonthlyPaid }}'> {% endfor %} If I use it for selection menu like: {% for m in mortgages %} <option value="{{m.MonthlyPaid}}" >{{m.MonthlyPaid }}</option> {% endfor %} I have in selection 2 elements (it is defined by views.py and is a list in its origin) but if I use it in j query in this way: $( "#mortgages_counter" ).each( function( index, element ){ console.log( $( this ).val() ); }); I see in console only the first value, And . length also shows 1. -
rq queue always empty
I'm using django-rq in my project. What I want to achieve: I have a first view that loads a template where an image is acquired from webcam and saved on my pc. Then, the view calls a second view, where an asynchronous task to process the image is enqueued using rq. Finally, after a 20-second delay, a third view is called. In this latter view I'd like to retrieve the result of the asynchronous task. The problem: the job object is correctly created, but the queue is always empty, so I cannot use queue.fetch_job(job_id). Reading here I managed to find the job in the FinishedJobRegistry, but I cannot access it, since the registry is not iterable. from django_rq import job import django_rq from rq import Queue from redis import Redis from rq.registry import FinishedJobRegistry redis_conn = Redis() q = Queue('default',connection=redis_conn) last_job_id = '' def wait(request): #second view, starts the job template = loader.get_template('pepper/wait.html') job = q.enqueue(processImage) print(q.is_empty()) # this is always True! last_job_id = job.id # this is the expected job id return HttpResponse(template.render({},request)) def ceremony(request): #third view, retrieves the result template = loader.get_template('pepper/ceremony.html') print(q.is_empty()) # True registry = FinishedJobRegistry('default', connection=redis_conn) finished_job_ids = registry.get_job_ids() #here I have the correct id … -
Django settings.py import error in mange.py Configuration error
Thanks in Advance for My Query. I have created a django project which has manage.py file inside src folder it works fine when running terminal from SRC folder. FOr Heroku deployement manage.py should be placed in root directory so i updated manage.py file with "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings")" Changed "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tweetme.settings")" to "os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings")" import issue is faced on running locally. Need solution how to import setting.py inside two folder deep. #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "src.tweetme.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise 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?" ) raise execute_from_command_line(sys.argv) I am facing following Error: attached Error_Message.png Hiras-Mac-mini-2:tweethere apple$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 23, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/Library/Python/2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/Library/Python/2.7/site-packages/django/conf/init.py", line … -
Internal Server Error and Type Error, get error on post request?Nginx Django
On local machine everything works great, but on production, creation of qr images not work, and creating qr images give me this error P.S on local host everything works great! because the working directory is determined where the file manage.py is located so that it does not clutter the main directory, I create it on the other for a temporary picture, save it in the correct place, then delete it! my creating qr image view def qr_code_generator(hex_code, username, __show__id, q, price): check_curent_dir = os.getcwd() if os.path.basename(check_curent_dir) == 'src': os.chdir('..') os.chdir('media/fake_qr_code_img/') qr_code_generate_himslef = pyqrcode.create(hex_code) generate_name = ''.join(username + '_' + str(__show__id) + '_' + str(q) + '_' + str(price) + '.png').replace(" ", "_") qr_code_generate_himslef.png(generate_name, scale=6) get_user_profile = get_object_or_404(UserProfile, user__username=username) get_upcoming_show = get_object_or_404(SectionUpcomingShow, id=__show__id) with open(generate_name, 'rb') as new_qr_img: new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":File(new_qr_img), "upcoming_show":get_upcoming_show}) if not created: pass try: os.remove(generate_name) except: print("Cannot be removed!") return 'Done' when i try to buy tickets i got this error on my email Internal Server Error: /purchase_tickets/ TypeError at /purchase_tickets/ super(type, obj): obj must be an instance or subtype of type Request Method: POST Request URL: http://therockband.tk/purchase_tickets/ Django Version: 1.11.6 Python Executable: /webapps/theband/bin/python3 Python Version: 3.5.2 Python Path: ['/webapps/theband/src', '/webapps/theband/bin', '/webapps/theband/src', … -
Django did not display DEBUG error page despite being run on localhost and ``DEBUG=True``
In my django project I did set DEBUG setting to true, and I'm accessing the server from localhost. Despite that instead of error page I get: "A server error occurred. Please contact the administrator.". -
Django2, the forms in template do not work
(only in Django 2 & 2.0.1) if I use {{form}} it works but if I use {{form.field}} it disappears all <form method="POST" class="post-form" method="post"> {% csrf_token %} {{ form }} <input type="submit" id="salva" class="btn btn-primary" /> </form> -
Django Sum Aggregation from Int to Float
So i save my fees in cents, but want to display them in Euro. The conversion problem is that it first divides the integer by 100 and then converts to a float. It should be the other way around. How can i do that? The following code should illustrate my Problem: >>> from django.db.models import F, FloatField, Sum >>> from payment.models import Payment >>> >>> paymentlist = Payment.objects.all() >>> result = paymentlist.annotate( ... fees_in_cents=Sum(F('fees'), output_field=FloatField())).annotate( ... fees_in_euro=Sum(F('fees')/100, output_field=FloatField())) >>> >>> print(result[0].fees_in_cents, result[0].fees_in_euro) 120.0 1.0 fees_in_euro should obviously be 1.20 -
I have set the related_name in OneToOne Field, but still get the RelatedObjectDoesNotExist error
When I use the to_representation I get error: django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server. The traceback is bellow: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/rest_framework/serializers.py", line 656, in <listcomp> self.child.to_representation(item) for item in iterable File "/Users/asd/Desktop/xxx/api/serializers.py", line 256, in to_representation if instance.physical_server == None: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 407, in __get__ self.related.get_accessor_name() django.db.models.fields.related_descriptors.RelatedObjectDoesNotExist: SwitchesPort has no physical_server. My Models: class SwitchesPort(models.Model): """ 交换机接口 """ ... switches = models.ForeignKey(to=Switches, on_delete=models.CASCADE,related_name="switchesports", help_text="所属交换机") vlanedipv4networkgroup = models.ForeignKey( to=VlanedIPv4NetworkGroup, # 初始化之后的 null=True, blank=True, on_delete=models.SET_NULL, related_name="switchesports", help_text="所关联的vlaned组") network_speed = models.IntegerField(default=10, help_text="交换机控制网络流量速度") class Meta: ordering = ['name'] def __str__(self): return self.name def __unicode__(self): return self.name class PhysicalServer(models.Model): """ physical_server """ ... switchesport = models.OneToOneField(to=SwitchesPort, related_name="physical_server", on_delete=models.DO_NOTHING, help_text="所属交换机接口", null=True) def __str__(self): return self.name def __unicode__(self): return self.name My Serializer is bellow: class SwitchesPortSerializer(ModelSerializer): """ switches port """ class Meta: model = SwitchesPort fields = "__all__" extra_kwargs = { "vlaned_network":{"read_only":True} } def to_representation(self, instance): serialized_data = super(SwitchesPortSerializer, self).to_representation(instance) if instance.physical_server == None: # there syas the error serialized_data['is_connected'] = True return serialized_data You see, the OneToOne Field have the related_name, why I still get the issue? -
jsonfield violates not-null constraints and filetype is not unsupported
I Have a model field field_name = JSONField(editable=False) from django admin I can't save it. If I give any json format data it shows this error 'InterfaceError: Error binding parameter 10 - probably unsupported type' -
Django last page pagination redirect
My problem is similar to this problem. The only difference is I use GCBV for my pagination. My view file is as follows: class ChatListView(ListView): model = Chat form_class = NewMessageForm template_name = 'chat.html' paginate_by = 5 queryset = form_class.objects.all() def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('chat') <--- here return render(request, self.template_name, {'form': form}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = NewMessageForm() return context What I want the post method to redirect to the last page of the pagination. In the link, it was achieved by return HttpResponseRedirect('/forum/topic/%s/?page=%s' % (topic.slug, posts.num_pages)). But for my GCBV, I don't know how to get the .numpages via an object. Any thoughts? -
How to POST values with specific ID from page that displays a list?
I'm working on my first django project which is a sport betting app. My models are: class Game(models.Model): home_team = models.CharField(max_length=100) away_team = models.CharField(max_length=100) class GameBet(models.Model): gameid = models.ForeignKey(Game) bet = models.IntegerField(default=None) #values: 1(home win), 0 (draw), 2 (away win) userid = models.ForeignKey(User) I am able to save user bets using a single game view, when I pass gameid in url, but that is not very effective. I created a simple page with list of games with 1 form per game for a start (at the end I would prefer to send all bets with one button): {% for game in games %} {{ game.id }} | {{ game.home_team }} | {{ game.away_team }} | <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="bet" /> </form> <br> {% endfor %} and my form is: if request.method == 'POST': #if request.POST["bet"] == 'bet': form = NewBetForm(request.POST) if form.is_valid(): bet = form.save(commit=False) bet.gameid = [r.id for r in owing_games] #it gives me a list and ValueError Cannot assign "[10, 11, 12]": "GameBet.gameid" must be a "Game" instance. bet.userid_id = current_user.id bet.bet = form.value() bet.save() How can I pass a single game.id in that case? -
Django rest ModelViewSet filtering objects
I have two models: Library and a Book. A Library will have Many Books. class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=30) address = models.CharField(max_length=80) phone = models.CharField(max_length=30, blank=True, null=True) website = models.CharField(max_length=60, blank=True, null=True) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) reader = models.ManyToManyField('Reader', related_name='wishlist') my serializers: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' And my view: class LibraryViewSet(viewsets.ModelViewSet): queryset = Library.objects.all() serializer_class = LibrarySerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.filter(which_library=library_id) serializer_class = BookSerializer My Urls: router = routers.DefaultRouter() router.register(r'libraries', LibraryViewSet) router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet) urlpatterns = router.urls my Library routes work correct. However for Books, I need to return the books only belonging to specific library. The default URL and all() returns all the books in database and can retrieve single by hitting books/1. How can I achieve this? I could do it previously with : @api_view(['GET', 'POST']) def books(request, library_id): but now I want to do it with ModelViewSet.