Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError with whitenoise.django
I've installed whitenoise with command: pip install whitenoise But when I'm moving on whitenoise.django there is only this error: raise ImportError( '\n\n' 'Your WhiteNoise configuration is incompatible with WhiteNoise v4.0\n' 'This can be fixed by following the upgrade instructions at:\n' 'http://whitenoise.evans.io/en/stable/changelog.html#v4-0\n' '\ -
How to iterate through multidimensional list/dict in a template
if I write : {{ object_list.1.related_items }} in my template everything is fine and I get what I want but if I write: {% for i in object_list %} {{ object_list.i.related_items }} {% endfor %} I don't get a result. Can somebody tell me how I solve this problem? -
object is not iterable but the other one is fine with the same type
I dont understand why this doesn't work while Series.object.all() works. Both have the same type Series right? but how come the below isn't working? 'Series' object is not iterable {% for tv_series in series %} {{ tv_series.name }} {% endfor %} def series_pg(request, slug): series = Series.objects.get(name=slug) class Series(models.Model): name = models.CharField(max_length=128, unique=True) descritpion = models.TextField() slug = models.SlugField(unique=True) def __str__(self): return self.name -
Validate Against Webmail Addresses in Django
Is it possible to validate "entirely in Django" the user registration process in my application, avoiding the use of a public webmail addresses? How can I do this? Should I have some kind of "black list" (for GMail, Hotmail and so on)? Thanks! -
__init__() takes 1 positional argument but 2 were given. response = wrapped_callback(request, *callback_args, **callback_kwargs)
my views.py file class Home(TemplateView): @staticmethod def get_name(request): form = NameForm() #function in forms.py return render(request, 'blog/post.html', {'form': form}) @staticmethod def post(request): global text form = NameForm(request.POST) if form.is_valid(): text = form.cleaned_data['your_name'] i dont where is the error anyone plz help args = {'form': form, 'text': text} return render(request, 'blog/post.html', args) -
downloadable font: download failed for Django app with static files in AWS S3
I am using a Summernote a simple WYSIWYG editor to allow users to edit their fonts in the textfield. For the icons to load it needs to download a font called summernote. This file is located in my aws folder with the below filepath Amazon S3/some_bucket_name/static/summernote/font This font loads perfectly in my dev environment. However when it comes to production the font is not loading and I see boxes like below instead of the icons I have added to my CORS permissions. This took care of the CORS error that I was getting before. <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>http://www.my_site.com</AllowedOrigin> <AllowedOrigin>https://www.my_site.com</AllowedOrigin> <AllowedOrigin>https://my_site.com</AllowedOrigin> <AllowedOrigin>https://my_site.com</AllowedOrigin> <AllowedOrigin>http://127.0.0.1:8000</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>HEAD</AllowedMethod> <AllowedMethod>DELETE</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> <AllowedHeader>Content-*</AllowedHeader> <AllowedHeader>Host</AllowedHeader> </CORSRule> </CORSConfiguration> But now I am getting a new error Status code: 403 Forbidden downloadable font: download failed (font-family: "summernote" style:normal weight:400 stretch:100 src index:1): status=2147746065 source: https://some_bucket_name.s3.amazonaws.com/static/summernote/font/summernote.woff?1d9aeaaff0a8939558a45be6cd52cd4c downloadable font: no supported format found (font-family: "summernote" style:normal weight:400 stretch:100 src index:3) source: (end of source list) Does anyone know how to get around this issue -
Include routed groups for authenticated url
Include routed groups for authenticated url. I need to create authentication groups and enable the routes according to the permissions. For example. urlpatterns = [ @adminGroup path('admin/', admin.site.urls), @userGroup, @adminGroup path('/home', home.site.urls), ] -
Django: allowing user to like post only once
Just wrote a function on Django that allows users to vote only once per post(bug). As you will see that it's been done by pressing the link. Just would like to know if it's possible to hide the Vote button after user voted once? Here is the code, hope it helps: views.py: def vote(request, bug_id): bug = get_object_or_404(BugTable, pk=bug_id) if request.user.is_authenticated: bug.vote += 1 try: Vote.objects.create(bug=bug, user=request.user) bug.save() except IntegrityError: messages.success(request, 'You already voted for this bug') return redirect(bugfix) return render(request, 'detail.html', {'bug': bug}) models.py class BugTable(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bug_name = models.CharField(max_length=50, blank=False) vote = models.IntegerField(default=0) def __str__(self): return self.bug_name class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bug = models.ForeignKey(BugTable, on_delete=models.CASCADE, related_name='voter') class Meta: unique_together = ('user', 'bug') detail.html {% block features %} <h5 style="margin-top: 10px;"><strong>{{ bug.bug_name }}</strong></h5> <a href="{% url 'vote' bug.id %}">Vote</a> {{ bug.vote}} {% endblock %} Tried with jQuery simple function using .hide method, did not work. May be there is something i could use just by entering {% if %} function? Thanks for any advice -
Filtering out private pages from tags
I recently made a tag cloud in my Wagtail-powered website, but I'm running into a problem where some tags (called "Topics" in my site) with only private articles/pages in them appear. So far, I did something like this to get the number of articles in each tag and filter them out if there are none: topics_with_articles = Topic.objects.annotate(num_articles=models.Count("articlepage")).filter(num_articles__gt=0) filtered_topics = topics_with_articles.order_by("-num_articles").values("name", "slug", "num_articles") And I have my models set up like this: from modelcluster.models import ParentalManyToManyField, ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag, TaggedItemBase @register_snippet class Topic(Tag): class Meta: ordering = ["slug"] proxy = True verbose_name = "Topic" verbose_name_plural = "Topics" class ArticleTopic(TaggedItemBase): content_object = ParentalKey("ArticlePage", related_name="article_topics") class ArticlePage(Page): topics = ClusterTaggableManager(through="articles.ArticleTopic", blank=True) I couldn't find an easy solution to get this to work, so how can I do that? -
How to implement varying access to different users dynamically in Django?
This is somewhat of a larger "fuzzy problem", where I'm currently trying to wrap my head around the problem and finding a good place to start. I'm creating an education web application using Django, where users who sign up all will be enrolled into different "courses". All of these should use the same "global" models, but with different data based on the course. The end goal is for admins easily being able to create multiple courses, where users can only access the pages in the courses they are currently enrolled in. I've currently broken this into the following sub-problems: Making a page and the content tied to the models tied to a specific "course-id" Only giving users specific authorization to the pages of the courses they are enrolled in (using the corresponding course-id) Customizing the admin view to allow admins to easily create new courses and add course-specific content - especially as the number of added courses scale up to +10 Finding a solution for the "enrollment process", where the admin can decide (either at registration, or after-the-fact, or both), which users are tied to which courses. I have tried googling around, but can't find anything specifically addressing this. The … -
Upload file in django by ajax
I have a code, which can upload some information from text-forms, but I don`t know how to do it with files. I use FileField in models.py and i get invalid form. When I use this form without FileField - all works. forms.py class UploadForm(forms.ModelForm): prefix = 'upload_form' class Meta: model = UploadModel fields = ('title', 'file', 'ended_date') file.is $(document).ready(function(){ var $uploadForm = $('.form-upload'); $uploadForm.submit(function(event){ event.preventDefault(); var $formData = $uploadForm.serialize(); var $thisURL = $uploadForm.attr('data-url') || window.location.href; $.ajax({ method:'POST', url: $thisURL, data: $formData, success: handleSuccess, error: handleError, }); function handleSuccess(data){ console.log(data.message); $myForm[0].reset() } function handleError(ThrowError){ console.log(ThrowError); } }); }); views.py def add_new(request): form_upload = UploadForm(request.POST, request.FILES, prefix='upload_form') print(form_upload.is_valid(), request.is_ajax()) if form_upload.is_valid() and request.is_ajax(): new_file = form_upload.save(commit=False) new_file.author = request.user new_file.created_date = timezone.now() new_file.save() data = { 'message': 'form is saved' } return JsonResponse(data) form_upload = UploadForm() return render(request, 'sharing/index.html', {'form_upload': form_upload}) -
Campo hacer un campo Hidden Formulario Django y pasar PK
Tengo dos tablas class Afiliado(models.Model): nombre = models.CharField(max_length=50) class Pago(models.Model): # Tabla Cabecera de Pago afiliado = models.ForeignKey(Afiliado, on_delete=models.CASCADE) fecha_pago = models.DateField(null=True, blank=True) este es mi formulario para agregar los pagos: class RegistroPago(forms.ModelForm): class Meta: model = Pago fields = [ 'afiliado' , 'fecha_pago', ] labels = { 'afiliado':'Nombre del Afiliado', 'fecha_pago':'Fecha de Pago', } widgets = { 'afiliado': forms.HiddenInput(attrs={'class':'form-control'}), 'fecha_pago': forms.TextInput(attrs={'class':'form-control'}), } como pueden ver en el widgets puse el campo 'afiliado' como HiddenInput porque si lo pongo como un select me aparece un combobox con la lista de afiliados y lo que quiero es que ese pago se asocie automáticamente a el usuario que tengo seleccionado Formulario de Pagos Por favor alguien me pude orientar como hago para pasarle el id del afiliado al formulario para que lo relacione directamente. class PagoCreate(CreateView): model = Pago form_class = RegistroPago template_name = 'crear_pago.html' success_url = reverse_lazy('lista_pagos') mi Template : {% extends 'base/base.html' %} {% block content%} <title> {% block title %}Crear Pago{% endblock %} </title> <div class="container"> <div class="header clearfix"> <form method="post">{% csrf_token %} <div class="col-sm-6" style="background-color:white;"> {{ form.as_p }} </div> <button type="submit" class="btn btn-primary btn-sm">Guardar</button> <a class="btn btn-danger btn-sm" href="/pago" role="button" >Cancelar</a> </form> </div> </div> {% endblock %} -
Django Detail View and update Filefield
I have the model class File(models.Model): name = models.CharField(max_length=30, default='.cc') codefile = models.FileField(...) with the serializer class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('id', 'name', 'codefile') read_only_fields = ('id', 'name') and the viewset class FileViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin): queryset = File.objects.all() serializer_class = serializers.FileSerializer def perform_create(self, serializer): serializer.save(name=self.request.data['codefile']) So by going to localhost:8000/files I see a list of all File-objects and can upload new files via post. How can I implement a detail-view with the django rest framwork, such that at localhost:8000/files/5 I would see the name and file of the File with pk=5, and with the option to update/reupload this codefile? -
Django ORM - How to left join on two conditions with many to many field
I have two models: class Subscription(models.Model): name = models.CharField(max_length=100, unique=True) class Email(models.Model): email = models.EmailField(unique=True) subscriptions = models.ManyToManyField(Subscription) is_confirmed = models.BooleanField(default=False) I need to simulate sql query through django orm select * from newsletter_subscription ss left join newsletter_mail_subscriptions ms on ss.id = ms.subscription_id and ms.mail_id = <mail_id>; so I can see if the mail is subscribed to each subscription by getting the entire list of available subscriptions i need something like FilteredRelated: q = Subscription.objects.annotate( is_subscribe=FilteredRelation( 'mail_subscriptions', condition=Q(mail_subscriptions__mail_id=10) ) ) But FilteredRelation doesn’t support conditions that span relational fields -
Can you create parent object and list of children objects in one same form
Im new to django and still learning its full potential. I have two models One is the parent (GoodsReceivedNote) and the other are the items for that note (One to Many). I realize a normal ModelForm is not going to work here as i need to create the parent and list of child objects in the same form. I looked in to InlineFormSets but as far as I undestood I need to create the parent object first and then assign it to my children. Also looked at this link : http://sayhelloworld.co/create-parent-child-model-objects-in-one-form-with-django/ how ever they are using the date to get the recent parent object and add it to the child which doesnt seem the best way GoodsReceivedNote.py class Goodsreceivednote(models.Model): GOODS_INWARDS = 'INWARDS' GOODS_REJECTED = 'REJECTED' NOTE_TYPES = ( (GOODS_INWARDS, GOODS_INWARDS), (GOODS_REJECTED, GOODS_REJECTED), ) rec_note_id = models.CharField(primary_key=True, max_length=20) note_date = models.DateField() type = models.CharField(choices= NOTE_TYPES, max_length=15, default=GOODS_INWARDS) The Items.py class Goodsreceiveitem(models.Model): received_item_id = models.CharField(primary_key=True, max_length=255) rec_note_id = models.ForeignKey(Goodsreceivednote, models.PROTECT) item_id = models.ForeignKey(Inventory, models.PROTECT) item_qty = models.IntegerField() Thanks In Advance ! Cheers ! -
How to customize Django confirmation form and view in password request
I'm trying to implement resetting password in Django 1.6 with my own templates instead of the custom Django administration auth_view and I've mainly followed this tutorial;https://ruddra.com/posts/implementation-of-forgot-reset-password-feature-in-django/. I've managed to customize the reset password page and the email sent for resetting the password but the confirmation page, which the resetting link is sent to is blank when I try to use the PasswordResetConfirm() class without Django administration forms (which work). In short, when clicking the email link for resetting password the webpage is blank but titled Confirmation at the top, so something in the code is blocking or missing. I've tried numerous of tutorials but nothing works. I've tried by placing 'django.contrib.admin' in INSTALLED_APPS in Settings after the applications, which 'unplugs' the custom Django administration form for changing password in the confirmation step to a blank page with the text Confirmation on top. I've also changed the template password_reset_confirm.html In views.py, following from linked tutorial class PasswordResetConfirmView(FormView): template_name = "registration/password_reset_confirm.html" success_url = 'registration/password_reset_complete.html' form_class = SetPasswordForm def post(self, request, uidb64=None, token=None, *arg, **kwargs): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() form = self.form_class(request.POST) assert … -
Django TypeError: 'int' object is not iterable when return QuerySet with method value_list()
class TopViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = MovieSerializer #queryset = Movie.objects.annotate(comment_count=(Count('comments'))).order_by("-comment_count","-rating") queryset = Movie.objects.all() def get_queryset(self): from_date = self.request.query_params.get('from_date') to_date = self.request.query_params.get('to_date') movies = super(TopViewSet, self).get_queryset() if from_date and to_date: movies = movies.filter(year__range=[from_date, to_date]).values_list('id','name','comments') return movies I'd like to return only 3 values instead of all in serializer class. Or there is another method to return only three values from Queryset -
Celery task is not inserted in the queue and thus application is blocked when task is called
I am trying to integrate Celery into my django application, to run some things async. First stop, would be the send_mail functionality. I have: Setup redis running at 6379. Also added the relevant setting to settings.py CELERY_BROKER_URL = 'redis://localhost' Setup a celery worker celery -A celery_settings worker -l DEBUG -E Here is the code that calls it(inside a view): send_email_async.apply_async([ 'Subject', 'body, 'your_favorite@friend.com', [user.email]], countdown=1 ) return JsonResponse({'key': 'value'}) Here is the task: @task def send_email_async(subject, body, from_mail, to, fail_silently=False): send_mail(subject, body, from_mail, to, fail_silently) return True I can see, via a debugger, that the execution is reaching the celery task.Though it looks like it is blocked there without further clues on what to do. This is my init.py from __future__ import absolute_import, unicode_literals from eservices_hua.celery_settings import app as celery_app __all__ = ['celery_app'] It is the first time I use celery+django so assume nothing :) -
How to get the related child type when the parent can have multiple child type?
Let's say I have 3 models like this: class Parent(models.model): CHILD_CHOICES = ( ('ChildA', 'Child A'), ('ChildB', 'Child B'), ) name = models.CharField(max_lenght=50) child_type = models.CharField(choices=CHILD_CHOICES, max_length=25, blank=True) class ChildA(models.model): parent = OneToOneField('Parent',related_name='child_a',blank=True, null=True) class ChildB(models.model): parent = OneToOneField('Parent',related_name='child_b',blank=True, null=True) When the parent is created the associated child model is created (depending on the child_type field). How to retrieve the according Child type from a Parent in the Parent view in order to map a custom Form to the right child? (for editing the Parent and the right Child Type in the same view) (In my real scenario I have 10 diffrent child type) -
How to ensure at least one of the Fields is not blank in Serializer?
I am creating an API to update some of my model's fields, I want the fields to be optional (i.e let the user choose which of the models fields he wants to change). At the same time, I don't want to accept an empty request (a request with empty body) I tried with "required=False" but this will allow empty requests. class NotificationsSerializer(serializers.Serializer): notify_add_friend = serializers.BooleanField(required=False) notify_added_to_group = serializers.BooleanField(required=False) Is there anyway to define a validator for the whole serializer or something? -
Control requests to view and template output in django
This is a view for get all the records in the EducationalRecord model: def all_education_resume(request): RESUME_INFO['view'] = 'education' educations_resume = EducationalRecord.objects.all().order_by('-created_date') template = 'resumes/all_resume.html' context = {'educations_resume': educations_resume, 'resume_info': RESUME_INFO} return render(request, template, context) Now, if I want to write exactly this view for other models (like job resumes, research resumes , etc.), I must another view one separately. My question is: How can I get a view for all these requests, so first check the URL of the request and then do the relevant query? How can I control URL requests in my views? My other question is exactly the same as my first question,with this difference: control view that must render in specific template.In other words,in second question the ratio between the template and the view is instead of the ratio of the view to the url or how to create a template for multiple views (for example, for a variety of database resume resumes, I have a template) and then, depending on which view render, the template output is different. I have implemented these two issues as follows: I wrote a view for each of request! In each view, I set the value of RESUME_INFO['view'], and then … -
Problem with sending client side data to server side (django)
I am trying to send client side data(html5 api for latitude and longitude) to server side. I am not familiar with JS but i found the code for two JS functions for latitude and longtitude: function latitude() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { return document.getElementById('latitude').setAttribute("value", position.coords.latitude); } ); } else { alert("Sorry, your browser does not support HTML5 geolocation."); } } function longitude() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { return document.getElementById('longitude').setAttribute("value", position.coords.longitude); } ); } else { alert("Sorry, your browser does not support HTML5 geolocation."); } } Then I created django form which will receive the data: class CordsForm(forms.Form): latitude = forms.CharField(widget=forms.TextInput( attrs={'id': 'latitude', 'type': 'hidden'})) longitude = forms.CharField(widget=forms.TextInput( attrs={'id': 'longitude', 'type': 'hidden'})) Also i created view which uses the form: def index(request): if request.method == 'POST': cords_form = CordsForm(request.POST) if cords_form.is_valid(): latitude = cords_form.cleaned_data['latitude'] longitude = cords_form.cleaned_data['longitude'] print(longitude) # only for testing print(latitude) # only for testing else: cords_form = CordsForm() return render(request, 'weather/index.html', {'form': cords_form}) This is the index page: {% extends 'weather/base.html' %} {% block content %} <form method="POST" id="geoform" name="geoform"> {% csrf_token %} {{ form.latitude }} <script>latitude();</script> {{ form.longitude }} <script>longitude();</script> </form> <script> document.addEventListener("DOMContentLoaded", function (event) { document.getElementById("geoform").submit(); }); </script> {% endblock content %} … -
Multiple choice fields in django aren't displayed appropriately in html
I created a form with a field having .MultipleChoiceFields() views.py cat_choices = ( ('Internships', 'Internships'), ('Scholarships', 'Scholarships'), ('Entrance exams', 'Entrance exams'), ) class ProfileForm(forms.ModelForm): category = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=cat_choices) class Meta: model = Profile fields=('about','category') I used it in the profile.html <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> ul { list-style-type: none; } * { box-sizing: border-box; } input{ width: 100%; font-family: 'Lato', sans-serif; font-size: 15px; border: 1px solid gray; border-radius: 4px; margin: 5px 0; opacity: 0.85; display: inline-block; line-height: 40px; text-decoration: none; } .container { position: relative; border-radius: 5px; background-color: white; padding: 20px 0 30px 0; } .col { width: 50%; left: 60px; margin: auto; padding: 0 50px; margin-top: 6px; } .row:after { content: ""; display: table; clear: both; } </style> </head> <body> <div class="container"> <form method="post"> <div class="row"> <div class="col"> <div> <strong><p> About </p></strong> {% csrf_token %} {{ profile_form.about }} </div> <div> <strong><p> Select categories you are interested in </p></strong> {% csrf_token %} {{ profile_form.category }} </div> <input type="submit" value="Submit"> </div> </div> </form> </div> </body> </html> I have two inputs (about and category). The category is a MultipleChoiceFields type. The inputs are styles in css in profile.html. But I want two different styles for two of the … -
Django Filter if field is not None
I have a model where I can set expire_date. I want to filter the model and when there's a expire_date set it should filter if the expire_date is lower than now. I tried it to do with Case and When but I can't filter in a When function, can I? News.objects.all().annotate(is_expired=Case(When(F("expire_date") != None, then=False if F("expire_date") <= datetime.now() else True))).filter(is_expired=False) -
Django link multiple table
I have four models as follows: class deals_view(models.Model): deal = models.ForeignKey(dealsModel, on_delete=models.CASCADE, related_name='deal_view') client = models.ForeignKey(client_profileModel, on_delete=models.CASCADE) client_ip = models.GenericIPAddressField(protocol='both') date_added = models.DateField(auto_now_add=True) class client_profile(models.Model): GENDER_NAME = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Others') ) user = models.ForeignKey(User, unique=True, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER_NAME, null=True) address = models.CharField(max_length=100, null=True) dob = models.DateField(null=True) class deals(models.Model): GENDER_NAME = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Others'), ('A', 'All'), ) AGE_RANGE = ( ('A1', '18-25'), ('A2', '25-40'), ('A3', '40-55'), ('A4', '55-100'), ('A5', '18-100'), ('AL', '13-100'), ('T1', '13-18') ) store = models.ForeignKey(storesModel, on_delete=models.CASCADE, related_name='deals_store') title = models.CharField(max_length=30) description = models.CharField(max_length=160) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.ForeignKey(categoriesModel, on_delete=models.PROTECT) targeted_gender = models.CharField(max_length=1, choices=GENDER_NAME) targeted_age = models.CharField(max_length=2, choices=AGE_RANGE) is_active = models.BooleanField(default=False) created_date = models.DateField(auto_now_add=True) expiry_date = models.DateField(default=(dt.now() + td(days=30))) class stores(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, unique=True) about = models.CharField(max_length=300) company_name = models.CharField(max_length=100) I want to list all deals for the current month and its corresponding number of views per gender. so far I've tried the following; i can get all the info but it seems i have multiple hits of the database: self.storeObj = storesModel.objects.prefetch_related('deals_store').get(id=storeid) self.deals_store = self.storeObj.deals_store segmentedInfo = self.deals_store.all().prefetch_related('deal_view').filter(deal_view__date_added__range=((datetime.today() - timedelta(days=30)), datetime.now())).distinct() for seg in segmentedInfo: for x in seg.deal_view.select_related('client').distinct(): print(x.client.gender) Is …