Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0.9 using dockerized MS Sql Server on Mac, varbinary conversion error
I am assuming this is NOT a common scenario -- however I am running Django 2.0.9, pyodbc 4.0.24, django-pyodbc-azure 2.0.4.1 and ODBC 17 on my Mac, talking to SQL Server running in Docker, Microsoft SQL Server 2017. For reasons also beyond my control, I am modeling a system where uploads are stored a BLOBs, varbinary types in SQL Server parlance. No matter what I do, as soon as I declare a BLOB type and attempt to load a fixture (without a BLOB) I get the error: Could not load mytype.MyType(pk=3455): ('22018', '[22018] [FreeTDS][SQL Server]Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. (257) (SQLExecDirectW)') The model is as follows: class MyType(models.Model): id = models.BigAutoField(primary_key=True) desc = models.CharField( max_length=4000, blank=True, null=True) name = models.CharField(max_length=8, blank=True, null=True) blah_id = models.BigIntegerField(blank=True, null=True) related_thing = models.ForeignKey( Thing, on_delete=models.PROTECT, blank=True, null=True) ... etc ... pdf = models.BinaryField(blank=True, null=True) # here is the sticking point class Meta: # etc I loaddata using a fixture with everything BUT the syllabus and I always get there error: Problem installing fixture '/path/to/fixtures/0011_mydata.json': Could not load mytype.MyType(pk=3455): ('22018', '[22018] [FreeTDS][SQL Server]Implicit conversion from data type varchar to varbinary(max) is not … -
python reportlab balance 2 frames in last page of every chapter
I have created a book with 2 frames on each page. At the end of each chapter, a PageBreak is added. The text on the last page of each chapter, by default, is not balanced between the 2 frames. I have not found any obvious way to tell ReportLab to balance a page. [To use the BalanceColumns class, it seems that I would have to know in advance what text will be placed in the last page of a Chapter.] I have tried tracking where the ReportLab will make the page breaks, but my calculations are off by a few lines on each page. I used flowable.wrap to do this. It seems to me that this is a common use of ReportLab. Is there an easy way for me to balance the last page of each chapter between the 2 frames? Extra Information: The text for the book comes from a database. I am using the free version of ReportLab in a DJango app. -
How to run a django standalone script
I'm having difficulty calling a django script. Here is what I'm currently doing in my root directory: >>> import os >>> os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py' >>> from django.conf import settings >>> settings.configure() >>> settings.DATABASES {} The settings.DATABASES should not be empty, so I know I haven't initialized the project correct. How would I do this in django2.1? I used to be able to do this easily using import settings; setup_environ(settings), but not anymore. -
Django Braintree Integration
I would like to integrate Braintree payment into my website. I know there are many mistakes in my code as I'm learning. Currently the code doesn't work even though I tried to follow the Braintree documentation as best as I could. How can I implement the payment on the Cart page? Thank you. views.py (Cart app) import braintree gateway = braintree.BraintreeGateway( braintree.Configuration( braintree.Environment.Sandbox, merchant_id="84vwbhmk7znyhc3x", public_key="gqswmjckv9w8d3mp", private_key="c570bb1237d8e8e1927d7ee60f4bca26" ) ) def cart_detail(request, total=0, cart_items = None): try: cart = Cart.objects.get(cart_id=_cart_id(request)) cart_items = CartItem.objects.filter(cart=cart, active=True) for cart_item in cart_items: total += (cart_item.service.price) except ObjectDoesNotExist: pass braintree_total = int(total * 100) client_token = gateway.client_token.generate() if request.method == 'POST': print(request.POST) # retrieve nonce nonce = request.POST.get('payment_method_nonce', None) # create and submit transaction result = gateway.transaction.sale({ 'amount': '{:.2f}'.format(braintree_total), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) cart.html <div class="col-12 col-sm-12 col-md-12 col-lg-6 text-center"> <table class="table my_custom_table"> <thead class="my_custom_thead"> <tr> <th> Checkout </th> </tr> </thead> <tbody> <tr> <td> Please review your shopping cart items before proceeding with the order payment. </td> </tr> <tr> <td class="text-left"> Your total is: <strong>£{{ total }}</strong> </td> </tr> </tbody> </table> <div class="mx-auto"> <div id="dropin-container"></div> <button id="submit-button">Pay with card</button> <script> var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: '{{ client_token }}', container: '#dropin-container' }, function … -
get value from key of Choices django model queryset like get_field_display
I'm trying display the value from choices in queryset, but it's show me the key. How to solve this? exp_dpto = _queryset_expenses.filter(paied=True, expired__month=current_month).annotate(total=Sum('price')).values('departament','total') result: <QuerySet [{'departament': 1, 'total': Decimal('55.00')}, {'departament': 4, 'total': Decimal('100.00')}]> I don't want show the Key, eg: departament:1, I want to show: departament:'Marketing' Thanks for all help. -
updating the profile picture in the same template
i'm new to django, and what i'm traying to do is that i have a profile page displaying the user's informations and his picture so i want to add a button that upload directly a new picture and display it; i tired to do it like this: Profile.html <div class="col-md-4"> {% if prf.image %} <div class="profile-img"> <img src="{{ prf.image.url }}" id="prf_img" alt=""/> </div> {% else %} <div class="profile-img"> <img src="{% static 'img/empty-profile-picture.png' %}" id="prf_img" alt=""/> </div> {% endif %} </div> <form method="post" action="{% url 'profile' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="upload" > </form> views.py @login_required def profile(request): if request.method == 'POST': form = picture_form(request.POST, request.FILES) if form.is_valid(): profile = Profile.objects.get(user=request.user) profile.image = form.cleaned_data['image'] profile.save() return redirect(reverse('profile')) else: profile=Profile.objects.filter(user=request.user) form=picture_form() return render(request, 'store/profile.html', {'profile': profile,'form':form}) but this return an empty form. -
Django annotate conditional expression invalid lookup
I try to create a queryset to use in a django_filters. service_list = table1.objects.annotate( Total=Sum( Case(When(table1fk__table2fk__table3fk__table4field='XX', then=Table2.field),output_field=IntegerField()) ) ) I get : "Related Filed got invalid lookup: table3fk" I try first to define @property on my table1 to do the sum but I need to sum my different XX sum to present sub total on my view. I hope it's clear enough. Thanks -
How to do calculation to a model's fields based on another model in django
I been stuck in putting this together for few days now and I really could use some insights. It's a stock portfolio and people put in their buys through modelform. Now I want to use the information to calculate distinct stocks. I am doing this directly in my view so so far I have: Getting distinct stock name: Stock.objects.order_by('symbol').values_list('symbol',flat=True).distinct() Getting total quantity based on distinct stock name: total_quantity = Stock.objects.order_by('symbol').values_list('symbol').annotate(Sum('quantity')) This is what I have in mind, but right now it's just getting data from model to model. How can I use distinct, aggregate inside this? for item in Stock.objects.filter(user = request.user).order_by('symbol').distinct(): s = Stockcal.objects.create() s.symbol = item.symbol s.total_quantity = item.quantity s.total_value = item.price*item.quantity s.save() This is what model 1/ model 2 should be. -
How to have exception for some words - Regex in django url pattern?
In my website, people can visit other's profile with url like https://example.com/slug-profile, here is the pattern: path('<slug:slug>',views.profile,name='profile') I also want that users go to settings,notifications: path('settings',views.param,name='param') # https://example.com/settings path('notifications',views.notifications,name='notifications') # https://example.com/notifications But in this case, settings will be considered as a slug. I have already set a function to avoid users to have slug like settings or notifications. I see that some websites use a prefix or something similar www.example.com/user/settings/ www.twitter.com/i/notifications/ In my project I would do: re_path(r'^(?P<slug>\w{5,})$',views.profile,name='profile') path('i/settings',views.param,name='param') i or user will never be considered as a slug profile since the slug regex expression must have at least 5 characters. How to have thees words or a list of words ['settings','notifications'] as exceptions in a regex pattern? Or Do I need to go with example that contains i user in url? -
Jinja2: Find if value is empty
I want to avoid displaying URL if the id field is empty in the Jinja template. Right now it looks like below where it works fine {% for some_url in item.some_url %} <td scope="row"> <a href="{% url 'any_view' %}?id={{some_url}}">Click Here</a> </td> {% endfor %} I've tried a couple of ways to find if some_url is empty or not but haven't succeeded yet. Recently I tried the following code: {% for some_url in item.some_url %} <td scope="row"> <a href="{% url 'any_view' %}?id={{some_url}}">Click Here</a> {% if item.facewall_url == None %} <p>none</p> {% else %} <p> url is there </p> {% endif %} </td> {% endfor %} I've also changed item.facewall_url to facewall_url too which isn't working. Also, I've tried if item.facewall_url is defined or facewall_url is defined which aren't working. Can someone please help me out -
Django ListView with simple actions for each item
I need to render a list of Django models, so ListView seems like a good choice. The problem is that it seems to be designed purely for displaying information. I need to add a couple of action buttons next to each item: one to delete it and one to perform a specific action. I was looking into a solution where the CBV would extend ListView and FormMixin, but this wouldn't do either, because the form would exist for the entire list rather than for each element. Besides, is a FormMixin even the right choice for two simple actions? Is it not a bit of an overkill? I am not very familiar with CBV, I find them cumbersome and confusing, so I tend to go with function views instead. But I would like to start doings things the Django way, I know that once you get used to them they work pretty nicely. So what would be an appropriate choice for my scenario? -
How to display the groups list of (logged in) user accessed groups in the creation of new user?
enter image description here In the picture we can see that there are 2 groups names(WILD,WILD2) are displaying.But the user who have logged in currently has only access to the WILD. I just want to change the functionality so that it has to display only the WILD group instead of displaying all groups list. Can anyone suggest me how to do that in django applications(how to override the functionality of displaying groups list) and Where to change? -
Docker with dJango - docker-compose up not working on Windows 10
Me and my team are having some issues when we try to put our python project up in localhost. When we got to PowerShell and type "docker-compose up" we get the following log: (myvenv) PS D:\GitHub\lux_pecuaria\workspace> docker-compose up Creating network "workspace_default" with the default driver Creating workspace_pecuaria_db_1 ... done Creating workspace_pecuaria_web_1 ... done Attaching to workspace_pecuaria_db_1, workspace_pecuaria_web_1 pecuaria_db_1 | The files belonging to this database system will be owned by user "postgres". pecuaria_db_1 | This user must also own the server process. pecuaria_db_1 | pecuaria_db_1 | The database cluster will be initialized with locale "en_US.utf8". pecuaria_db_1 | The default database encoding has accordingly been set to "UTF8". pecuaria_db_1 | The default text search configuration will be set to "english". pecuaria_db_1 | pecuaria_db_1 | Data page checksums are disabled. pecuaria_db_1 | pecuaria_db_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok pecuaria_db_1 | creating subdirectories ... ok pecuaria_db_1 | selecting default max_connections ... 100 pecuaria_db_1 | selecting default shared_buffers ... 128MB pecuaria_db_1 | selecting dynamic shared memory implementation ... posix pecuaria_db_1 | creating configuration files ... ok pecuaria_db_1 | running bootstrap script ... ok pecuaria_web_1 | Performing system checks... pecuaria_web_1 | pecuaria_web_1 | System check identified no issues (0 silenced). pecuaria_web_1 … -
Getting errors in using GeoIP2 in django
I am trying to use GeoIP2 to get user's cities and countries using their IP when they view my website. I have downloaded 2 files from https://dev.maxmind.com/geoip/legacy/geolite/ , GeoLite Country and GeoLite City Binary/gzip files. After that I put them in the directory geoip inside my projects root. And there I unzipped them. Here is the image and I have also added this line to my project settings.py file: GEOIP_PATH = os.path.join(BASE_DIR, 'geoip') but when I try to use GeoIP2 it gives me error: GeoIP2Exception at / Invalid GeoIP country and city data files. I am using django 2.0.4. can anybody help me to solve this? thanks. -
Django: annotate queryset with string
I need to annotate a queryset with strings from dictionary. The dictionary keys come from the model's field called 'field_name'. I can easily annotate with strings from dictionary using the Value operator: q = MyModel.objects.annotate(new_value=Value(value_dict[key], output_field=models.CharField())) And I can get the field value from the model with F expression: q = MyModel.objects.annotate(new_value=F('field_name')) Putting them together however fails: # doesn't work, throws # KeyError: F(field_name) q = MyModel.objects.annotate(new_value=Value(value_dict[F('field_name')], output_field=models.CharField())) Found this question, which afaiu tries to do the same thing but that solution throws another error: Unsupported lookup 'field_name' for CharField or join on the field not permitted. I feel like I'm missing something really obvious here but I just can't get it to work. Any help appreciated. -
Heroku/Django shell_plus: Could not open editor
I'm trying to run a script on Heroku. I didn't want to create a management command and wanted to copy/paste from a django shell_plus. I ran heroku run python manage.py shell_plus --ipython, but when I tried to run %edit, I got this warning: In [1]: %edit IPython will make a temporary file named: /tmp/ipython_edit_g6lgdrb3/ipython_edit_ki541tmw.py Editing... /bin/sh: 1: vi: not found /app/.heroku/python/lib/python3.7/site-packages/IPython/core/magics/code.py:699: UserWarning: Could not open editor warn('Could not open editor') How can I solve this problem? -
Django Cookiecutter upgrade best practice
I built an application using cookiecutter-django by @pydanny back in May, docker-compose was used for both dev and production environments and it's running very well, Now I have a requirement for asynchronous tasks and I want to use Celery, I did not choose celery when using the cookiecutter tool way back at the beginning, What's the best way to integrate celery into my project ? Also noting that I will probably take this opportunity to upgrade docker-compose from version 2 to 3, bring mailgun, Django etc. to the latest versions Is it too messy to integrate to a live project ? Should I just create a new project using the cookiecutter tool ? Thanks -
Override to_representation in List serializer class
I have a serializer that implements the BaseSerializer class in which I'm using the to_representation function to do a function call like so: class ItemSerializer(serializers.BaseSerializer): def to_representation(self, instance): ret = super().to_representation(instance) ret['log'] = SERVICE.log(instance.id) return ret class Meta: list_serializer_class = ItemListSerializer model = models.Item fields = '__all__' I also have a list serializer for the same ItemListSerializer which looks like this: class ItemListSerializer(serializers.ListSerializer): def create(self, validated_data): items = [models.Item(**item) for item in validated_data] return models.Item.objects.bulk_create(items) What I want to do is override the to_representation method in the ItemSerializer for when I want to get the entire list of Items. I basically want to avoid doing a function call per item and instead do a bulk call for all the items when the list of items is requested for performance reasons. Is there a good way to do this? I followed these docs for creating the ItemListSerializer:https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior but it only talks about overriding create and update methods. -
Cron not doing my task without the command python manage.py runcrons
I managed to make a function that sends lots of emails to every user in my Django application, for that I used the django-cron package. I need to send the emails in a particular hour of the day, so I added in my function the following: RUN_AT_TIMES = ['14:00'] schedule = Schedule(run_at_times=RUN_AT_TIMES) The problem is that this function is only called if I run the command: python manage.py runcrons What can I do to make the application work after one single call of the command python manage.py runcrons? P.S.: I need this application to work in Heroku as well. -
Problem reading rendered barcode via reportlab with barcode scanner
Hello I have a problem here I have a view that renders barcode on html template which I print using a thermal printer but the scanner doesn't read the code after it has been printed # utility.py from reportlab.lib.units import mm from reportlab.graphics.barcode import createBarcodeDrawing from reportlab.graphics.shapes import Drawing, String from reportlab.graphics.charts.barcharts import HorizontalBarChart class MyBarcodeDrawing(Drawing): def __init__(self, text_value, *args, **kw): barcode = createBarcodeDrawing('Code128', value=text_value, barHeight=15*mm, humanReadable=False) Drawing.__init__(self,barcode.width,barcode.height,*args,**kw) self.add(barcode, name='barcode') if __name__=='__main__': #use the standard 'save' method to save barcode.gif, barcode.pdf etc #for quick feedback while working. MyBarcodeDrawing("HELLO WORLD").save(formats=['gif','pdf'],outDir='.',fnRoot='barcode') #views.py def barcode(request, stock_id): obj = get_object_or_404(Stock, id=stock_id) d = utility.MyBarcodeDrawing(obj.description,) d.save(formats=['svg','pdf'],outDir='static_root/media/',fnRoot='barcode') barcodePicUrl = "barcode/barcode.svg" return render_to_response('barcode.html', {'url':barcodePicUrl}) were did I go wrong? -
Get a list of object created for the last days grouped by day
I need to get a list of objects that have been created in the last few days, grouped by day, in order to display the data in a chart. Now I do this: Model.objects.filter( created__date__lte=today, created__date__gte=today-delta ).values('created').annotate(count=Count('id')) But, I get the following queryset: <SoftDeletableQuerySet [{'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 208157, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 297617, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 385555, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 474287, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 507464, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 552092, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 585314, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 618656, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 652501, tzinfo=<UTC>), 'count': 1}, {'created': datetime.datetime(2018, 10, 15, 13, 5, 35, 696849, tzinfo=<UTC>), 'count': 1}]> As you can see, the objects were grouped by creation date, but this field is DateTimeField, not DateField, therefore, grouped in milliseconds. I'm trying to do this: Model.objects.filter( created__date__lte=today, created__date__gte=today-delta ).values('created__date').annotate(count=Count('id')) But I get the following error: FieldError: Cannot resolve keyword 'date' into field. Join on … -
How to display the creation dates only once
When I create an item, I automatically add the creation date. The body is written to the body itself, it is saved in the database and then displayed. And the creation time is automatically added to created_at. I need to display all the dates under which any items were created in sorted order. -- models.py from django.db import models class Todo(models.Model): body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) --views.py def all(request): date = Todo.objects.order_by('created_at') return render(request, 'todo/all.html', {'date':date}) In the view, I try to use order_by and output it in the template --all.html {% for date in date %} <h1>{{ date.created_at }}</h1> {% endfor %} Then I get this situation. This is practically what I need, but the output depends on the number of items under each date, and I just need to print the date once, that is, Oct. 13,2018 and Oct.14,2018, each date once, how to achieve this result? -
Session mismatch in Django [duplicate]
This question is an exact duplicate of: Unwanted Session duplication in Django I have a situation in which: User 1 modifies its session. User 2 browses and his session becomes also User 1. That's very strange. In the session table, everything looks OK, it happens with or without Redis. setting SESSION_SAVE_EVERY_REQUEST to True fixes it. What can cause such a behavior? I'm using Django 1.6 -
Annotating ManyToMany Fields and produce difference - Django
My code looks like this, Class A: amount = models.DecimalField(); Class B: amount = models.DecimalField(); Class C: amount = models.DecimalField(); Class D: amount = models.DecimalField(); Class Common(models.Model): a = models.ManyTomanyField(A) b = models.ManyTomanyField(B) c = models.ManyTomanyField(C) d = models.ManyTomanyField(D) Expected Common Queryset will be queryset = a__amount+b__amount-c__amount-d__amount == 0 -
Django Serializer Model LeftJoin
Hi im new to Django and i hope someone can help me with my little problem ^^ i have Models like this: class Article(model.Model): name = model.CharField(max_length=100) ... class Stock(model.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, null=True) quantity = model.IntegerField(max_digits=10, default=1) quality = models.CharField(max_length=15, choices=[(tag.value, tag.value) for tag in States]) ... and i want to get a list of all Articles with all the Stocks like [{ name: 'Bla', stock: [{ quantity: 22, quality: 'good', }] }] I got a View: class ArticleListView(ListAPIView): queryset = Article.objects.all()??? serializer_class = ArticleStockSerializer permission_classes = (IsAuthenticated, HasAccess) But im not sure how to use it and a Serializer like this: class ArticleStockSerializer(ArticleSerializer): stock = serializers.SerializerMethodField() def get_stock(self, obj): stock = StockSerializer() return stock class Meta(ArticleSerializer.Meta): model = Article fields = ArticleSerializer.Meta.fields + ('stock',) Not working and i cant find the right way to use it. Hope someone can help me :) thx and regards xQp