Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '(len(seasons))' from 'range(seasons)'
I have a var with the name 'seasons' that returns the number of seasons in a tv show and I know for a fact it does work and it returns it. but I'm trying now to loop through it so if a tv show has 6 seasons it echos: season1, season2.. etc but it doesn't work. code : {% for season in range(seasons) %} <li rel="p{{season}}" class="activate-panel">الموسم {{ season }}</li> {% endif %} reference to how I got the number of seasons from db. -
Does select_for_update see rows added by another select_for_update transaction?
I want to create a model with ID equal to the current greatest ID for that model plus one (like auto-increment). I'm considering doing this with select_for_update to ensure there is no race conditions for the current greatest ID, like this: with transaction.atomic(): greatest_id = MyModel.objects.order_by('id').last().id MyModel.objects.create(id=greatest_id + 1) But I'm wondering, if two processes try to run this simultaneously, once the second one unblocks, will it see the new greatest ID inserted by the first process, or will it still see the old greatest ID? For example, say the current greatest ID is 10. Two processes go to create a new model. The first one locks ID 10. Then the second one blocks because 10 is locked. The first one inserts 11 and unlocks 10. Then, the second one unblocks, and now will it see the 11 inserted by the first as the greatest, or will it still only see 10? In the select_for_update docs, it says: Usually, if another transaction has already acquired a lock on one of the selected rows, the query will block until the lock is released. So for my example, I'm thinking this means that the second process will rerun the query for the … -
Django's ListView - How to customise it
I am sorry if this is a duplicate, but I did not find any answer to my question. My issue below I am really struggling to understand how to customise my views when using ListView. I read the Django documentation, but I find it very brief. What I would like to do is to count the questions for each topic and return the topic with the most questions. I would be able to count the number of questions for each topic with the following line of code in my models.py (Topic class): def questions_count(self): return Question.objects.filter(question__topic = self).count() However, I would like to return only the most popular Topic and the number of questions. Using a function-based view, I would loop over the topics, and I would create two variables storing the topic name and the number of questions. However, with the ListView I do not know whether to use get_context_data(), get_queryset() or something else. My view class: class TopicsView(ListView): model = Topic context_object_name = 'topics' template_name = 'home.html' My models: class Topic(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Question(models.Model): .... topic = models.ForeignKey(Topic, related_name='questions', on_delete=models.CASCADE) .... -
Django queryset difference method loosing ordering
I am trying to use Django's built in difference method on a queryset but it seems ordering is gone after the difference method is used. objects = self.get_index_children() print("objects are %s ordered" % objects.ordered) featured_recipes = objects.filter(featured=True)[:3] print("featured_recipes are %s ordered" % featured_recipes.ordered) latest_recipes = objects.difference(featured_recipes) print("latest_recipes are %s ordered" % latest_recipes.ordered) objects are True ordered featured_recipes are True ordered latest_recipes are False ordered . <---- Is this supposed to be like this or bug on django side ? if so is there any proper way of finding difference between 2 querysets ? -
Django StreamingHttpResponse: How to choose size to yield?
When using StreamingHttpResponse from a Django view, called from gunicorn + gevent worker, behind nginx, how to determine (perhaps by reasoning) a good length for each iteration of yield-ed bytes? Below is a snipped-down example of such a view: def my_view(request): def yield_bytes(): while ... some_bytes = ... # What's a good len(some_bytes) here? yield some_bytes return StreamingHttpResponse(yield_bytes()) -
Change attribute field type in SQLite3
I am trying to change the field type of one of attributes from CharField to DecimalField by doing an empty migrations and populated the migrations log with the following: from __future__ import unicode_literals from django.db import migrations from decimal import Decimal def populate_new_col(apps, schema_editor): #Plug data from 'LastPrice' into 'LastPrice_v1' in the same model class 'all_ks'. all_ks = apps.get_model('blog', 'all_ks') for ks in all_ks.objects.all(): if float(ks.LastPrice): #Check if conversion to float type is possible... print ks.LastPrice ks.LastPrice_v1, created = all_ks.objects.get_or_create(LastPrice_v1=Decimal(float(ks.LastPrice)*1.0)) else: #...else insert None. ks.LastPrice_v1, created = all_ks.objects.get_or_create(LastPrice_v1=None) ks.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0027_auto_20190301_1600'), ] operations = [ migrations.RunPython(populate_new_col), ] But I kept getting an error when I tried to migrate: TypeError: Tried to update field blog.All_ks.LastPrice_v1 with a model instance, <All_ks: All_ks object>. Use a value compatible with DecimalField. Is there something I missed converting string to Decimal? FYI, ‘LastPrice’ is the old attribute with CharField, and ‘LastPrice_v1’ is the new attribute with DecimalField. -
Referencing MPTTModel in another regular model? django
I'm using django-mptt as utility to categorize my articles. My model setup is as follow : class Genre(MPTTModel): name = models.CharField(max_length=100, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Article(models.Model): source = models.ForeignKey('Source', on_delete=models.CASCADE) url = models.URLField(max_length=300) text = models.TextField() title = models.CharField(max_length=500, blank=True) Now my question is: If I have for example the following hierarchy: 'Politic > Election > SomeCountry' and I have an article that has 'SomeCountry' category, should I add to the Article model a ForeignKey field: category = models.ForeignKey('Genre', blank=True, null=True, on_delete=models.CASCADE) And thus I have to set the value of the category field of the article as 'SomeCountry'. Or I should add a ManyToManyField to the Article model: category = models.ManyToManyField('Genre', blank=True) And thus I have to set the value for the category field of the article as ['Politic', 'Election', 'SomeCountry']. -
How to split and get values of list saved as a string?
Input: var = "["run", "play", "splash"]" o/p required: "run" "play" "splash" or var = ["run", "play", "splash"] -
how to shuffle the data retrieved from the database
I have book template which display more info about the book like title,price and author etc.. in the same template I've similar books section where I want to display similar book to the featured book according to the classification (both have the same classification) and to do that i'm thinking of shuffling books i retrieve from the database instead of just using normal loop to make it more dynamic as in every book has that classification, the page shows different books not the same books every time here's the code in views.py def book(request, book_id): book = get_object_or_404(Book, pk=book_id) similar_books = Book.objects.all()[:4] book_context = { 'book': book, 'similar_books': similar_books } return render(request, 'books/book.html', book_context) and this the the code in my template <div class="row"> <div class="col py-5 text-center"> <h3 class="mb-5">Similar books</h3> <div class="row d-flex justify-content-center"> {% for similar_book in similar_books %} {% if similar_book.classification == book.classification and similar_book.id > book.id %} <div class="col-md-3"> <a href="{% url 'book' similar_book.id %}"><img src="{{ similar_book.img.url }}"></a> <a href="{% url 'book' similar_book.id %}"><p class="mt-2">{{ similar_book.title}}</p></a> <p class="text-muted">{{ similar_book.author }}</p> <p>{{ similar_book.price }}</p> </div> {% endif %} {% endfor %} </div> </div> the reason i'm including similar_book.id > book.id is that i don't want it to … -
Django: Reverse URL patterns not found
I am trying to make regex (Django URL) work with with the queryset. I tried different patterns with template URL but it didn't work. Generic ListView: class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs["tag"] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") My URL: path("products/<slug:tag>/", views.ProductListView.as_view(), name='products'), Template: I couldn't get it work in tempalte like below. I tried passing different keyword arguments but it is not working: <li class="nav-item"> <a class="nav-link" href="{% url 'products' %}">Products</a> </li> Error: Reverse for 'products' with arguments '('',)' not found. 1 pattern(s) tried: ['products\\/(?P<tag>[-a-zA-Z0-9_]+)\\/$'] -
Braintree success method Django
def checkout(request, **kwargs): client_token = generate_client_token() existing_order = get_user_pending_order(request) publishKey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': token = request.POST.get('stripeToken', False) if token: try: charge = stripe.Charge.create( amount=100*existing_order.get_cart_total(), currency='usd', description='Example charge', source=token, ) return redirect(reverse('carts:update_records', kwargs={ 'token': token }) ) except stripe.CardError as e: message.info(request, "Your card has been declined.") else: result = transact({ 'amount': existing_order.get_cart_total(), 'payment_method_nonce': request.POST['payment_method_nonce'], 'options': { "submit_for_settlement": True } }) if result.is_success or result.transaction: return redirect(reverse('sharing:upload', kwargs={ 'token': token }) ) else: for x in result.errors.deep_errors: messages.info(request, x) return redirect(reverse('carts:checkout')) get_total = existing_order.get_cart_total() get_total.save() context = { 'order': existing_order, 'client_token': client_token, 'STRIPE_PUBLISHABLE_KEY': publishKey } return render(request, 'carts/checkout.html', context) I want to extend if result.is_success or result.transaction: this method to upload as well def upload(request, token): if result.is_success or result.transaction: model = CN form_class = uploadform form = uploadform(request.POST or None, request.FILES or None) if form.is_valid(): data = form.save() upload = form.cleaned_data['upload'] client_need = form.cleaned_data['client_need'] data.save() return render(request, 'sharing/upload.html', {"form": form}) else: return redirect(request, 'sharing:index', context) But when i use the method i get an error saying name 'result' is not defined When i request checkout method result = checkout(request) if result.is_success or result.transaction: model = CN form_class = uploadform form = uploadform(request.POST or None, request.FILES or None) … -
Is there an API or Library to help finding a song from lyrics part?
I'm writing django app and there's a page where people can write quotes from a song and based on that I would like to display songs that contain this lyrics, so they can select from which song are the lyrics. I googled about it and the closest I got was PyLyrics and similar, but unfortunately they only get lyrics from songs, so the opposite of what I wanted. -
In Jinja Template, some lines of code are in {} and some are in {% %}. What's the difference?
I am learning Django and I am unable to get why some code is merely in { } brackets and while other is {% %}. What'the difference? Example is given below: {% extends "layout.html" %} {% block body %} <ul> {% for user in users %} <li> <a href="{{ user.url }}">{{ user.username }}</a> </li> {% endfor %} </ul> {% endblock %} -
Django MPTT tree as model filter in admin
I have a model linked to a related model that is a Django MPTT tree model, I would like to be able to filter the first model using the Django MPTT tree in the admin console. class Tenders(models.Model): ... sector=models.ForeignKey(Sector, to_field='sectorId', null=True, blank=True,on_delete=models.CASCADE) ... class Sector(MPTTModel): name = models.CharField(max_length = 255) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,related_name='children') sectorId = models.IntegerField(default=0,null=True,unique=True) In the Django admin I would like to set up the filters for the Tenders model such that the Django-MPTT tree is the filter. I have tried using the following: class adminTenders(admin.ModelAdmin): def linkTo(self,obj): return mark_safe("""<a href='{}' target="_blank" >Tender Link</a>""".format(obj.tenderLink)) linkTo.short_description='' list_display=( 'title', 'linkTo', 'sector', 'region', 'repository', 'id', ) list_filter=( ('sector', TreeRelatedFieldListFilter), ) admin.site.register(Tenders,adminTenders) However I get the following error when trying to run this and I cant figure it out: File "py36/lib/python3.6/site-packages/mptt/admin.py", line 314, in field_choices mptt_level_indent * levels_dict[pk]) KeyError: 0 Any help would be greatly appreciated. -
how to access child entire record in parent model in django rest framework
I am new to Django rest framework.i am trying to get child model records to the parent model as a field so that all the RefreshmentImage models records are available in games_sports list.i have posted sample code. model.py class Refreshment(models.Model): title = models.CharField(max_length=200, unique=True) type = models.CharField(max_length=200) charges = models.DecimalField(max_digits=12, decimal_places=2, help_text="Charges per hour") class RefreshmentImage(models.Model): refreshment = models.ForeignKey(Refreshment, on_delete=models.CASCADE) image = models.FileField(upload_to="refreshment_image/", null=True, blank=True) serializers.py class EntertainmentSerializer(serializers.ModelSerializer): class Meta: model = Refreshment fields = '__all__' class RefreshmentImageSerializer(serializers.ModelSerializer): refreshment = EntertainmentSerializer(read_only=True, many=True) class Meta: model = RefreshmentImage fields = '__all__' views.py def all_games_sports(request): entertainment = Refreshment.objects.all() serialize = EntertainmentSerializer(instance=entertainment,many=True) serial = RefreshmentImageSerializer(instance=entertainment,many=True) main = {'status': True, 'code': CODE_SUCCESSFUL, 'msg': SUCCESS, 'games_sports': serialize.data,'image':serial.data} return HttpResponse(json.dumps(main), content_type='application/json') what i got is like: games_sports": [ { "id": 1, "title": "yyy", "type": 1, "charges": "500.00", }, { "id": 2, "title": "xxxxx", "type": "something", "charges": "501.00", } ******* ], "image": [ { "id": 1, "image": null, "date_created": "2019-03-03T08:16:15.538024+05:30" }, ********** ] i want it to be: games_sports": [ { "id": 1, "title": "yyy", "type": 1, "charges": "500.00", "image": [ { "id": 1, "image": image_path, "date_created": "2019-03-03T08:16:15.538024+05:30" }, } *********** ], -
Upload APNs certificate to AWS Lambda
I am using Django with Zappa to connect to serverless AWS Lambda. To get APNs (Apple Push Notification services) up and running, I originally had to upload my certificate file to the server, so that my backend can access it whenever it needs to. But now that I migrated to AWS Lambda, I am not sure how to upload the certificate file. I use this package django-push-notifications to use APNs and in my Django settings, I have PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": os.path.join(BASE_DIR, "../../Certificates_and_keys/prod_pushcert.pem"), "APNS_TOPIC": "org.reactjs.native.example.Spap", "UPDATE_ON_DUPLICATE_REG_ID": True, "USER_MODEL": "social.User", } Where the value for APNS_CERTIFICATE is the path of the APNs certificate file. Before using AWS Lambda, I had another server where I uploaded the certificate file with ftp. I don't know how to do that with AWS Lambda. Any suggestions? -
Django Ldap Autentication only works with DN_TEMPLATE
trying to get my django authentication work with an ldap server but i cannot login, I've managed to do it using forumsys test ldap server using AUTH_LDAP_USER_DN_TEMPLATE, but adding both ou with LDAPSearchUnion (what i will need in my real project) it only shows "incorrect username/password" (my message in case of failed login) Here's my settings.py: AUTH_LDAP_SERVER_URI = "ldap://ldap.forumsys.com" AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearchUnion( LDAPSearch("ou=mathematicians,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"), LDAPSearch("ou=scientists,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"), ) AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', ) Views.py: def login_page(request): if request.user.is_authenticated: return redirect("list") context = { 'form': LoginForm, } if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('list') else: messages.error(request, 'Wrong username or password') return redirect("login") return render(request, 'login.html', context) Does anyone knows what could I be doing wrong? -
database "Todolist" does not exist with postgresql on django
Even thoug I have created a database with the name Todolist, I am still getting the error database does not exist after python manage.py makemigrations. I am using postgresql -
Django 2.1 - Check if answer is correct and return a feedback
I'm trying to develop a system like quiz. I have a model like this: from django.db import models from questoes.models import Questao class MCQuestao(Questao): def checar_correta(self, ans): answer = Alternativa.objects.get(id=ans) if answer.correta is True: return True else: return False class Meta: verbose_name = 'Questão múltipla escolha' verbose_name_plural = 'Questões múltiplas escolhas' class Alternativa(models.Model): questao = models.ForeignKey(MCQuestao, on_delete=models.CASCADE) resposta = models.TextField() fundteorico = models.TextField() correta = models.BooleanField(default=False) def __str__(self): return self.resposta class Meta: verbose_name = "Alternativa" verbose_name_plural = "Alternativas" I would like it when someone clicks the "Responder" button to return some feedback on the screen (fundteorico in this case, class Alternativa). How would i do that? Thanks! -
Why do i need to reset the winsock?
So we have a distributed system. The steps that happens when i login to the application: I go to abc.xyz.com SSO with OAuth2 starts Redirects to the application, and the makes calls to load certain data from a different endpoint, e.g. abcapi.xyz.com The loading process is seen to fail from the browser's dev tool. With an error net::ERR_CONNECTION_RESET During this time, if i try the same process from a different pc, it works just fine. And to recover from this state on the first pc is to reset the winsock on the adapter or to disconnect and reconnect to the network. Some more details: abc.xyz.com is an Angular5 app, and the abcapi.xyz.com is using nginx + gunicorn + django Running a packet capture when the issue occur, shows that the client p/c didnt recieve any ACK from abcapi.xyz.com and hence sent a reset RST flag (which i think is the reason for the log entry net::ERR_CONNECTION_RESET I am still trying to gather more details like: 1. Kind of network adapters and driver version of the p/c that encounter this issue. 2. Trying to find a way to see what is in the p/c's winsock that gets fixed after following the … -
Using django cut filter in template with regexp
I have URLs that all end with an image filename. I am trying to strip all of the URL except the filename, however the URL path can vary, as I have images in different directories. I am wondering if there is someway to use regexp with the cut filter, as I have not found a way to do so yet. An example of what I am trying to do: {{ instance.image_url|cut:"/images/products/*/dl_img/" }}' Where * refers to various directory names, such as beds or tables Is there an easy way to do this in a template? -
a double call from the django database
I create a website. I use Python and Django. In my database, I have two tables - the first table has been texts, the second table has been images. Table Page contains such fields as: title, text. Text is the content of the given subpage. Table Image contains images, which are used in subpages. When I write in html file: {{ Page.text|safe }} {{ Image.code|safe }} I get a result a text and below him an image. I want, that the image is appeared inside text. I mean that in the page I can see part of text from field 'text' in table 'Page', an image from table 'Image' and below the picture further part of the text from field 'text' in table 'Page'. My problem is that I do not know how to call a record from the table 'Image' inside table 'Page'. I try to write {{ Image.code|safe }} inside the text field, but website reads this as 'text', not directing. Could you help me? PS. Please, dirkgroten do not write something, your comments are not useful... -
How to completely uninstall django-taggit from my project?
I want to remove django-taggit from my project, but when I removed the 'taggit' app from the INSTALLED_APPS, the following error occurred: raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration SourceManager.0002_auto_20190218_2112 dependencies reference nonexistent parent node ('taggit', '0002_auto_20150616_2121') I think this error occurred because django-taggit has migration files, so how to safely remove it from my project? -
Django render many-to-many
I'd like to render in html a table including all books read by different people (= ManyToMany relationship) models.py: class Reader (models.Model): name = models.CharField(max_length = 100) books = models.ManyToManyField(Book) def __str__ (self): return self.name filters.py: class ReaderFilter(django_filters.FilterSet): name = django_filters.CharFilter(field_name='name', lookup_expr='icontains') books = django_filters.CharFilter(field_name='books',lookup_expr='icontains') views.py: def readers_overview(request): readerfilter = ReaderFilter(request.GET, queryset=Reader.objects.all()) return render(request, 'readers/readers.html', {'readerfilter' : readerfilter }) html: <thead> <tr> <th>Name</th> <th>Title</th> </tr> </thead> <tbody> {% for reader in readerfilter.qs %} <tr> <td> {{reader.name}} </td> <td> {{reader.books}} </td> </tr> {% empty %} <tr> <td colspan="5"> No such reader exists</td> </tr> {% endfor %} </tbody> I get the following as output under title: " readers.Book.None" how can I solve this? -
handling duplicate objects with custom slugs via mixins
we have a django app with two objects, cities and events. a common url pattern for us would be: app.com/city/name-of-city/event/name-of-event where name-of-city and name-of-event are slugs. ex: class City(models.Model): name = models.CharField(max_length=100, unique=True) slug = AutoSlugField(populate_from='name', always_update=True, unique=True, sep='-', max_length=255) ... events get their slug the same way on the Event model: slug = AutoSlugField(populate_from='name', always_update=True, unique_with='city', sep='-', max_length=255) the issue I'm having difficulty sorting out is how to handle an instance where the same city has multiple events with the same name. mixins.py class CityMixin(object): city_slug_url_kwarg = 'slug' city = None def fetch_city(self, request, *args, **kwargs): if not self.city: self.city = get_object_or_404( City, slug=kwargs.get(self.city_slug_url_kwarg)) return self.city def get_context_data(self, **kwargs): kwargs.setdefault('city', self.city) return super(CityMixin, self).get_context_data(**kwargs) def dispatch(self, request, *args, **kwargs): """ Sets 'city' within the view """ self.city = self.fetch_city(request, *args, **kwargs) return super(CityMixin, self).dispatch(request, *args, **kwargs) class EventMixin(CityMixin): city_slug_url_kwarg = 'city_slug' event_slug_url_kwarg = 'slug' event = None def fetch_event(self, request, *args, **kwargs): if not self.event: event = get_list_or_404( Event, slug=kwargs.get(self.event_slug_url_kwarg)) return self.event def dispatch(self, request, *args, **kwargs): """ Sets 'city' and 'event' within the view """ user = request.user self.city = self.fetch_city(request, *args, **kwargs) self.event = self.fetch_event(request, *args, **kwargs) if self.event.city != self.city: raise Http404 return super(EventMixin, self).dispatch(request, *args, …