Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django: How to add a foreignkey to a dependent form, to a multi-form submit?
Forgive the logic of the table structure below example. It only meant as a simple example of the situation that I am. So the situation is that I want to make an employee form page, where the department and line manager might or might not exist already. So I replace the drop-down box with the form field for the foreign key, so they can be created if need all in one step for the user. However, with this kind of dependency, I am not doing the right thing in view to make it work. If you need more detail please do ask. If you can make the Title more precise please do. Thank you for your time. Model class Employee(models.Model): name = models.CharField() age = models.CharField() line_manager = models.ForeignKey(LineManager) department = models.ForeignKey(Department) class LineManager(models.Model): manager_name = models.CharField() department = models.ForeignKey(Department) class Department(models.Model): department_name = models.CharField() Form class EmployeeForm(ModelForm): class Meta: model = Employee fields = ['name', 'age' #'line_manager' Not needed #'department' Not needed] exclude = ('line_manager', 'department') class LineManagerForm(ModelForm): class Meta: model = LineManager fields = ['manager_name'] exclude = ('department') # There is a basic form for Department, as well. View class AddEmployeeView(View): forms = {'department': DepartmentForm(self.request.POST or None), 'line_manager': … -
"Closure Table" in django models?
Can someone help me to create Django models with next tables which us "Closure Table" hierarchical tree architecture. I am confused of relationship in models. "document" TABLE: "document_tree" TABLE: | document_id | document_name | | ancestor | descendent | level | | -------------|---------------| | ---------|------------|-------| -
Try to post a dictionary to my view
In my template, I have a form and a <select> with many <option>. I have to pass 2 values in each <option>, so I had the idea to make a dictionary : <option value="{'Game':{{game.on_game.id}},'Platforme':{{game.on_plateform.id}}}"> It returns something like this : <option value="{'Game':3,'Platforme':3}"> In my view I want to save a new entry : post = request.POST entry = InboxRecruiting() entry.on_game = Games.objects.get(id=post['game']['Game']) entry.on_platforme = Plateform.objects.get(id=post['game']['Platforme']) entry.save I have an error : string indices must be integers Thanks for your help. -
Integrate c++ Compiler to a website using DJANGO
I would like to integrate an online code editor with a C++ compiler integrated into my website. Are there any soft service which allows to compile and execute codes from user. and is there any possibility to compile the code into the website server and run it in the user machine ? thanks -
get_absolute_url not making any effect
I only used this in my template. I am following a tutorial. In tutorial video is working but I couldn't make it work. Here is my template code: <i> {% for object in object_list %} <div class="media"> <div class="media-left"> <a href="#"> {% if object.img %} <img class="media-object" src="..." alt="..."> {% endif %} </a> </div> <div class="media-body"> {{ object.content }}<br/> via {{ object.user }} | {{ object.timestamp|timesince }} ago | <a href='{{ object.get_absolute_url }}'>View</a> </div> </div> <hr/> </i> -
Celery Beat not Working
Celery beat is not scheduling task properly and freezes. Celery Configuration 4.1.0 CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ACCEPT_CONTENT += ['pickle'] CELERYBEAT_SCHEDULE = { 'testing_msg': { 'task': 'modules.sms.tasks.testing_message', 'schedule': crontab(minute=1), }, } tasks.py @task() def testing_message(*args, **kwargs): SmsAPI().send_sms("Hello Shubham Message Time is {}".format(datetime.now().time()), "958xxxxxx") SmsAPI().send_sms("Hello Nishant Message Time is {}".format(datetime.now().time()), "971xxxxxx") Celery Beat Logs (Nishant) shubham@shuboy2014:/media/shubham/BC161A021619BDF8/Nishant Project/Project1$ celery -A config beat -l debug raven settings celery beat v4.1.0 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2018-01-04 14:57:53 Configuration -> . broker -> redis://127.0.0.1:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%DEBUG . maxinterval -> 5.00 minutes (300s) [2018-01-04 14:57:53,139: DEBUG/MainProcess] Setting default socket timeout to 30 [2018-01-04 14:57:53,139: INFO/MainProcess] beat: Starting... [2018-01-04 14:57:53,334: DEBUG/MainProcess] Current schedule: <ScheduleEntry: celery.backend_cleanup celery.backend_cleanup() <crontab: 0 4 * * * (m/h/d/dM/MY)> [2018-01-04 14:57:53,334: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2018-01-04 14:57:53,336: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. Any helpful comments and answers will be appreciated. -
How to construct a response in Django as specified in finger print reader sdk
The following is part of a documentation of SDK for a finger print device. SDK documentation Device sends: GET /iclock/cdata?SN=xxxxxx&options=all Thereinto, xxxxxx is the device’s serial number. server returns (example): GET OPTION FROM: xxxxxx Stamp=82983982 OpStamp=9238883 ErrorDelay=60 Delay=30 TransTimes=00:00;14:05 TransInterval=1 TransFlag=1111000000 Realtime=1 Encrypt=0 How can i construct such a response in Django? -
Django 2: project root url namespace not working
I have the following url patters in the project root's urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('main/', include('main.urls', namespace='main')), ] But django complains with the following message: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. According Django's documentation, the pattern of 'main' should be correct. What's the problem? -
How to do logging in flask?
The python logging module will have problem in multiprocessing. Because there is no lock between processes while they writinig to the same log file. But the flask or django programes will always run in multiprocessing enviroment when they are hosted by uwsgi. Uwsgi run multiple workers. One worker is one process that hosted the flask/django program. So this is a situation that write log into one file from multiple process How flask or django to solve this? -
Django User Profile Model Sign Up Form
I'm developing django project. Now I'm making sign up form with profile model. But I got a problem. models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usernickname = models.CharField(db_column='userNickName', max_length=50, blank=True, null=True) userbirth = models.DateField(db_column='userBirth', blank=True, null=True) class Meta: managed = False db_table = 'profile' @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py : from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): userBirth = forms.DateField() class Meta: model = User fields = ('username', 'password', 'userBirth') widgets = { 'username': forms.TextInput(), 'password': forms.PasswordInput(), 'userBirth': forms.DateField(), } views.py : def join(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.userbirth = form.cleaned_data.get('userbirth') user.save() user = User.objects.create_user(username=user.username, password=user.password) user.save() return redirect('index') else: form = UserForm() return render(request, 'registration/join.html', {'form':form}) and when sign up, InternalError at /join/ (1054, "Unknown column 'profile.user_id' in 'field list'") this error returns. when log in to /admin, same error returns. I don't have any idea.. I refernced this blog: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html#sign-up-with-profile-model