Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update ends in negative balance after massive update requests Django
Currently, I've this method inside my models.py def charge(self, amount): self.balance = (self.balance - Decimal(amount)) self.save() When A new request comes in I check if that user has current_balance >= price So I can do objectRow.charge(price) the issue is when I get 1000 request to the same ID I end up in -000 negative balance and the users ends up owing me money and that's not the point. This is my validation so far. accountObject = account.objects.get(auth_token=auth_token) if accountObject.balance >= settings.MT_COST: # Save ProductObject = product(application=applicationObject, account=accountObject, cost=settings.MT_COST, direction=2, status_log=1, product=product_id, ip_address=ip_address) ProductObject.save() # Charge User ProductObject.charge(settings.MT_COST) data = {'status': "ok"} return HttpResponse(json.dumps(data), content_type='application/json', status=200) # Not enough Balance else: data = {'status': "error"} return HttpResponse(json.dumps(data), content_type='application/json', status=406) -
Django unicode convertion
I did some research on Unicode strings, but I've unfortunately not been able to figure out why Python does some things. I have this piece of code: output["anything"] = { "type": "Feature", "properties": { "name": "somename", "amenity": "Store", "popupContent": "Store 3 " }, } When I use print(output) it prints this as: {u'anything': u'type': u'Feature', u'properties': {u'amenity': u'Store', u'name': u'somename', u'popupContent': u'Store 3'}} I would however like to have this without the u' ' as my javascript utility won't read this. If the answer would also give me some insight in why this is happening, I would really appreciate that. -
Update seconds dropdown based on the selection of the first dropdown using the database
I have two dropdowns in my HTML. The second select would change depending on the selection of the first one. I want my first element to be the one to make an AJAX call and extract what's inside of my database. I am not quite fluent in jQuery/AJAX and I need help on this one. Here is an example: <select name="menu"> <option value="meat"> Meat </option> <option value="seafood"> Seafood </option> <option value="vegetarian"> Vegetarian </option> <option value="dessert"> Dessert </option> </select> <select name="entrees"> {% for i in meat %} <option value='{{idx.0}}'> {{i.1}} </option> {% endfor %} //more loops for other menu </select> When the user select the type of food, different entrees appears on the second html dropdown. I am using python and django in my backend. The entrees are being updated regularly that is why I can't hardcode the options of the second dropdpwn, as many have suggested on some question here. LET'S SAY: I choose 'meat.' How do I make an ajax call to get all the meat entrees in an array so I can loop into it? I would greatly appreciate it if you can comment lines that are important so I can learn something new. Thank you very much … -
ValueError: Dictionary Update Sequence Element #0 has length 0; 2 is required
So, everything was working perfectly fine. But when I tried to "Log-out" I got this error: Internal Server Error: / Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Desktop\infortion\home\views.py", line 28, in posts_list return render(request, 'home/post_list.html', context) File "C:\Python36\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Python36\lib\site-packages\django\template\loader.py", line 68, in render_to_string return template.render(context, request) File "C:\Python36\lib\site-packages\django\template\backends\django.py", line 66, in render return self.template.render(context) File "C:\Python36\lib\site-packages\django\template\base.py", line 205, in render with context.bind_template(self): File "C:\Python36\lib\contextlib.py", line 82, in __enter__ return next(self.gen) File "C:\Python36\lib\site-packages\django\template\context.py", line 263, in bind_template updates.update(processor(self.request)) ValueError: dictionary update sequence element #0 has length 0; 2 is required [10/Oct/2017 00:21:10] "GET / HTTP/1.1" 500 90547 I tried every URL but getting the same error. Even if i'm trying to log into Admin panel it's showing the same error. What should I do? -
Django - How to get the top 10 highest scores, but limiting it to a single score per user?
I have a simple model to keep scores for any number of score based games: class Score(models.Model): game = models.ForeignKey(Game, related_name='leaderboards') value = models.IntegerField(db_index=True) uom = models.CharField('Unit of Measurement', max_length=10) user = models.ForeignKey(settings.AUTH_USER_MODEL) class Meta: ordering = ['-value'] ... My Django Rest Framework API view is as follows which is intended to get me the current leaderboard for a particular game: class LeaderboardView(APIView): ... def get(self, request, pk): game = get_object_or_404(Game, pk=pk) # This query doesn't work scores = Score.objects.filter(game=game).order_by('-value').distinct('user')[:5] serializer = ScoreSerializer(scores, many=True) return Response(serializer.data) The problem is I'm having trouble figuring out how to get the top 10 highest scores, but limiting it to a single score per user (eg - their highest) using the ORM rather than manually getting all scores and then looping through them to ensure I only grab the highest score per user. Thanks for any help in advance. -
Django Serializers not parsing foreign key objects
I have the models: class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) manager_id=models.ForeignKey('self',null=True,blank=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() class notify(models.Model): sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') viewed=models.CharField(max_length=2) In my views I am writing Query as: def notification(request): template = loader.get_template('base.html') user = employees.objects.get(emp_id=request.user.username) emp_id=user.emp_id; notification=notify.objects.filter(receiver_id__employee__emp_id=emp_id); data = serializers.serialize("json", notification) print(data); context={'notification':data,'notification_count':notification_count} femp = json.dumps(context) return JsonResponse(femp, safe=False, content_type="text/html") In print(data) its printing [{"model": "apply.notify", "pk": 32, "fields": {"sender_id": 121, "receiver_id": 44, "viewed": "N"}}] Here its printing the sender_id=121 which is id in leave table but if I want start_date and emp_name(as it is referenced from employee in leave table).What should I write in serializers.serialize()so that I can reference foreign key enteties. -
Unable to understand the flow of list serializer update after properly implementing create
I am using list Serializer by many = True. The create method is running perfectly but i am unable to understand the flow of custom update method of list serializer in documentation of django rest framework. Using the base of list serializer is clear but when i am using it in code the flow is not understandable. I am not able to understand what book.items mean in the fourth line. In the documentation it is also asking to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only. Looking to understand what documentation is saying and how to implement it. The context from documentation is give below. class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping:a book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, … -
Postgres vs SQL lite page not found discrapancy
I have my dev environment with django - SQLlite and my prod is with django - Postgres I have view that works perfectly on SQL lite login_required def receipt_pdf(request,pk): try: Receipt_payment_id_dict = Receipt_payment.objects.filter(is_active = True ).aggregate(Max('id')) if Receipt_payment_id_dict: Receipt_payment_id = Receipt_payment_id_dict['id__max'] Receipt_payment_dict = get_object_or_404(Receipt_payment, pk=Receipt_payment_id) else: Receipt_payment_dict = "no data" except ValueError: raise Http404("At least one active value should be in -Receipt_payment-, contact your administrator") try: general_id_dict = General_configurations.objects.filter(is_active = True ).aggregate(Max('id')) if general_id_dict: general_id = general_id_dict['id__max'] general_dict = get_object_or_404(General_configurations, pk=general_id) else: general_dict = "no data" except ValueError: raise Http404("At least one active value should be in -General_configurations-, contact your administrator") payment = get_object_or_404(LeasePayment, pk=pk) # leasetenant = lease.tenant_set.all().order_by('-id') # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="Receipt.pdf"' buffer = BytesIO() # Create the PDF object, using the BytesIO object as its "file." p = canvas.Canvas(buffer) But When I execute same code with Postgres I get No Receipt_payment matches the given query. What could be the problem? -
Query by datetime.now().date of lower from Django DateTimeRangeField
I use a postgres DateTimeRangeField in Django model. It is the existing database and all the existing rows has both lower range and upper range. Now I need to query for all the rows where date of the lower range is a specific date for example something like rangefield.lower.date==1 . Please don't tell me to use separate fields for Start date and end date. This system is in production and I need to query that to filter for analytics. -
images and css django files not loading
Hello everyone, Well i'm new to django, I made my first profissonal project and the problem is sometimes the site displays all the images correctly but sometimes everything disappears same with django admin css which is not working actually. and I have really tried everything but still I can't find a solution on my own. Here are my files : urls.py if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") Example of model containing imagefield class Article(models.Model): name = models.CharField(max_length=300,blank=True,null=True) price = models.IntegerField(default=5) image = models.ImageField(null=True, blank=True, height_field="height_field", width_field="width_field", verbose_name="profile picture" ) height_field = models.IntegerField(default=600, null=True) width_field = models.IntegerField(default=600, null=True) description = models.TextField() souscategorie = models.ForeignKey(SousCategorie, related_name="souscate") slug = models.SlugField(unique=True) how i display an image on template {% if sous.image %} <a href="{% url 'liste' slug=sous.slug %}"><img src="{{sous.image.url}}" width="100" height="100" alt="" /></a> {% endif %} -
Deploy to my server with Git
I have a development of a django project on my day-to-day laptop. Now I have put together a server with Ubuntu, nginx, gunicorn with postgreSQL. I have pip't git on both my laptop and server. And done a 'git init' in my project on the laptop. Now I am trying to push/deploy this on my local server. I have done tons of commands that, more or less, look like this git push --set-upstream ssh://admin@192.168.1.240/home/admin/Django/ master Do not think I have to say that I am new to all this exciting stuff. It is very interesting, but now my head is foggy and I am stuck. Pointers in right direction are much appreciated! =) -
Is JSON not serialise-able over http or Django doesn't know how to read it?
I have created a couple of projects with Django. Every time I try to send an ajax POST request from frontend to django, I have to use JSON.stringify() function, pass it inside the body of POST request and parse the JSON manually inside Django (using ujson, because of its faster). My question is that why do I need to do this manually? -
django edit user profile onetoone field
Hi i know how to allow users to edit user model in Django but its not working with onetoone field. please let me know how to allow users to edit user with onetoone field i tried but its not working model.py class userProfile(models.Model): userName = models.OneToOneField(User) nick = models.CharField(max_length=100) agreement = models.BooleanField(default=False) profileimage = models.ImageField(upload_to = profileimagepath, blank=True) def __unicode__(self): # __str__ return unicode(self.userName) forms.py class EditProfileForm(UserChangeForm): class Meta : model = User fields = ('email','password','nick','profileimage') views.py def edit_profile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/changeprofile') else: form = EditProfileForm(instance=request.user) args = {'form':form} return render(request, 'editprofile.html', args) editprofile.html <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">change</button> urls.py url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), -
Get the subdomain in a Django view? using django-hosts library
I'm making a project in django. The aplication have to show diferent images and languages depending on the subdomain. For example: www.mysite.com will be the default page in english, but if the subdomain is mx.mysite.com the language must be spanish. Whith django-hosts I can make that each subdomain redirect to a diferent django-app and I works well. The problem is that I want to make only one app to all diferent subdomains, only changing the language. I think that is possible get the subdomain in a view and render the template with the language depending on the subdomain. But I don't know how to do it, please help. THIS IS MY DJANGO HOSTS.PY where the host 'www' and 'mx' redirect to the same app 'mysite' but must be in diferent languages. from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', 'mysite.urls', name='www'), host(r'help', 'help.urls', name='help'), host(r'mx', 'mysite.urls', name='mx'), ) -
Can't use Django in virtualenv
I had 2 django project , I created 2 different virtualenv for them. When I create another one virtualenv and install django and create djangoproj I tried python manage.py runserver and had this: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ImportError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " 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? What I need to do? I already tried uninstall django, pip, virtualenv and install : sudo apt-get install python3-pip sudo pip3 install virtualenv sudo virtualenv ENV source newenv/bin/activate sudo -H pip3 install django -
What to use for caching dynamically generated pages
I'm planning to use Django as an application server, nginx as a web server for serving static files. I'd like something to cache pages that Django generates. Varnish seemed to be Ok. I started to study it. But faced difficulties. I ask questions here, at StackOverflow: help me with this case in the tutorial. And there is either no answer, or something like: "Well, this is an obsolete tutorial". Well, there is nothing else. And a suspicion bore: maybe nobody uses Varnish anymore. Look: all videos at YouTube is at least a year old. At stackoverflow search for Varnish tag gives only 1,521 questions. Whereas a tag for Django gives 154,093 questions. Well, Varnish must be a more general technology: any site needs an accelerator. I'd say there should be more questions about it. Anyway, could you tell me whether Varnish is dead or not? And what should I use instead of it? -
Error: Cannot assign ... "Product.partner" must be a "Partner" instance
I am attempting to save multiple 'products' to a single 'partner' using a formset and a ForeignKey. I am getting the following error when I attempt to create a Product: Cannot assign "<PartnerForm bound=True, valid=True, fields=(name;logo;banner_image;mission;vision;website_link;fb_link;twitter_link;ig_link)>": "Product.partner" must be a "Partner" instance. I am pretty sure that I am close any help would be greatly appreciated. My models.py looks as follows: class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") banner_image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field") mission = models.TextField() vision = models.TextField() height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) # text = models.TextField() website_link = models.CharField(max_length=120) fb_link = models.CharField(max_length=120) twitter_link = models.CharField(max_length=120) ig_link = models.CharField(max_length=120) slug = models.SlugField(unique=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return self.name def get_absolute_url(self): return reverse("partners:detail", kwargs={"slug": self.slug}) # return "/partner/%s/" %(self.id) def get_markdown(self): mission = self.mission markdown_text = markdown(mission) return mark_safe(markdown_text) #Creating a many to one relationship so that one can upload many Products class Product(models.Model): partner = models.ForeignKey(Partner, default=None) name = models.CharField(max_length=120) product_image = models.ImageField(upload_to=upload_location, # product_image = models.ImageField(upload_to= (upload_location + '/' + name), Something like this need to append actual product name so these dont just get dumped in the media for partners null=True, blank=True, width_field="width_field", … -
Memcached not working beyond scope(?)
I cannot seem to find any instances of memcached seemingly having some sort of scope, but that is what seems to be happening to me right now. In my views.py, I have a value stored in memcached auto increment every time the page loads. I know this is working because after about 30 reloads, it is at about 30. However, if I try to access this variable from python manage.py shell, for example, the value stored there does not work. Furthermore, any values I store in that shell will persist only while that shell is running. Here is what I am doing in the shell: from django.conf import settings from django.core.cache import cache > cache.get('my_incr_key') # This auto-increments in views.py None > cache.get('my_new_key') None > cache.set('my_new_key', 12, None) > cache.get('my_new_key') 12 The problem is, if I exit the shell, then run this again, the same exact thing will happen: most notably, getting my_new_key will still return None. That I cannot see the value stored in my_incr_key suggests to me that there is a scope issue at play. This is driving me absolutely nuts! Is there such a thing as scope for memcached? Is that what is at play here? How … -
how to implement search and sorting function in Django table
I know that there are Django-datatable, django_tables2, and even django_filter to perform search and sorting to the table. But is there any easy way to perform search and sorting for each column in Django table ? I have tried using Django-datatable, django_tables2 and even django_filter, but none of them work. I have attached my code for the template. I am rendering two different tables using the code below, one is with action and status column while the other is without these two columns. {% if some %} <table id="example" class="display" cellspacing="0" width="100%" border="1.5px"> <tr align="center"> <th style="font-family: Calibri" > Student ID </th> <th style="font-family: Calibri" > Student Name </th> <th style="font-family: Calibri" > Start Date </th> <th style="font-family: Calibri" > End Date </th> <th style="font-family: Calibri" > Action </th> <th style="font-family: Calibri" > Status </th> </tr> {% for item in query_results %} <tr align="center"> <td style="font-family: Calibri" > {{item.studentID}} </td> <td style="font-family: Calibri" > {{item.studentName}} </td> <td style="font-family: Calibri" > {{item.startDate|date:'d-m-Y'}} </td> <td style="font-family: Calibri" > {{item.endDate|date:'d-m-Y'}} </td> <td style="font-family: Calibri" > {% if item.status == 'Approved' %} {% else %} <a href="{% url 'timesheet:edit' id=item.id status='a' %}"><button onclick="alert('timesheet accepted')">Approve</button></a> <a href="{% url 'timesheet:edit' id=item.id status='d' %}"><button onclick="alert('timesheet denied')")>Deny</button></a> {% … -
Django. How to compare expired_date to datetime.now()
I am using django to build an appointment web. I want to compare every appointments time to DateTime.now(), so the appointment can expire 2 hours before DateTime.now(). For example, suppose there is an appointment with a time of "11/07/2017, 7 PM". It should be expired at "11/07/2017 5 PM". Users have to book the appointment at least 2 hours earlier than the appointments time. -
Factory Boy - inherit strategy for SubFactory
I'm trying to create a Django model instance using "build" strategy (e.g. create in-memory objects and do NOT commit it to the database). The model has a foreign key to another Django model - Survey, so I was hoping to use SubFactory to instantiate that model: class SurveyInvitation(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) . class SurveyInvitationFactory(factory.DjangoModelFactory): class Meta: model = models.SurveyInvitation survey = factory.SubFactory(SurveyFactory) When I call the build function: survey_invitation = SurveyInvitationFactory.build() it does create an instance of SurveyInvitation model in memory, but it apparently creates a saved instance of Survey model (using a "create" strategy, I suppose). Is it possible to tell Factory boy to propagate the strategy I choose to subfactories? -
Django paginator not providing content on next page
I use Django paginator to break my search results to few pages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger In my view I perform the search based on the output from the form @login_required def payment_range_list(request): #import pdb; pdb.set_trace() title = 'payment list' #import pdb; pdb.set_trace() if request.method == "POST": form = PaymentRangeForm(request.POST) #import pdb; pdb.set_trace() if form.is_valid(): start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] building = form.cleaned_data['building'] payment_list = LeasePaymentFilter(request.GET, queryset=LeasePayment.objects.filter(payment_date__range=[start_date, end_date],lease__unit__building = building )) paginator = Paginator(payment_list, 25) # Show 25 contacts per page page = request.GET.get('page') try: payment_page = paginator.page(page) except PageNotAnInteger: payment_page = paginator.page(1) except EmptyPage: payment_page = paginator.page(paginator.num_pages) else: payment_list = None payment_page = None start_date = None end_date = None building = None else: payment_list = None payment_page = None start_date = None end_date = None building = None #form = PaymentRangeForm() form = PaymentRangeForm(initial = {'building': 0 }) return render(request,'payment/payment_range.html', {'form':form, 'payment': payment_list,'page_payment':payment_page, 'start_date':start_date, 'end_date':end_date, 'building':building }) On the top of the page I have a form that I use for search and 2nd part is used to display the results. {% extends "rent_base.html" %} {% load crispy_forms_tags %} {% block title %} Lease List {% endblock title %} {% block content %} <div class="container-fluid"> … -
How do I prefetch all objects in a database with Django ORM?
I need to migrate a large amount of data from another database, and it's running very slowly because I have to constantly check if the object already exists so I don't have duplicates. Is it possible to have a queryset which prefetches all objects? Kind of like Asset.objects.prefetch_all(). I don't think I can use prefetch_related for this since it only prefetches related objects. -
Django OAuth authentication against Github, without database
I want to create a Django app that does not use a database, but authenticates against Github using OAuth 2.0. The point being that anyone who belongs in our Github organization can log into the app and perform operations, which involve making changes to files in a repo in Github. Think something like the facility in the Github web application to edit files through the web browser. Since I do not need to actually check files out locally using the Github API, I was hoping to avoid having any kind of server-side state. Is there a way I can do this with Django? Thank you -
How to serve Angular2 using Django builtin webserver
how to serve Angular2 app using Django builtin webserver? I think I'm having some problems with the template and static paths from django. My django project structure looks like following: DjangoDir/ manage.py project/ settings.py urls.py app1/ app2/ static/ app2/ something.js something.css templates/ app2/ index.html urls.py views.py I have an angular2 app with following index: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Angular2</title> <base href="/"> <link href="something.css" rel="stylesheet"/> </head> <body> <app-root></app-root><script type="text/javascript" src="something.js"></script> </body> </html> I get HTTP Status 404 (Not Found) code for the something.js and something.css file. Any ideas? Here is my views.py in app2. from django.shortcuts import render # Create your views here. def index(request): return render(request, 'app2/index.html')