Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django group by and count
I am trying to perform a grouping on my model which looks like this: class Restaurant(models.Model): pass class Order(models.Model): created = models.DateTimeField(auto_now_add=True) restaurant = mdoels.ForeignKey('Restaurant') Now I want to know how many orders were created each day. This means I need to get date from DateTime field and then a count. If it's relevant, I'm getting Order queryset in this way: restaurant = Restaurant.objects.get(id=request.data['restaurant_id']) orders = restaurant.order_set.filter(created__lte=some_date) Now, how can I get what I want from orders? I have tried things like: orders.values('created').annotate(Count('created')) Using TruncDate and so on. I am using Python 2 and Django 1.11. -
Django: Several clicks on submit button = several entries in database
I just realised when clicking very fast on the form submit button several times, while it is loading. My POST request is sent several times, meaning I am able to create up to 10 database entries where it's supposed to be only one. I wasn't aware of this until now and wonder if that is normal behaviour or if there is some issue with my view? def event_detail_view(request, event, organizer): queryset = Event.objects.filter(organizer__slug=organizer) event = get_object_or_404(queryset, slug=event) tickets = collect_all_tickets(event, organizer) ReserveFormSet = formset_factory(ReserveForm, formset=BaseReserveFormSet, extra=0) formset = ReserveFormSet( initial=tickets, form_kwargs={'organizer_slug': organizer} # Example [{'ticket': "Early Bird"}, {'ticket': "Regular Ticket"},] ) if request.method == 'POST': formset = ReserveFormSet( request.POST, initial=tickets, form_kwargs={'organizer_slug': organizer} ) if formset.is_valid(): order_reference = unique_order_reference_generator() # TODO Marc: Move into function for form in formset: ticket_name = form.cleaned_data['ticket'].name int_or_empty = form.cleaned_data['quantity'] qty = is_int_or_zero(int_or_empty) if qty > 0: obj = form.save(commit=False) obj.ticket_name = ticket_name obj.order_reference = order_reference obj.save() return redirect('organizers:index', organizer=organizer) return render(request, 'events/event_detail.html', {'event': event, 'formset': formset}) -
Javascript does not insert value on django's formset hidden input field
I'm attempting to pass a value on a hidden input field in a formset. However when I hit submit I get nothing back: 'form-0-my-field': ['']. Can anyone please help me with this issue? Here's my form: class MyForm(forms.Form): my_field = forms.CharField(widget=forms.HiddenInput(attrs={ 'class': 'my_field'})) formset: MyFormSet = formset_factory(MyForm, max_num=5) views.py def my_view(request): if request.method == 'POST': formset = MyFormSet(request.POST) if formset.is_valid(): print(formset.cleaned_data) else: formset = MyFormSet() return render(request, 'my_template.html', ctx={'formset': formset}) And finally my template with a script in the end to target my_field: {% for form in formset.forms %} {% for field in form.visible_fields %} {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} <button type="submit">Submit</button> <script> document.getElementsByClassName("my_field").value = "some str"; alert(document.getElementsByClassName("my_field").value); </script> -
django dynamic form initial attribute not honored
i'm creating forms dynamically via this class: class dynform (forms.Form): def __init__(self,*args, **kwargs): super(dynform,self).__init__(*args, **kwargs) for i in args: for k,v in i.iteritems(): self.fields[k] = eval(v) i'm passing the fields as a dictionary like: {'Hand Hygiene Performed Before Patient Contact': 'forms.ChoiceField(choices=boolResponses,required=False,initial="No")'} the boolReponses tuple has 'Yes','No','N/A' values, my problem is that my "initial = 'No'" is not honored in the web-page. -
Filtered items on admin item list and whole items in breadcrumbs
I am working with django 1.11 and I would like to have in admin panel - on the list - whole items till now and + 2 months forward. I mean I don't need events from December. Below is my code in admin.py: def get_queryset(self, request): currentMonth = datetime.now().month qs = models.Event.objects.all().filter(date__month__lte=currentMonth+2) return qs Problem is that, I don't have events from example December in the breadcrumbs. Is possibility to have all items in breadcrumbs and filtered items on the list? -
Django-Postgres: length of CharField as primary key
In my Django model there is a CharField as primary key with 250 characters as max_length: key = models.CharField(primary_key=True, max_length=250) Also, in Postgres the max length of thekey column is 250 as shown below: Column | Type | Collation | Nullable | Default ---------------------+------------------------+-----------+----------+--------- key | character varying(250) | | not null | However, when I am giving keys longer than 50 characters I am getting: value too long for type character varying(50) For keys shorter than 50 everything works fine. So there must be an implicit limit of 50 characters for the key column even though the limit seems to be 250. But why? And how can I change this? -
html2pdf with Django
I'm trying to generate PDF file from html rendering I use the following class to generate the HTML Views.py class ReportList(ListView): model = Reports template_name = 'myreports.html' context_object_name = 'reports' def get_context_data(self, *args,**kwargs): context = super(ReportListView, self).get_context_data(*args,**kwargs) context['reports'] = Reports.objects.all().values('id','idsys','time','item','customer').filter(id =self.kwargs['id'],.... ) return context urls.py url(r'^reports/(?P<id>\d+).../$', views.ReportList.as_view(), name = 'myreports'), I haven't idea of generate the pdf (by button link) I tested reportlab and wkhtmltopdf without succes!! Do you have any suggestions please? -
Django Rest Framework SearchFilter doesn't work
I am trying to implement two filters in my ViewSet (OrderingFilter and SearchFilter), but only OrderingFilter works. I can see the proper control for OrderingFilter in the browsableAPI, but I don't get the proper control for searching. This is my ViewSet: from rest_framework.filters import OrderingFilter, SearchFilter from GeneralApp import serializers, models class CountryViewSet(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) queryset = models.Country.objects.all() serializer_class = serializers.CountrySerializer filter_backends = (OrderingFilter, SearchFilter) Thanks for your help. -
do i need to install virtualenvwrapper-win for Django
I'm going to use Django for my final project so when i'm following the documentation it mentioned that we need to install virtualenvwrapper-win.Is it must to install virtualenvwrapper-win before installing Django? or not? -
Django queries: return a Q object that will translate to "AND (...)"
I am writing a simple search for our website, and I need to filter the entries on a number of criteria. However, if the strictest filtering is not satisfied, I want to return the results for a less strict search. To that end, I want to create a number of query objects, each with one more filter, then iterate them backwards trying to get a result, and return the first one I get this way. What I am doing is: q0 = MyIndex.objects.in_city(city_id) q1 = q0.filter(name_contains(words)) where def name_contains(words): if not words: return Q() query = Q(words_contains=words[0]) for word in word[1:]: query = query | Q(words_contains=word) When I pass the words that are not present in the database, I still get a result, because the query part returned by the name_contains is attached via OR and not AND. Is there a way I can return that query so that it is always attached to the rest of the query by AND? -
Django inline actions - checkboxes instead of buttons
I am using django 1.11 with external app - django-inline-actions. I would like to have checkboxes instead od action buttons in item detail in admin panel. In the end I want to fill in checkboxes of items and export to external file. Is it possible? class ParticipantInline(InlineActionsMixin, admin.TabularInline): model = models.Participant inline_actions = [] extra = 0 fields = ('first_name', 'last_name', 'company', 'street', 'post_code', 'city', 'email', 'phone_number', 'comment',) -
Django ORM update_or_create() case sensitivity
Problem Description I have a model called SourceData that looks like this: class SourceData(models.Model): seller = models.ForeignKey(DataSourceStatus, null=True, default=True, related_name='source_data') sessions = models.FloatField(null=True, default=None) bounce_rate = models.FloatField(null=True, default=None) goal_completions_all = models.FloatField(null=True, default=None) goal_conversion_rate_all = models.FloatField(null=True, default=None) transactions = models.FloatField(null=True, default=None) transaction_revenue = models.FloatField(null=True, default=None) data_date = models.DateField() source = models.CharField(max_length=100) When I try to populate it, I iterate through a list of records which are dictionary objects, each with a case-sensitive source field. Sometimes these source fields will look like Master List or MASTER LIST and I want to preserve the casing. Here is my population method: source_data, created = SourceData.objects.update_or_create( seller=data_source_status, data_date=date_record, source__iexact=sub.get('source', ' '), defaults={ 'seller': data_source_status, 'data_date': date_record, 'sessions': sub.get('sessions', 0), 'bounce_rate': sub.get('bounceRate', 0), 'goal_completions_all': sub.get('goalCompletionsAll', 0), 'goal_conversion_rate_all': sub.get('goalConversionRateAll', 0), 'transactions': sub.get('transactions', 0), 'transaction_revenue': sub.get('transactionRevenue', 0), 'source': sub.get('source', ' '), } ) After looking through much documentation and StackOverflow articles, I added __iexact to the source param, which I believed would require the string to be EXACTLY what I retrieved for it to update the record. This is not what is actually happening however. Master List is overwritten by MASTER LIST... Any suggestions would be most appreciated! -
Django - postgres: how can I verify whether the database connection is SSL?
My postgres server should be forcing SSL connection however I would like to verify this setting directly from the Django app. Is there a way to inspect the database connection (perhaps through manage.py shell and make sure the connection is SSL? -
Django leaflet canvas
How to make django-leaflet render with canvas? I checked on leaflet documentation that it should use preferCanvas but there are no manual in django leaflet that shows how to do it, while var map are hidden somewhere... Any clue -
Pyinstaller django static files not being used on Windows
I'm using PyInstaller to try and make running of a Django project simple for a user. It works perfectly on my Linux PC but when I try and create it on a Windows PC the static files are not loading and I cannot understand why. I'm using the following .spec file to create the application. # -*- mode: python -*- block_cipher = None a = Analysis(['manage.py'], pathex=['C:\\Users\\henry\\potential-waffle'], binaries=[("C:/Program Files (x86)/Windows Kits/10/Redist/ucrt/DLLs/arm", '.')], datas=[('media','media'),('potential_waffle/static','static')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, exclude_binaries=True, name='webscraper', debug=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, name='webscraper') My static files are defined within settings.py as: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "potential_waffle/static"), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static') And I'm picking up the static files for runserver: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The program works fine and does everything it should except the formatting of the browser and within terminal I have the following: [08/Jun/2018 12:00:57] "GET /login/?next=/ HTTP/1.1" 200 5438 [08/Jun/2018 12:00:57] "GET /static/agency/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 302 0 [08/Jun/2018 12:00:57] "GET /static/font-awesome/css/font-awesome.min.css HTTP/1.1" 302 0 [08/Jun/2018 12:00:57] "GET /static/agency/css/agency.css HTTP/1.1" 302 0 [08/Jun/2018 12:00:57] "GET /static/toastr/toastr.min.css HTTP/1.1" 302 0 … -
Validations of Model Serializers
I have to modify the feature of ModelSerializer, my expectations are as, I have two fields in my Model. Both are charFields. class MyModel(models.Model): name = models.CharField(blank=False, null=False, max_length=20) value = models.CharField(blank=True, null=True, max_length=20) My serializer is as, class MyModelSerializer(ModelSerializer): class Meta: model = MyModel fields = '__all__' I am have to create the object of MyModel using this serializer. Now issue is that if I am passing the 'bool' values in my fields, its showing error message that 'Not a valid string.' (As expected by Modelserializer) { "name":True, "value":False } My requirements are to handle the 'bool' value and converted that 'bool' into 'str'. what should be the trick to resolve this. -
Best SEO: Angular 6 or Django?
I am going to start on a project that requires that its webpages can be well indexed by search engines. Pages are dynamically created using data from the database. I have two options: Front-end website using Angular 6 with a backend database service Back-end driven website using Django Given that the website should be indexed well by search engines, which option would be best to achieve best SEO? Also, what are considerations that should be made here? -
TypeError: products() got multiple values for argument 'pk'
models.py I have two models with manytomany field which makes me confuse everytime. class Product(models.Model): product_name = models.CharField(max_length=32) quantity = models.IntegerField() remarks = models.TextField(blank=True) class Vendor(models.Model): vendor_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) product = models.ManyToManyField(Product) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class VendorSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=False) class Meta: model = Vendor fields = '__all__' def create(self, validate_data): product_data = validate_data.pop('product') vendor = Vendor.objects.create(**validate_data) for product_data in product_data: Product.objects.create(vendor=vendor, **product_data) return Vendor views.py from rest_framework.decorators import detail_route class VendorViewset(viewsets.ModelViewSet): serializer_class = VendorSerializer queryset = Vendor.objects.all() @detail_route(methods=['GET']) def products(request, pk=None): qs = self.get_object().product.all() serializer = ProductSerializer(qs, many=True) return Response(serializer.data) urls.py from django.conf.urls import url, include from . import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('vendor', views.VendorViewset) urlpatterns = [ url(r'', include(router.urls)), ] Then I browse http://localhost:8000/vendor/1/products/ I get that error. How can this be solved? -
Protobuf: DecodeError while parsing from post request body
I have generated Serialized string in python and passing it to an API as a post request body. But while parsing the string its returning an empty protobuf object. Parsing works well if the string is parsed directly, but not when it's passed to API. The following code works custom_email = ProtoClass() body = <protobuf string> custom_email.ParseFromString(body) print(custom_email) But the following doesn't custom_email = ProtoClass() body = request.body custom_email.ParseFromString(body) print(custom_email) -
Passing url parameter to function
urls.py url(r'^add-friend/(?P<user>[\w-]+)/$', views.add_friend, name='add_friend'), views.py @login_required(login_url='/login') def add_friend(request, user): user=User.objects.get(username=request.user) friend=User.objects.get(username=user) Friend(user=user, friend=friend).save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) Template <a href="{% url 'add_friend' user.username %}"><i class="fas fa-user-plus">Add</i></a> the value of user.username in template is test, and the current user is test1. Everytime I run the function, I get a Friend object with both fields (user and friend) equaling test1, but I expect the user field to be test1 and the friend field to be test according to what is being passed on from template. -
Which open source web panel is best for hosting Django (python) site on centOS (Linux)?
Which open source web panel( C-PANEL) is best for hosting Django (python) site on centOS 7(Linux)? -
How to make Postgres to manage the table’s lifecycle in a django project
I'm trying to create a project using django with a populated database, my problem is when I try to create a new object I get this error duplicate key value violates unique constraint, because the database is already populated, what can I do to change it to make Postgres manage it or django to get the right sequence? thanks in advance -
Text to speech in django
I want to create a voice system . Whenever a user visits on my website a post is displayed . Then the user will click next , then next post appears , the process goes in this way. I want my post to be spoken which will be heared by the user. Basically whenever a user visits on my website and when a post is displayed , a user should be able to hear the post or read the post. Currently i am only able to display my posts but not able to give them voice. Kindly help me in this query. views.py def qpage(request): contact_list = Post.objects.all() paginator = Paginator(contact_list, 1) page = request.GET.get('Q') contacts = paginator.get_page(page) return render(request, 'data/post.html',{'contacts': contacts,'Page':page}) post.html Post No.{{ Page }} {% for contact in contacts %} {{ contact.question }}<br /> {% endfor %} <div class="pagination"> <span class="step-links"> {% if contacts.has_previous %} <a href="?Q={{ contacts.previous_page_number }}">previous</a> {% endif %} <span class="current"> Question {{ contacts.number }} of {{ contacts.paginator.num_pages }} </span> {% if contacts.has_next %} <a href="?Q={{ contacts.next_page_number }}">Next</a> {% endif %} -
Django querysets - Performing subqueries
How to make query to get all components added by a certain user? Also in the resulting object I want to have the system name and project name too. I saw examples demonstrating sub-queries for two tables, but I need this for 3 tables. Thank you. class component(models.Model): id = models.AutoField(primary_key=True) server = models.ForeignKey(server, on_delete="CASCADE") name = models.TextField(blank=True) comments = models.TextField() timestamp = models.DateTimeField(auto_now=True) class system(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(project, on_delete="CASCADE") name = models.CharField(max_length=255,blank=True) comments = models.TextField() timestamp = models.DateTimeField(auto_now=True) class project(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255,blank=True) comments = models.TextField() user = models.ForeignKey(User, on_delete="CASCADE") timestamp = models.DateTimeField(auto_now=True) -
How can use firebase url shortener in python Django?
Is there any way to use firebase URL shortener(dynamic links) programmatically in Python Django?