Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why picture not update?
I'm created a view to update the info from a model called Profile, and this updated everything except the picture. This is the method that I called to upload the picture: def url(self, filename): route = 'users/{}/{}'.format(self.username, filename) return route and this is the model: class Profile(User): picture = models.ImageField('Imagen', blank=True, null=True, upload_to=url) born_date = models.DateField('fecha de nacimiento', blank=True, null=True) def set_picture(self, picture): self.picture = picture This is my view: class ProfileUpdateView(SameUserPermissionViewMixin, UpdateView): model = Profile template_name = 'account/profile_update_form.html' form_class = ProfileUpdateForm def get_success_url(self): return reverse_lazy('account:detail_user', kwargs={'pk': self.object.pk}) def form_valid(self, form): self.object = form.save(commit=False) self.object.picture = form.cleaned_data['picture'] print(form.cleaned_data['picture']) self.object.save() return super(ProfileUpdateView, self).form_valid(form) and my form class is this: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['username', 'first_name', 'last_name', 'email', 'picture', 'born_date', 'sex'] In the view when I print form.cleaned_data['picture'] return None -
ElasticSearch - bulk indexing for a completion suggester in python
I am trying to add a completion suggester to enable search-as-you-type for a search field in my Django app (using Elastic Search 5.2.x and elasticseach-dsl). After trying to figure this out for a long time, I am not able to figure yet how to bulk index the suggester. Here's my code: class SchoolIndex(DocType): name = Text() school_type = Keyword() name_suggest = Completion() Bulk indexing as follows: def bulk_indexing(): SchoolIndex.init(index="school_index") es = Elasticsearch() bulk(client=es, actions=(a.indexing() for a in models.School.objects.all().iterator())) And have defined an indexing method in models.py: def indexing(self): obj = SchoolIndex( meta = {'id': self.pk}, name = self.name, school_type = self.school_type, name_suggest = {'input': self.name } <--- # what goes in here? ) obj.save(index="school_index") return obj.to_dict(include_meta=True) As per the ES docs, suggestions are indexed like any other field. So I could just put a few terms in the name_suggest = statement above in my code which will match the corresponding field, when searched. But my question is how to do that with a ton of records? I was guessing there would be a standard way for ES to automatically come up with a few terms that could be used as suggestions. For example: using each word in the phrase as … -
django-auth-ldap AUTH_LDAP_FIND_GROUPS_PERMS not working
I'm running Django 1.8.18 and django-auth-ldap 1.2.11 authenticating against Active Directory. My current configuration authenticates properly against the AD, however, when I enabled AUTH_LDAP_FIND_GROUPS_PERMS it doesn't seem to do anything. I've previously tried AUTH_LDAP_MIRROR_GROUPS (which works without any problem), and found all of the user's groups created. The only slight issue is that it also remove any local group memberships the user had. In any case, after having the groups auto-created by AUTH_LDAP_MIRROR_GROUPS I would expect AUTH_LDAP_FIND_GROUPS_PERMS would auto-add the user to that same group on the next login. However, this did not happen. The only change in configuration was those two lines. The AUTH_LDAP_GROUP_TYPE is set to NestedActiveDirectoryGroupType() Any ideas why users aren't being added to the groups with matching names? -
"myobject" is not Iterable, but my obect is erased
hello i have a trouble about Object is not Iterable in django, when i delete a obect, the message from django is 'myobject' object is not iterable. here my views.py def delete(request, id=None): myobject = get_object_or_404(MyObject, id=id) myobject.delete() context = {'myobject': myobject} return render(request, "cat/home.html", context) and here my home.html {% block content %} {% for foo in myojbect %} {% if foo.name_myobject %} <p><a href="{% url 'cat:detail_myobject' id=foo.id %}">{{ foo.name_myobject }}</a></p> {% endif %} {% if foo.desc %} <p>{{ foo.desc }}</p> <a href="{% url 'cat:delete_myobject' id=foo.id %}">Delete</a> {% endif %} {% endfor %} {% endblock %} if i push "delete", Error appears like that " 'myobject' is not iterable" but my object is erased -_- Thank you sir for help :) -
My custom user authentication for y custom Django user model wont work
I made my own user model so users could sign up with email. However, when i tried to log in with my custom login, it wouldn't work My Views: def login_view(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(usename=email, password=password) if user: login(request, user) return redirect('/account/') else: print(str(password)+" "+str(email)) else: form = LoginForm() return render(request, 'users/login.html',{'form': form}) My authentication backend: class UserAuth(object): def authenticate(self, request, username=None, password=None,): try: user = User.objects.get(email=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None My User model: class UserManager(BaseUserManager): def _create_user(self, first_name, last_name, username, email, is_admin, password=None, **extra_fields): """ creates a User with first name, last name, username, email, password """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, username=username, email=email, is_admin=is_admin, is_active=True, **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, first_name, last_name, username, email, password, **extra_fields): return self._create_user( first_name, last_name, username, email, False, password, **extra_fields ) def create_superuser(self, first_name, last_name, username, email, password=None, **extra_fields): return self._create_user( first_name, last_name, username, email, True, password, **extra_fields ) class User(AbstractBaseUser): first_name … -
add action to react form for redirecting
I have a django sign up form that I recently changed to a react modal window, I created the modal successfuly like this var WindowModal = React.createClass({ getInitialState(){ return {showModal: false}; }, close(){ this.setState({showModal: false}); }, open(){ this.setState({showModal: true}); }, handleEmailChange: function(e) { this.setState({email: e.target.value}); }, handlePasswordChange: function(e) { this.setState({password: e.target.value}); }, handleSubmit(){ console.log("EMail: " + this.state.email); console.log("Password: " + this.state.password); }, render () { return ( <div> <a onClick={this.open} className="action action-signin">Already have a Studio account? Sign In</a> <Modal show={this.state.showModal} onHide={this.close}> <Modal.Header closeButton> <Modal.Title className="modal-title">Sign In</Modal.Title> </Modal.Header> <Modal.Body> <h1>Sign In to Studio</h1> <Form horizontal> <FormGroup controlId="formHorizontalEmail"> <Col componentClass={ControlLabel} sm={2}> Email </Col> <Col sm={10}> <FormControl type="email" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange}/> </Col> </FormGroup> <FormGroup controlId="formHorizontalPassword"> <Col componentClass={ControlLabel} sm={2}> Password </Col> <Col sm={10}> <FormControl type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/> </Col> </FormGroup> <FormGroup> <Col smOffset={2} sm={10}> <Button type="submit" onClick={this.handleSubmit}> Sign in </Button> </Col> </FormGroup> </Form> </Modal.Body> <Modal.Footer> <Button onClick={this.close}>Close</Button> </Modal.Footer> </Modal> </div> ); } }); what I need is when I click on the submit button, my data gets passed to the django view for processing, so i was wondering how i can set my form to have an action attribute that points to the view -
DRF, send help text of model field
For instance, shipping_required = models.BooleanField( pgettext_lazy('ProductVariant field', 'shipping required'), default=True ) When I send over shipping_required field, I'd like to send over pgettext_lazy('ProductVariant field', 'shipping required') as well as a first step to make our app internationalized. Would there be a convenient way to do it with DRF? -
Django + Nginx + uWSGI: Internal Server Error
I'm getting an "Internal Server Error" when I try to GET my site. This is what's on the log file: Tue May 9 02:46:31 2017 - *** Starting uWSGI 1.9.17.1-debian (64bit) on [Tue May 9 02:46:31 2017] *** Tue May 9 02:46:31 2017 - compiled with version: 4.8.2 on 23 March 2014 17:15:32 Tue May 9 02:46:31 2017 - os: Linux-3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 Tue May 9 02:46:31 2017 - nodename: ip-172-31-24-23 Tue May 9 02:46:31 2017 - machine: x86_64 Tue May 9 02:46:31 2017 - clock source: unix Tue May 9 02:46:31 2017 - pcre jit disabled Tue May 9 02:46:31 2017 - detected number of CPU cores: 1 Tue May 9 02:46:31 2017 - current working directory: / Tue May 9 02:46:31 2017 - writing pidfile to /run/uwsgi/app/landingpage/pid Tue May 9 02:46:31 2017 - detected binary path: /usr/bin/uwsgi-core Tue May 9 02:46:31 2017 - setgid() to 33 Tue May 9 02:46:31 2017 - setuid() to 33 Tue May 9 02:46:31 2017 - your processes number limit is 15926 Tue May 9 02:46:31 2017 - your memory page size is 4096 bytes Tue May 9 02:46:31 2017 - detected max file descriptor number: 1024 … -
Generic Foreign Key nested serializers
Im seem to have this issue when using Generic Foreign Key with custom name that cause the serialisation to fail when i have them nested in other serializers I can view view the Note list view just fine, and observe that it has a relation to exercise, but when i try and view the exercise view (list or detail), it seem to be trying to use the default field names (object_id, content_type) in the Note serialisation. I have attached the all the relevant code. Tell me if you guys need any more models.py class Base(models.Model): # id = models.AutoField(primary_key=True) changedate = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='user_%(class)s', on_delete=models.CASCADE) status = models.CharField(max_length=50) valid = models.BooleanField() class Meta: abstract = True class Note(Base): related_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) related_object_id = models.PositiveIntegerField() related_content_object = GenericForeignKey('related_content_type','related_object_id') note = models.TextField() def __unicode__(self): return self.note serilizer.py class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note owner = serializers.ReadOnlyField(source='owner.username') fields = ('id', 'changedate', 'owner', 'status', 'valid', 'related_content_type', 'related_object_id', 'note') class ExerciseSerializer(serializers.ModelSerializer): notes = NoteSerializer(many=True, read_only=True) content_type = serializers.SerializerMethodField() modifiers = ModifierSerializer(many=True, read_only=True) def get_content_type(self, obj): return ContentType.objects.get_for_model(Exercise).id class Meta: model = Exercise owner = serializers.ReadOnlyField(source='owner.username') fields = ('id', 'changedate', 'owner', 'name', 'exercise_group', 'status', 'valid', 'notes', 'content_type', 'modifiers') The error is Cannot … -
URL after successful logging in Django
I have different type of users each with different template.How can I change my URL to url(r'^something/$', views.login_user, name='login_user'), from url(r'^$', views.login_user, name='login_user'), when logged in. my views if user is not None: if user.is_active: login(request, user) if user.groups.filter(name='hod').exists(): return render(request, 'retest/hod.html', {}) elif user.groups.filter(name='principal').exists(): return render(request, 'retest/principal.html', {}) elif user.groups.filter(name='Rep').exists(): return render(request, 'retest/home.html', {}) elif user.groups.filter(name='Ajithzen').exists(): return render(request, 'event/ajithzen.html', {}) elif user.groups.filter(name='graphics').exists(): return render(request, 'event/ashok.html', {}) elif user.groups.filter(name='Event_incharge').exists(): return render(request, 'event/incharge.html', {}) elif user.groups.filter(name='Event_coord').exists(): return render(request, 'event/chair.html', {}) elif user.groups.filter(name='IEEE').exists(): return render(request, 'event/ieee.html', {}) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) else: return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) return render(request, 'retest/login.html') urls.py url(r'^$', views.login_user, name='login_user'), -
Passing django query results to another query
I am trying to first select all categories that are part of a class and pull all posts that are tied to those categories with a limit of 3 per category. class ForumCategory(models.Model): name = models.CharField(max_length=40) description = models.TextField() class_id = models.ForeignKey(Class) class ForumPost(models.Model): name = models.CharField(max_length=100) details = models.TextField() author = models.ForeignKey(User) class_id = models.ForeignKey(Class) category = models.ForeignKey(ForumCategory) created_at = models.DateTimeField(auto_now_add=True) Here is my queryset: categories = ForumCategory.objects.filter(class_id=class_id) forum_post = ForumPost.objects.filter(id__in=categories.values_list('id', flat=True)).order_by('-id')[:3] -
send many notifications by sockets using Django and Channels
I want to know what is the best approach, iterate every user and send the message by his own socket(this means to have only one socket listening for multiple events) or subsrcribe all the users i want to notify and send by only one socket or channel(this means having many sockets from different channels). Or there is something better to do? -
Serving pdf files by link, downloaded as pdf.html
Crated function to allow users download pdf files by link. Works fine, the only problem that what user save is .html. So all files are file.pdf.html. def download(request,ticket_id): ticket_path = str(Ticket.objects.get(id=ticket_id).upload) with open('files/media/' + ticket_path, 'rb') as pdf: response = HttpResponse(pdf.read()) response['content_type'] = 'application/pdf' response['Content-Disposition'] = 'attachment;filename="file.pdf"' return response Why? -
Django Rest Framework - AssertionError Fix your URL conf, or set the `.lookup_field` attribute on the view correctly
I'm trying to return as single object (not a queryset) that is specific to a user without them having to specify an identifier/pk within the requested URL. Each user has an organisation FK. i.e. http://website/organisation and not http://website/organisation/1 I'm receiving the following error, since it's expecting this identifier: AssertionError: Expected view OrganisationDetail to be called with a URL keyword argument named "user__organisation_id". Fix your URL conf, or set the.lookup_fieldattribute on the view correctly. How/What do I need to specify when using the RetrieveModelMixin/GenericAPIViewso that it returns a singular object linked by a FK? my view class: class OrganisationDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,generics.GenericAPIView): serializer_class = OrganisationDetailSerializer lookup_field = 'pk' #yes, I know this is the default and there's no need to speciy def get_queryset(self): return Organisation.objects.filter(pk=self.request.user.organisation_id) def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) my url: url(r'^api/v1/organisation/$', OrganisationDetail.as_view()), my model: class Person(AbstractUser): organisation = models.ForeignKey(Organisation, related_name='members', null=True) is_admin = models.BooleanField(default=False) def __str__(self): return self.first_name + " " + self.last_name + " - " + self.email -
Django: Heroku deploy not migrating properly
I'm new to Heroku and I am trying to do my first deploy with a change in my models. Now I already have some important stuff in my app's database that I don't want to lose (I'm using PostgresSQL). Anyway, I did those few improvement to my app's model and it works alright locally, but when I try to deploy it just gives me the Internal Server Error: /lares/ ProgrammingError at /lares/ column lares_imovel.referencia does not exist I am used to throwing makemigrations and migrate locally and than just git push heroku master Anyway, I also tried the heroku run python manage.py migrate afterwards, but I get the same result every time. I deleted all my migrations files and created them again for this particular app, still it works locally and the issue remains on production. Do you guys have any idea why this is happening? I don't know if any of my code is necessary, I'm pretty sure the problem is not there, but if requested I can post it here. Thanks! -
Django with html/js error - Forbidden (CSRF cookie not set.)
I've tried almost everything I could see over several days to make this happen. I've tried this on my friend's computer and it works there, but not on mine. Currently, I have the following views.py and index.html for django server. index.html <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://www.w3schools.com/lib/w3.css"> <title title="Audio Editor">Audio Editor</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </head> <main> <h1><img src="http://blog.blogtalkradio.com/wp-content/uploads/2011/10/Audio_Icon.jpg" alt="http://blog.blogtalkradio.com/wp-content/uploads/2011/10/Audio_Icon.jpg" style="float:left;width:30px;height:width;"><img src="https://image.freepik.com/free-icon/question-mark_318-52837.jpg" alt="https://image.freepik.com/free-icon/question-mark_318-52837.jpg" style="float:left;width:30px;height:width;"> Obfuscate your audio</h1> <br> <br> <body> <h3>1. Upload your audio:</h3> <input type="file" id="audio-file" onchange="fileAdded()"/> <p id="message"></p> <br> <h3>2. Obfuscate and download:</h3> <button id="obfuscate-button" onclick="obfuscate()">Obfuscate!</button> </body> <br> <br> <hr> <a href="https://github.com/mgjo5899/web_audio">Check out the github page!</a> </main> <script> var file = undefined; var audio_formats = ["mp3", "wav"]; //var csrftoken = getCookie('csrftoken'); // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } /* function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ … -
Why is Django template pattern matching with wrong view and causing a NoReverseMatch error?
I have a NoReverseMatch error. The pattern it is showing is not the one it is supposed to be associated with. The error: NoReverseMatch at /games/list/ Reverse for 'game_single' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['games/(?P<pk>\\d+)/$'] I dont understand why its trying to Reverse for 'game_single' when the view is supposed to be 'game_list' My Main urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ #leaving the r'' blank between the parenthesis makes it the #default URL url(r'', include('blog.urls')), url(r'^admin/', admin.site.urls), url(r'^games/', include('code_games.urls')), ] My code_games app urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^list/$', views.game_list, name='game_list'), url(r'(?P<pk>\d+)/$', views.game_single, name='game_single'), url(r'^new/$', views.game_new, name='game_new'), ] My code_games app views.py #view for seeing all games def game_list(request): games = Game.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'code_games/game_list.html', {'games': games}) #view for seeing/playing an individual game def game_single(request, pk): games = get_object_or_404(Game, pk=pk) return render(request, 'code_games/game_single.html', {'games': games}) #view for adding a new game def game_new(request): if request.method == "POST": form = GameForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('game_single', pk=post.pk) else: form = GameForm() return render(request, 'code_games/game_new.html', {'form': form}) My Template: {% extends … -
CSRF protect a django-cms plugin - token missing or incorrect
I've got a plugin intended to sit in the footer (static placeholder) of all pages. It's just a form to subscribe to an newsletter, I catch the form submission in the plugin render(), but running this on a remote server returns a CSRF verification failed. Request aborted. Is it possible to explicitly add csrf_protect() to a CMSPluginBase subclass? forms.py class NewsletterSubscriptionForm(forms.Form): email = forms.EmailField( widget=forms.TextInput(attrs={ 'class': u'textinput', 'placeholder': u'Enter your email address', 'type': u'email' }) ) def clean_email(self): """ Subscribe the user if the email is valid. """ email = self.cleaned_data['email'] subscribe_to_campaign( email, campaigns=[settings.NEWSLETTER_CAMPAIGN_UID] ) return email newsletter.html <form class="newsletter__form" action="." method="post"> {% csrf_token %} <h4 class="newsletter__title">Subscribe to our newsletter</h4> {% for field in form.email %} <div class="newsletter__row"> {{ field }} <button type="submit" name="newsletter_signup" class="newsletter__submit"> </button> </div> {% endfor %} </form> cms_plugins.py class NewsletterPlugin(CMSPluginBase): cache = False model = CMSPlugin name = _("Newsletter Signup") render_template = "cms/plugins/newsletter.html" def render(self, context, instance, placeholder): request = context['request'] if request.POST: if 'newsletter_signup' in request.POST: form = NewsletterSubscriptionForm(request.POST) context.update({ 'form': form, 'newsletter_completed': form.is_valid() }) return context context.update({ 'instance': instance, 'placeholder': placeholder, 'form': NewsletterSubscriptionForm() }) return context -
Django: One endpoint, POST open to all, GET requires authentication
Using Latest Django/Django Rest Framwork. I can't figure out how to allow one endpoint to have the following rules: POST - open to anyone (AllowAny permission) GET - Authenticated. There is no way to have conditional permissions depending on the method, so there's only one way to change permissions are on a per-view like this: @api_view(['POST']) @permission_classes([AllowAny]) def users_view(request): return Response("Okay!") But there i no way to do something like this (I have a default requirement to be authenticated in my settings.py): @api_view(['GET']) def users_view(request): return Response("Okay - you're authenticated") @api_view(['POST']) @permission_classes([AllowAny]) def users_view(request): return Response("Okay! this is a public endpoint") How can I do this? -
Select2 parameter for templateResult and templateSelection different (django)
I've got a strange problem. I have a product select element item in my web application. Because there are quite many products in the database I've decided to load them dynamically with select2. The issue is that I want to pass an additional parameter (Unit) that would be displayed opposite the select box. So to find a product i use Django as backend and my method looks like this. class FindProductAjaxView(AjaxableResponseMixin, CreateView): model = Product form_class = ProductForm def get_ajax(self, request, *args, **kwargs): query = request.GET.get('q', None) if query: products = Product.objects.filter(name__icontains=query).values( "pk", "name", "unit") results = list(products) return JsonResponse(data={'items': results}, safe=False) else: return JsonResponse(data={'success': False, 'errors': 'No mathing items found'}) So it returns the pk, name and unit fields correctly. Here is the script I use to create my select2 product inputs. <script> function initProductSelect2 (select) { select.select2({ placeholder: "Wyszukaj...", ajax: { url: '/recipes/find_product', dataType: 'json', delay: 250, language: 'pl', data: function (params) { return { q: params.term, // search term page: params.page }; }, processResults: function (data) { data = data.items.map(function (item) { return { id: item.pk, text: item.name, name: item.name, unit: item.unit }; }); return { results: data }; }, cache: true }, escapeMarkup: function (markup) { … -
How do I access own parameters in class based views - Django
I have this url: url(r'^ceniky-edit/kadernictvi/$', views.CenikView.as_view(typ='kadernictvi'), name='ceniky-edit-kadernictvi'), and I want to get value of "typ" in my view, how I can do that ? Thank you guys. -
Django ranked search with multiple fields containing a match
I am having trouble with non-distinct results in a ranked search query set. I am using Django's full-text search with a PostgreSQL DB. To make the search fuzzy, I implemented PostgreSQL trigrams. I built a backend that holds artists and their associated albums. I want to be able to search artists by their name, or the name of an album they made. It works fine except that if an artist has a self-titled album then the query_set will have that artist twice. This backend is an API and will have a separate frontend so I would rather not hide the duplicate in the frontend. def search_filter(self, queryset, name, value): if value: query = SearchQuery(value) vector = SearchVector( 'artist_name', 'albums__name' ) queryset = queryset.annotate( rank=SearchRank(vector, query), similarity=TrigramSimilarity('artist_name', value) + TrigramSimilarity('albums__name', value) ).filter(similarity__gt=0.3).order_by('-rank', '-similarity') return queryset I have tried running .distinct('id') but this fails due to not ordering by 'id' first, but if I order by 'id' before rank then the ordering is incorrect and rank/similarity are useless. I have also tried forcing the queryset to evaluate after distinct('id') but before ordering, but the ordering step just makes another call to the DB which causes the distinct to fail due to not … -
PDF preview using embed tag with Django
Well, I'm new on this. I want to know if I can display a PDF file in my Django template using embed tag like: <embed src="/file/to/pdf/some_pdf.pdf" /> I tried: <embed src="{{form.file_path.value}}" width="500" height="525" /> Where {{form.file_path.value}} is my pdf file directory or name saved in the database. This is the forms.py file: fields = [ 'title', 'publication_date', 'file_path', 'size', 'authors', 'editorial', ] labels = { 'title': 'Title', 'publication_date': 'Publication Date', 'file_path': 'File preview', 'size': 'Size', 'authors': 'Authors', 'editorial': 'Editorial', } widgets = { 'title':forms.TextInput(attrs={'class':'form-control'}), 'publication_date':forms.TextInput(attrs={'class':'form-control'}), 'file_path':forms.TextInput(attrs={'class':'form-control'}), 'size':forms.TextInput(attrs={'class':'form-control'}), 'authors': forms.CheckboxSelectMultiple(), 'editorial': forms.Select(attrs={'class':'form-control'}), } And this is the views.py file: class BookList(ListView): model = Book template_name = 'book/book_list.html' context_object_name = 'book' queryset = Book.objects.prefetch_related('authors') paginate_by = 10 def get_context_data(self, **kwargs): context = super(BookList,self).get_context_data(**kwargs) book_list =Book.objects.all() paginator = Paginator(book_list,self.paginate_by) page = self.request.GET.get('page') try: book_list = paginator.page(page) except PageNotAnInteger: file_book = paginator.page(1) except EmptyPage: book_list = paginator.page(paginator.num_pages) context['book_list'] = book_list return context -
DRF: Dynamically select Serializer class based on field value
I'm working in an application where I need to build an API to return product catalogs to the application's client, this is how my models look. class Category(models.Model): name = models.IntegerField(...) description = models.CharField(...) category_type = models.PositiveIntegerField(...) . . . class Product(models.Model): code = models.IntegerField(...) category = models.ForeignKey(Category, ..) . # Common product fields . class ProductA(Product): product_a_field = models.IntegerField(..) . . . class ProductB(Product): product_b_field = models.IntegerField(...) . . . Except for the common fields (inheritated from Product) both models ProductA and ProductB are very different from each other. What I want to do is to send a different set of products to the clients based on the value of the Category.category_type field. I would like to simplify my Category Serializer as: class CategorySerializer(serializers.ModelSerializer): . def __init__(self, *args, **kwargs): # # Some code to select the product Serializer # products = ProductSerializer() class Meta: model = Category fields = ('name', 'description', 'category_type', 'products') Is there any way to achieve this? I'm using Python3, Django 1.10, and DRF 3.6. -
Django Set foreign key to parent value on delete
I have a model, Location with a self-referential foreign key. On deletion of a location's parent, I want to set its parent_id to its grandparent's ID, but not surprisingly, the following throws the error name 'parent' is not defined: class Location(Model): parent = models.ForeignKey('self', models.SET(parent)) If I were to delete Colorado from this table: | id | name | parent_id | |----|----------|-----------| | 1 | USA | NULL | | 2 | Canada | NULL | | 3 | Colorado | 1 | | 4 | Utah | 1 | | 5 | Denver | 3 | | 6 | Boulder | 3 | I would want the result to look like this: | id | name | parent_id | |----|----------|-----------| | 1 | USA | NULL | | 2 | Canada | NULL | | 4 | Utah | 1 | | 5 | Denver | 1 | | 6 | Boulder | 1 |