Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to split a TextField to create content?
I have a model named Name, with the following code: class Name(models.Model): owner = models.ForeignKey(UserProfile) nombre = models.CharField(max_length=60) multinombres = models.TextField() I want that if you choose CharField just enter a name string text, but if you choose TextField you can enter multiple names text strings one per line. I have the idea to do something like: multinombres.splitlines() How and where do I implement it? -
Django Haystack - ElasticSearch result window too large
I've been working on a web app developed with Django which uses Postgres and ElasticSearch. It uses ElasticSearch since the database stores a lot of data which increases by the hour. To get things working quickly I used django-haystack 2.6.0 which allows me to access Elastic Search quite easily. So far so good. The problem appeared when I made a query on ElasticSearch and the result was really big. The error I got was the following: TransportError: TransportError(500, u'search_phase_execution_exception', u'Result window is too large, from + size must be less than or equal to: [10000] but was [12602]. See the scroll api for a more efficient way to request large data sets. This limit can be set by changing the [index.max_result_window] index level parameter.') After some research I tried increasing the result windows size but this won't work in the long term since the query-set size keeps increasing. Also django-haystack doesn't appear to implement scroll api so I can't follow the advice shown in the stack trace. My question is: is there anyway I can fix this error and get a big query set with django-haystack maybe paginating the results in some way? Or is there a better approach without … -
django 1.11 makemigration error with custom range field
at djangosnippets I found a example for a IntegerRangeField (https://djangosnippets.org/snippets/3016/) from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models class IntegerRangeField(models.IntegerField): def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs): self.min_value, self.max_value = min_value, max_value validators = [] if isinstance(max_value, int): validators.append(MaxValueValidator(max_value)) if isinstance(min_value, int): validators.append(MinValueValidator(min_value)) models.IntegerField.__init__( self, verbose_name, name, validators=validators, **kwargs ) def formfield(self, **kwargs): defaults = {'min_value': self.min_value, 'max_value':self.max_value} defaults.update(kwargs) return super(IntegerRangeField, self).formfield(**defaults) My model: class MyModel (models.Model): ..... automatic_logout_value = IntegerRangeField (min_value=5, max_value=1440, blank=True, null=True, default=30) After starting "python manage.py makemigrations" I get the error: c:\python34\lib\site-packages\django\db\migrations\state.py line 437, in from_model e, TypeError: Couldn't reconstruct field automatic_logout_value on myApp.myModel: __init__ () got multiple values for keyword 'validators' Any idea whats wrong with the code? Thanks! -
Django read uploaded CSV file
I am using Python 3 and Django 1.8. When we upload files. Before you save the file, I can read csv file. And the csv file to see. def index(request): if request.POST and request.FILES: csvfile = request.FILES['csv_file'] dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024)) csvfile.open() reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect) return render(request, "index.html", locals()) The third line gives the following error: cannot use a string pattern on a bytes-like object -
How to use django rest api in existing django project
I am newbie in django rest framwork.I want to know how can i implement django rest api in my existing normal django project. Is it better approach to create new api (html and form) using django rest? or create api(rest framwork) and call it from existing project? -
django beautifulsoup web scraping
I am new to django. I am trying to create a simple web scraping using beautifulsoup with django. I tried some methods to scrape data from website using beautifulsoup. I just need to create django form for entering url for parsing. once user enter url and submitted it should parse url and generate page title in next form with editable option. How can we do this in django forms and views ? I am looking for some ideas to start.. -
how could I run makemigrations with out errors in django
I am using (learning) pyhton/django programming using Eclipse editor. I recently deleted migration files (manually selecting through editor) in migrations folder except init.py file since it was giving some errors with field names that I deleted before. I physically deleted those files. Now when I run makemigrations, it says the dependancy files can not be located. Part of error : ...raise NodeNotFoundError (self.error_message, self.key, origin=self.origin) django.db.migrations.excemption.NOdeNotFoundError: Migration login.0007_auto_20170512_2502 dependancies reference nonexistant parent node ('login','0006_auto_20170515_2226') Could some one let me know how I could reconstruct the migration files ? Thank you in advance. PG -
Difficult loading template and variables when moving from local server to server for production
I trying to move an html page that works at local server to a production, but when loading the page in the production, i am getting the following page: enter image description here I tried to use previous posts in this subject but without success. My code is: *** Setting.py - Template directories PROJECT_PATH = os.path.realpath(os.path.dirname(__file__)) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'transport.wsgi.application' TEMPLATES_DIRS =( PROJECT_PATH + '/templates/', ) TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) base.html - <!DOCTYPE html> {% load staticfiles %} <!-- Don't forget this --> <html> <head> <title>{% block title%}{% endblock %}</title> <meta charset="utf-8"/> {% load staticfiles %} <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <link href='https://fonts.googleapis.com/css?family=Satisfy' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> {% block body%} {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% block content%} {% endblock %} {% endblock %} </body> </html> index.html {% extends 'base.html' %} {% block title%} Welcome to the Login … -
In Django, form isn't rendered on browser
I have started learning django, but I can't understand how to render form. This is form.py I have made. from django import forms class TweetForm(forms.Form): text = forms.CharField(widget = forms.Textarea(attrs = {'rows' : 1, 'cols' : 85}), max_length = 160) country = forms.CharField(widget = forms.HiddenInput()) This is code snippet in views.py. from .forms import TweetForm class Profile(View): def get(self, request, username): params = dict() user = User.objects.get(username = username) tweets = Tweet.objects.filter(user = user) params["user"] = user params["tweets"] = tweets form = TweetForm return render(request, 'profile.html', {'params' : params, 'form' : form}) This is html file and it must render form I have made. {% extends "base.html" %} {% block content %} <div class="row clearfix"> <div class="col-md-12 column"> <form method="post" action="post/"> {% csrf_token %} <div class="col-md-8 col-md-offset-2 fieldWrapper"> {{ form.text.errors }} {{ form.text }} </div> {{ form.country.as_hidden }} <div> <input type="submit" value="post"> </div> </form> </div> <h3>&nbsp;</h3> <div class="col-md-12 column"> {% for tweet in tweets %} <div class="well"> <span>{{ tweet.text }}</span> </div> {% endfor %} </div> </div> {% endblock %} When I issue command(run server), browser don't render form without any exception. I think there is a problem in views.py file, But I can't find it. How can I send form … -
What does ** stand for when filtering a queryset in Django? [duplicate]
This question already has an answer here: What does ** (double star) and * (star) do for parameters? 12 answers I am currently overwriting the default behaviour of django's django.views.generic.Detailview this is the get_object function of the original DetailView: def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError("Generic detail view %s must be called with " "either an object pk or a slug." % self.__class__.__name__) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching … -
Django: Show field if NOT logged in
I have the following form that works as it should. However, I wish to show the "currentCharities" field only when the user is NOT logged in: class SelectTwoTeams(BootstrapForm): team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format"})) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format"})) currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None, widget=forms.Select(attrs={"class": "select-format"})) I have tried so many options without success. Is there an easy way to do this? Many thanks in advance, Alan. Below is the rest of the form incase it helps: def __init__(self, *args, **kwargs): user = kwargs.pop('user') self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None) self.currentSelectedTeam2 = kwargs.pop('currentSelectedTeam2', None) self.currentfixturematchday = kwargs.pop('currentfixturematchday', None) self.currentCampaignNo = kwargs.pop('currentCampaignNo', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) cantSelectTeams = UserSelection.objects.select_related().filter(~Q(fixtureid__fixturematchday=self.currentfixturematchday),campaignno=self.currentCampaignNo, ) if not cantSelectTeams: queryset = StraightredTeam.objects.filter(currentteam = 1).order_by('teamname') else: queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)).order_by('teamname') teamsAlreadyPlaying = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday, fixturedate__lte = timezone.now()) postponedGames = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday,fixturestatus = "P") queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('home_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('away_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=postponedGames.values_list('home_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=postponedGames.values_list('away_team_id', flat=True)).order_by('teamname') self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset self.fields['team1'].initial = self.currentSelectedTeam1 self.fields['team2'].initial = self.currentSelectedTeam2 self.fields['team1'].label = False self.fields['team2'].label = False self.fields['currentCharities'].label = False def clean(self): cleaned_data = self.cleaned_data # individual field's clean methods have already been called team1 = cleaned_data.get("team1") team2 = cleaned_data.get("team2") if team1 == team2: raise forms.ValidationError("You may not pick the … -
ImageCms.profileToProfile - Cannot open profile file
I'm trying to convert a PIL image from sRGB into CMYK using ImageCms.profileToProfile() However, when attempting to load either the inputProfile or outputProfile, I get the following error PyCMSError: cannot open profile file Both profiles are pulled from an online source, and each link works, but I cannot figure out why it's not reading the profiles. The ImageCMS documentation says that using the path to the file will work, but I have also tried ImageCms.getOpenProfile(profileFilename), and passing the returned object into the .profileToProfile(), but the new method still won't read the profile name. Any thoughts why? Is there a better way I can convert an sRGB Image to a CMYK Image? My code: resized_image = ImageCms.profileToProfile(rgb_image, inputProfile='https://linkToProfile.s3.amazonaws.com/icc/sRGBColorSpaceProfile.icm', outputProfile='https://linkToProfile.s3.amazonaws.com/icc/USWebCoatedSWOP.icc', renderingIntent=0, inPlace=0) resized_image.save('foo.jpg') -
saving images in the modelformset_factory
The images are not being saved, although the other details in the form are being saved. I need to know, the pieces that are missing in the code views.py class ProductCreateView(CreateView): def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset)) def form_valid(self, form, formset): return HttpResponseRedirect(self.get_success_url()) def get(self, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(queryset=ProductImages.objects.none()) return self.render_to_response(self.get_context_data(form=form, formset=formset)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = ImagesFormset(self.request.POST, self.request.FILES) form_valid = form.is_valid() formset_valid = formset.is_valid() if form_valid and formset_valid: user = self.request.user form.instance.user = user self.object = form.save() images = formset.save(commit=False) product = self.object.save() for img in images : if hasattr(self.model, 'product'): img.media = product img.save() return self.form_valid(form, formset) else: return self.form_invalid(form, formset) models.py def product_download(instance, filename): return '%s/%s' %(instance.product.slug, filename) class ProductImages(models.Model): product = models.ForeignKey(Product) title = models.CharField(max_length=120) media = models.ImageField(upload_to=product_download, width_field='max_width', height_field='max_height', null=True, blank=True) max_width = models.CharField(max_length=100, null=True, blank=True) max_height = models.CharField(max_length=100, null=True, blank=True) featured_image = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return unicode(self.media) forms.py` class ProductImagesForm(forms.ModelForm): media = forms.ImageField(label='Image') featured_image = forms.BooleanField(initial=True) class Meta: model = ProductImages fields = ['media', 'featured_image', ] ImagesFormset = modelformset_factory(ProductImages, fields=('media', 'featured_image'), extra=1, max_num=4) Hope … -
Django pagination filtered results CBV
How can I paginate using multiple filters in Django CBV? I have some filters in my view and form and I don't know how to paginate it. Everything that I've tried has failed. Here my code. models.py class Lei(models.Model): CHOICE_TIPO_LEI = ( ('complementar', 'Lei complementar'), ('ordinaria', 'Lei ordinária'), ('decreto', 'Decreto'), ('portaria', 'Portaria'), ('convenio', 'Convênios Municipais'), ) numero = models.CharField(max_length=6) tipo_lei = models.CharField(u'Tipo do documento', max_length=15, choices=CHOICE_TIPO_LEI) ano = models.CharField(max_length=4) titulo = models.TextField() arquivo = FileBrowseField("Arquivo PDF", max_length=200, extensions=[".pdf",".doc", ".xls", ".docx", ".xlsx"], directory="leis/", blank=True, null=True) publicacao = models.DateTimeField(u'publicação', auto_now=True, blank=True) class Meta: db_table = "tb_lei" verbose_name = "Lei" verbose_name_plural = "Leis" def __str__(self): return self.titulo views.py class LeisListView(ComunsNoticiasMixin, ListView): model = Lei template_name = 'leis/leis.html' context_object_name = 'leis' def get_context_data(self, **kwargs): context = super(LeisListView, self).get_context_data(**kwargs) context["an"] = Lei.objects.values('ano').distinct().order_by('-ano') context["tl"] = Lei.objects.values('tipo_lei').distinct().order_by('tipo_lei') return context class BuscaLeiListView(ComunsNoticiasMixin, ListView): model = Lei template_name = 'leis/busca-leis.html' context_object_name = 'busca_leis' paginate_by = 1 def get_queryset(self, **kwargs): numero = self.request.GET.get('n') ano = self.request.GET.get('a') tipo_lei = self.request.GET.get('t') palavra = self.request.GET.get('p') leis = Lei.objects.all().order_by('-ano', '-numero') if numero: leis = leis.filter(numero=numero) if ano: leis = leis.filter(ano=ano) if tipo_lei: leis = leis.filter(tipo_lei=tipo_lei) if palavra: leis = leis.filter(titulo__icontains=palavra) return leis form.html <form method="get" action="{% url 'leis:busca_lei_view' %}"> <div class="form-group"> <select name="t" class="form-control"> … -
Using django formsets to create new instances every time the view is rendered
I am trying to add attendance of a whole classroom for different dates.I am using django formsets to render multiple forms, each for a student in classroom in which I have supplied initial data to fill the student, entry_no field before hand. Rest of the fields I ave using the view.The problem I am facing is that whenever I call the view for creating new attendance instances, the data gets updated rather than new instances being created.How can I create new attendances for different dates. models.py class Attendance(models.Model): date = models.DateField("Date") author = models.ForeignKey(User,related_name='attendances_taken') is_present = models.BooleanField(default='True') marked_status = models.BooleanField(default='False') entry_no = models.CharField(max_length=12,default='yyyyddnnnnn') student = models.ForeignKey(User,related_name='course_attendances') classroom = models.ForeignKey(Classroom,related_name='student_attendance') def __str__(self): return "%s %s was %s on %s" %(self.student.first_name,self.student.last_name,self.is_present,self.date) views.py @login_required def mark_attendance(request,classroom_slug): classroom = get_object_or_404(Classroom, slug=classroom_slug) students = classroom.students.all() data = request.POST or None AttendanceFormSet = modelformset_factory(Attendance, fields=('entry_no','student','is_present'),can_delete=True,extra= len(students),max_num=len(students)) date = request.GET.get("qdate") initial = [{'entry_no':x.profile.entry_number,'student': x} for x in students] formset = AttendanceFormSet(data=data,initial=initial,queryset=Attendance.objects.filter(classroom=classroom)) for form in formset: form.fields['student'].queryset = students if request.method == 'POST' and formset.is_valid(): for form in formset: if form.is_valid(): new_attendance = form.save(commit=False) new_attendance.author = request.user new_attendance.classroom = classroom new_attendance.date = date new_attendance.save() return redirect('classroom_detail',classroom.id) return render(request,'attendance/formset.html',{'formset':formset,'date':date}) -
django-filter use paginations
I'm using the django-filter package to provide a search functionality on my List view. Now I want to add a pagination. I'm trying to combine it with the django pagination, but I have no clue on how to go on: My views.py: def search(request): qs = local_url.objects.filter(global_url__id=1).all() paginator = Paginator(qs, 25) page = request.GET.get('page') try: pub = paginator.page(page) except PageNotAnInteger: pub = paginator.page(1) except EmptyPage: pub = paginator.page(paginator.num_pages) url_filter = PublicationFilter(request.GET, queryset=qs) return render(request, 'ingester/search_list.html', {'filter': url_filter, 'publication':pub}) -
How to invert django models.BooleanField's value?
I have some models.BooleanFields and I want them to be displayed inverted in Django Admin view. Is there a way to do it with a function with fieldname parameter? For example, for admin.py: list_display = (inverted('booleanField1'), 'booleanField2', inverted('booleanField3')) Also it is important to remain those icons that are default for BooleanField. Thank you in advance. -
Django Noreverse Error for below code
I'm trying to set search navbar to work on my website but I keep getting this error which I do not to decode. I'm using django 1.8 on Python 2.7 My template html file is below. <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'home' %}">Home</a></li> <form class="navbar-form navbar-left" method="GET" role="search" action="{% url 'product' %}"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search" name="q" value='{{ request.GET.q }}'> </div> </form> My Overall url file is below. from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ # Examples: url(r'^$', 'newsletter.views.home', name='home'), url(r'^contact/$', 'newsletter.views.contact', name='contact'), url(r'^about/$', 'ecommerse2.views.about', name='about'), # url(r'^blog/', include('blog.urls')), url(r'^product/', include('product.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^accounts/', include('registration.backends.default.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my local app urls is below. from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from .views import ProductDetailView, ProductListView urlpatterns = [ # Examples: url(r'^$', ProductListView.as_view(), name='Class_based_List_vie'), url(r'^(?P<pk>\d+)/$', ProductDetailView.as_view(), name='Class_based_vie'), #url(r'^(?P<id>\d+)', 'product.views.product_det_vie_func', name='Detail_view_func'), ] For the above code highlights the below line and getting 404 error with NoReverseMatch at /product/ and Reverse for 'product' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) … -
Django Report Builder Watch Error
Background: This week I stood up a Django site, connected it to four legacy Dbs we have. I installed report_builder, got her up and running. It works ok for most of the reports but some of them are breaking. I am getting two sets of errors that I think are contributing. The first look like this: /usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py:110: Warning: Truncated incorrect DOUBLE value: 'OutsideLocal' I get about four of these. I believe this may just be a problem with the model but I am having trouble locking it down. The other error and possibly the more important one for my purposes is a watch error: [2017-05-18 12:28:03,962 pyinotify ERROR] The pathname '/root /IPNV/django-test/src/CUCMCDR/models.py' of this watch <Watch wd=74 path=/root/IPNV/django-test/src/CUCMCDR/models.py mask=4038 proc_fun=None auto_add=False exclude_filter=<function <lambda> at 0x7f7c286e6f50> dir=False > has probably changed and couldn't be updated, so it cannot be trusted anymore. To fix this error move directories/files only between watched parents directories, in this case e.g. put a watch on '/root/IPNV/django-test/src/CUCMCDR'. Performing system checks... This docs are a little sparse and I can't seem to find out what the 'watch' is -
weasyprint don't show images in PDF Django
Welcome friends I need your help. I can't show images in my pdf. I know that we need to add url_fetcher to weasyprint.HTML. http://weasyprint.readthedocs.io/en/stable/tutorial.html?highlight=url_fetcher I try but it does not work. i don't know how to use a url_fetcher. tasks.py from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.conf import settings import weasyprint from io import BytesIO html = render_to_string('order/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') email.attach_alternative(html_content, "text/html") email.send() How to solve a problem ? Do you have any suggestion? I would appreciate your help -
Django destroys group by statement adding the PK
I have a simple task which I currently not able to get designed using the Django QuerySet. The following model is used: class Accountdata(models.Model): amount = models.DecimalField(max_digits=9, decimal_places=2) bookingdate = models.DateField() renter = models.ForeignKey(Renter, null=True, blank=True) All I want to do is create a group by which sums up all the amount payed by the renter per month (renter can pay multiple times a month) I used the following QuerySet (for one specific renter): Accountdata.objects.filter(renter_id=16).annotate(month=TruncMonth('bookingdate'), amountSum=Sum('amount')).values('month', 'amountSum').order_by() Unfortunately the result is wrong. I figured out that Django adds the primary key into the group by clause (used the QuerySet "query" methode to see what is going on): SELECT DATE_TRUNC('month', "accountdata"."bookingdate") AS "month", SUM("accountdata"."amount") AS "amountSum" FROM "accountdata" WHERE "accountdata"."renter_id" = 16 GROUP BY "accountdata"."id", DATE_TRUNC('month', "accountdata"."bookingdate")' I do not kow why Django is doing this since I do not have the ID inside the "values" section of the QuerySet. Using Django 1.11 and Python 3.6.1 -
sending email back/forth internally django
Currently I have a custom email notification implemented and it works when you post a comment you receive an email which notify you about the posted comment, now the thing is that this is happening internally in the system, so basically the staff (account_handler's) are talking to each other and get notify via email. Now the problem that I'm facing is that account_handlers that leave a comment on my thread for example will receive an email and the system will to, but when I respond to the thread I'm not receiving anything, so the question is how can I fix this, can someone help me understand this? In my model I'm using this code for comment email notification setup: class LeadContact(models.Model): # models here account_handler = models.ForeignKey(User, blank=True, null=True, related_name='handling_leads', on_delete=models.SET_NULL) # some custom function here def send_comment_posted_emails(self, comment): comment_user = comment.user comment_text = comment.comment handler_user = self.account_handler handler_email = handler_user.email if handler_email is not None and handler_email != comment_user.email: current_site = Site.objects.get_current() leads_url = self.get_view_url() + "#CommentsDiv" ctx = {"leads_url": leads_url, "site_name": current_site.name, "leads_sn": self.serial_number, "poster_name": user_util.get_user_full_name_or_user_name(comment_user), "comment_text": comment_text} subject = render_to_string("vinclucms_sales/email/email_sales_comment_posted_subject.txt", ctx) subject = "".join(subject.splitlines()) message = render_to_string("vinclucms_sales/email/email_sales_comment_posted_message.html", ctx) MailManager.send_mail_with_error_handler(subject, message, settings.DEFAULT_FROM_EMAIL, [handler_email], message_html=message) class Meta: # Meta … -
Django filter objects from many to many relationship
I'm having a problem when trying to filter over a many-to-many relationship. This is my models.py: class Member(models.Model): name = models.CharField(max_length=255) class Talk(models.Model): members = models.ManyToManyField(Member) I want to get the conversations in which two members are participating. Here are the data I have: { "pk": 2, "members": [ 36384, 12626, 48397 ], }, { "pk": 3, "members": [ 36384, 12626, -89813, 48397 ], } I want to get conversations where the two specified members participate. My query was as follows: Talk.objects.filter(members__in=[12626, -89813]) The result I get is the following: <QuerySet [<Talk: 2>, <Talk: 3>, <Talk: 3>]> How can I make the result to be this? <Talk: 3> Note: It is in the only conversation in which the specified members are participating Thanks -
How to fetch dunder or single underscore attributes in django template tags?
I have an object qna from django view to the template. If I try to extract information from qna in django template I get this error Variables and attributes may not begin with underscores: 'qna._questions my html: {% for q in qna._questions %} <h4 class="qn_idx_head">Question 1</h5> <h3 class="qn_head"></h4> <div class="choices_div"> <ul> {% for c in q.__choices__ %} <li>{{ c }}</li> {% endfor %} </ul> </div> {% endfor %} -
Django - Reduce URL query-string length
I been working with Django Forms for a while but recently I had to create a form to search for data with a MultipleChoiceField. Since the URL must be shared between the users the form performs a GET to the server to keep the search parameters in the query-string. The problem is that if multiple options are checked the length of the URL increases too much. For example: http://www.mywebsite.com/search?source=1&source=2&source=3... Is there anyway working with django forms to get a url like the following: http://www.mywebsite.com/search?source=1-2-3... Or is it a better approach to create a token that compress the query-string parameters? Thanks!