Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use posgresql 'interval' in Django?
Here is my PostgreSQL statement. select round(sum("amount") filter(where "date">=now()-interval '12 months')/12,0) as avg_12month from "amountTab" How to use this in Django? I have an object called 'Devc', with attribute 'date'. I want to get the sum of the specific data within past 12 months, not past 365 days. -
Add a dynamic number of fields to Django admin form
I have 3 Models "Configuration", "Process", and "ProcessConfiguration" as defined below: class Configuration(models.Model): name = models.CharField(max_length=MAX_CONFIGURATION_NAME_LEN, unique=True, db_index=True) description = models.TextField(blank=True) validation = models.CharField(max_length=MAX_CONFIGURATION_VALIDATION_LEN, blank=True) entity = models.CharField(max_length=MAX_CONFIGURATION_ENTITY_LEN, blank=False) is_customer_visible = models.BooleanField(default=False, editable=True) class ProcessConfiguration(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE, db_index=True) configuration = models.ForeignKey(Configuration, on_delete=models.CASCADE, db_index=True) value = models.TextField() created = models.DateTimeField(editable=False, auto_now_add=True, db_index=True) def __str__(self): return self.process.name + ": " + self.configuration.name + " = " + self.value[:80] class Meta: unique_together = ('process', 'configuration') class Process(models.Model): name = models.CharField(max_length=MAX_PROCESS_NAME_LEN) What I am trying to do is to add a new CharFeild to the Process admin form for each of the Configuration objects that have a particular entity flag set. I thought I would be able to do this how I have added other fields to forms, but within a loop. class ProcessCreateForm(forms.ModelForm): test_above = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) extented_configurations = Configuration.objects.filter(entity='proc', is_customer_visible=True) for config_item in extented_configurations: kwargs = { 'label': "123", 'required': False } field_class = forms.CharField self.fields[config_item.name] = field_class(**kwargs) When I print out the fields at the end of the init, I can see that the new fields have been added, however when I load the page I can only see the "test_above" field. The end … -
django rest serialize a string when model object is not defined
having trouble serializer a string during a try/except statement. here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize. class RefundOrder(APIView): def post(self, request, **kwargs): print('test') body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) amount = body_data['amount'] tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id']) refund = SquareGateway(tenant).refund(amount) serializer = RefundSerializer(refund) return Response(serializer.data) this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data. def refund(self, order, amount, reason): try: response = self.client.transaction().create_refund(stuff) refund = Refund( order=order, amount=response.refund.amount_money.amount, ) refund.save() return refund except ApiException as e: return json.loads(e.body)['errors'][0]['detail'] this is the the Refundserialize class RefundSerializer(serializers.ModelSerializer): class Meta: model = Refund fields = ('id', 'amount') -
Creating a simple webpage with Python, where template content is populated from a database (or a pandas dataframe) based on query
I use python mainly for data analysis, so I'm pretty used to pandas. But apart from basic HTML, I've little experience with web development. For work I want to make a very simple webpage that, based on the address/query, populates a template page with info from an SQL database (even if it has to be in a dataframe or CSV first that's fine for now). I've done searches but I just don't know the keywords to ask (hence sorry if this a duplicate or the title isn't as clear as it could be). What I'm imagining (most simple example, excuse my lack of knowledge here!). Example dataframe: import pandas as pd df = pd.DataFrame(index=[1,2,3], columns=["Header","Body"], data=[["a","b"],["c","d"],["e","f"]]) Out[1]: Header Body 1 a b 2 c d 3 e f User puts in page, referencing the index 2: "example.com/database.html?id=2" # Or whatever the syntax is. Output-page: (Since id=2, takes data row data from index = 2, so "c" and "d") <html><body> Header<br> c<p> Body<br> d<p> </body></html> It should be pretty simple right? But where do I start? Which Python library? I hear about Django and Flask, but are they? Is there an example I could follow? And lastly, how does the syntax … -
Creating serializer to display correct data
I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer. What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models: class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) Here's how I want the data displayed: { user: 2 status: "Hello" total_votes: 101 choices: [ { "id": 2, "choice": "first choice", "vote_count": 31, "question": 3 }, { "id": 4, "choice": "second choice", "vote_count": 70, "question": 3 } ], choice_selected: 2 } In the data above, the logged in user selected choice 2 in this specific question. class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(source='choice_set', many=True) class Meta: model = Question fields = '__all__' class GetProfileQuestions(ListAPIView): serializer_class = QuestionSerializer def get_queryset(self): return Question.objects.all() This query successfully prints out each question and its choices. However, how do I … -
Python JOB in separated project
I have a Django Project with some CRUD pages. Now i need create a JOB to make some task once per minute. I think about two solutions but i would like to know which should be better approach to follow Python Best Practices: 1- Create a job.py inside my django project and call a start() method when urls.py is called, because i need initialize this job.py in some moment. 2- Create a job.py in separated project and run "python job.py". For me, is better create a separated project and run "python job.py" because my job don't depends on django project. But i really don't know if a good choice in python world. -
Django return redirect to external url not working
I'm having difficulty getting a redirect to work for external URLs. The following is in the views.py file: def link_out(request): products = products_for_cart(user=request.user) product = get_object_or_404(products, pk=product_id) if product.is_link(): variant_id = request.POST.get('variant') variant = ProductVariant.objects.get(id = variant_id) print(variant.external_url) response = redirect(variant.external_url) print('before redirect') return response print('after redirect') 'before redirect' and the URL are printed in the shell, however, the browser never redirects to an external URL. https://www.google.co.uk/ before redirect INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] There are two things that seem interesting to me, the three POSTs after the redirect (all INFO prints are coming in threes??), and that the redirect isn't executing in the browser. My questions are, where does the redirect get returned to from the views.py file, and what could be the reason for the broswer not redirecting? Thanks -
CORS blocked in dockerized Django REST + Angular project
I decided to dockerize an existing Django REST + Angular app today. The website is displaying as it should, however CORS requests are being blocked. Access to XMLHttpRequest at 'http://localhost:8000/branches/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The angular App is dockerized using Nginx. I was using this tutorial in the progress (docker + compose files are listed below). Strange thing about this is that I had this problem before and solved it through the use of the djang-cors-headers package. Along with CORS_ORIGIN_ALLOW_ALL = True, this no longer seems to be solving the issue. Can this be related due to the fact that the application now runs in containers? I'm providing the dockerfiles for the projects along with the docker-compose file below. Not sure if they are relevant though. Dockerfile for the Angular project: FROM tiangolo/node-frontend:10 as build-stage WORKDIR /app COPY package*.json /app/ RUN npm install COPY ./ /app/ ARG configuration=production RUN npm run build -- --output-path=./dist/out --configuration $configuration # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx FROM nginx:1.15 COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html # Copy the default nginx.conf provided by … -
Django Rest Framework - Restrict FK entries
I have 2 models, Post and Comments class Post(models.Model): post_id = models.IntegerField(primary_key=True) ... class Comment(models.Model): post = models.ForeignField(Post, on_delete=models.CASCADE, related_name='comment_post') ... I have made a serializer for post class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all___' class PostSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, source='comment_post') class Meta: model = Post fields = ('post_id', 'comments') The PostSerializer gives all the comments on a particular post. I want to access 5 latest comments per post. (planning to use something like order_by('-comment_time')[:5]) How can i do this in Django Rest Framework within PostSerializer? Thanks! -
How add extra fields data to database with UserCreationForm Django?
I'm trying to add data from UserCreationForm extra fields to database, i want to add multiple fields to UserCreationForm and save it to database. I saw other examples from topics here in stackoverflow, but it doesn't work. Here is a example of my code: ( fields: "agree_terms" or "price" could be anything else) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs= {'placeholder':'Email'})) agree_terms = forms.BooleanField() price = forms.DecimalField(decimal_places=2, max_digits=10000) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('username', 'password1', 'email','password2','agree_terms','price') views.py @csrf_protect def registers(request): if request.method == 'POST': form = UserRegisterForm(request.POST) print(form) print(form.is_valid()) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,'Conta criada {}'.format(username)) return redirect('login') else: form = UserRegisterForm() return render(request,'header-login.html',{'form':form}) -
writing unit test for many to many model in django program
in my django projects, I have a two class like following: class DataTag(models.Model): title = models.CharField(max_length=120, unique=True) relations = models.ManyToManyField('DataTag', related_name='related_data_tags', blank=True) and the another class is: class Data(models.Model): tags = models.ManyToManyField('DataTag',related_name = 'data') def tag_name(self): if self.tags.all(): return self.tags.all()[0].title return '' both my models work, but now I want to write a test for main_tag_name, and checking if this function returns a true value or not.until now I write the following: from unittest import TestCase class BusinessTest(TestCase): def test_tag_name(self): self.data = Data.objects.create() self.tag1 = DataTag.objects.create() I am new on writing test. please help me for writing this test. Thanks in advance -
Django template variable (model instance) translation
There is a Product model with name CharField in my db. There is a template for rendering one instance of the Product model on the page. In view i'm passing to the template product variable which is filtered instance of the Product model. In template i need to translate variable {{ product.name }} depending on which Product instances page is rendering now. After reading Django documentation: To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. i decided to use next: {% blocktrans with product_name=product.name%}{{product_name}}{% endblocktrans %} in django.po file i get: msgid "%(product_name)s" Can you tell me please, am i on the right way? And how should name attributes of the other product instances be translated if such approach allows to provide translation only for one product.name? Thanks for any attention! -
Formatting DateTimeField in Django
When saving timestamp in Django's DateTimeField using auto_now_add this way: creation_timestamp = models.DateTimeField(auto_now_add=True) the field is saved with miliseconds: 2018-11-20T15:58:44.767594-06:00 I want to format this to be displayed without miliseconds: 2018-11-20T15:58:44-06:00 But the only option I could come up with does not exactly shows what I need: format="%Y.%m.%dT%H:%M:%S%z" gives me 2018.11.20T15:58:44-0600 How do I format this field the way I need? Alternatively I'd rather save DateTimeField without milliseconds at all but does auto_now_add allow to do this sort of thing? -
jQuery not sending element text to form field [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 23 answers I created a set of links in jQuery. The "zip_list" below is from an ajax call that got the data from a Django database request. This part works as expected, at least I think... //end of ajax call that gives json response dataType: "json", success: function(data) { zip_list = JSON.parse(data); //parse json response x = zip_list.length; //get length value for loop var container = $('<div />'); for(j=0; j<x; j++){ container.append($('<a href="#">').addClass("zip_response").text(zip_list[j]["city"]+','+zip_list[j]["state"])); container.append($('<br>')); } $('.zip_menu').append(container); } It outputs html code that looks like this: <div class="zip_menu"> <div> <a href="#" class="zip_response">COLUMBIA,MO</a> <br> <a href="#" class="zip_response">HINTON,MO</a> <br> <a href="#" class="zip_response">LINDBERGH,MO</a> <br> </div> </div> Now with those links, when they are clicked should fill in form data, with the below jQuery: $(".zip_response").click(function () { var txt = $(this).text(); //****NOT WORKING ON ELEMENTS CREATED THROUGH JQUERY, BUT WORKS ON SAME LINKS IF PUT IN AS NORMAL HTML var city_state = txt.split(","); //splits that text that in the tag, but a comma producing an array, with the city and state console.log(city_state[1]); $("#state").val(city_state[1]); //form field for state $("#city").val(city_state[0]); //form field for city }); The issue is that at this point in the … -
django 2.13 login_required build-in decorator doesn't work
i work on Django 2.1.2 and i wanted decorated my view base on class. I apply login_required decorator in path path('', login_required(CredentialsList.as_view()), name='credentials-list'), when i send request to CredentialList it responds normally, it does not redirect me to the login screen. whether I omitted something from the configuration LOGIN_URL='login/' LOGIN_REDIRECT_URL = 'list/' -
Django second page not found
Can any one tell me why my help page keeps returning page not found please? Views from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): my_dict = {'insert_me':"Hello I am from views.py !"} return render(request, 'first_app/index.html', context=my_dict) def help(request): help_dict = {'help_insert':'HELP PAGE'} return render(request, 'first_app/help.html', context=help_dict) First_app urls from django.urls import path from first_app import views urlpatterns = [ path('', views.index, name='index'), path('', views.help, name='help' ), ] first_app urls: from django.contrib import admin from django.urls import include, path from first_app import views urlpatterns = [ path('', views.index, name='index'), path('first_app/', include('first_app.urls')), path('admin/', admin.site.urls), ] there is a template folder with first app_folder both html files are in there. Have tried http://127.0.0.1:8000/first_app/help and http://127.0.0.1:8000/help What am I missing please? -
Django getstream User object is not iterable
i try to integrate Django with Getstream. Mostly code work, but at the end on profile page, i have error: "User object is not iterable". I follow tutorial get stream Twitter, and search through Getstream pinterest example. I have the same code, but for me don't work. Try both, getstream Twitter profile view and pinterest style profile view. Both the same error. View: def user_detail(request, username): ''' Shows the users profile ''' enricher = Enrich(request.user) profile_user = get_user_model().objects.get(username=username) feed = feed_manager.get_user_feed(profile_user.id) activities = feed.get(limit=25)['results'] context = {} do_i_follow_users(request.user, [profile_user]) context['profile_user'] = profile_user context['activities'] = enricher.enrich_activities(activities) response = render(request, 'account/user/detail.html', context) return response When I check getstream dashboard I see log of actions: Screen getstream dashboard log What are the other options to interate through user. I need only user timeline on this page. -
jQuery not decrementing value in Django Inline Formset UpdateView
I'm using this script - https://github.com/elo80ka/django-dynamic-formset/blob/master/src/jquery.formset.js With this template: <div id="approach_form" class="form-control pl-4 pt-2"> {% for formset in inlines %} <table> {% for form in formset %} {{ form.id }} {{ form.errors }} <tr> <td>{{ form.approach_type }}</td> <td>{{ form.number }}</td> <td>{% if form.instance.pk %}{{ form.DELETE }}{% endif %}</td> </tr> {% endfor %} </table> {{ formset.management_form }} {% endfor %} </div> And it renders this html: <div id="approach_form" class="form-control pl-4 pt-2"> <table> <input type="hidden" name="approach_set-0-id" value="25" id="id_approach_set-0-id"> <tbody><tr class="approach-formset"> <td><select name="approach_set-0-approach_type" id="id_approach_set-0-approach_type"> <option value="">---------</option> <option value="ILS">ILS</option> <option value="CATII">CAT II</option> </select></td> <td><input type="number" name="approach_set-0-number" value="2" min="0" id="id_approach_set-0-number"></td> <td><input type="hidden" name="approach_set-0-DELETE" id="id_approach_set-0-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <input type="hidden" name="approach_set-1-id" value="24" id="id_approach_set-1-id"> <tr class="approach-formset"> <td><select name="approach_set-1-approach_type" id="id_approach_set-1-approach_type"> <option value="">---------</option> <option value="ILS" selected="">ILS</option> <option value="CATII">CAT II</option> <option value="CATIII">CAT III</option> </select></td> <td><input type="number" name="approach_set-1-number" value="1" min="0" id="id_approach_set-1-number"></td> <td><input type="hidden" name="approach_set-1-DELETE" id="id_approach_set-1-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <input type="hidden" name="approach_set-2-id" value="26" id="id_approach_set-2-id"> <tr class="approach-formset"> <td><select name="approach_set-2-approach_type" id="id_approach_set-2-approach_type"> <option value="">---------</option> <option value="ILS">ILS</option> <option value="CATII">CAT II</option> </select></td> <td><input type="number" name="approach_set-2-number" value="3" min="0" id="id_approach_set-2-number"></td> <td><input type="hidden" name="approach_set-2-DELETE" id="id_approach_set-2-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <tr class="approach-formset-add"><td colspan="3"><a class="add-row" href="javascript:void(0)">Add</a></td></tr></tbody></table> <input type="hidden" name="approach_set-TOTAL_FORMS" value="3" id="id_approach_set-TOTAL_FORMS"><input type="hidden" name="approach_set-INITIAL_FORMS" value="3" id="id_approach_set-INITIAL_FORMS"><input type="hidden" name="approach_set-MIN_NUM_FORMS" value="0" id="id_approach_set-MIN_NUM_FORMS"><input type="hidden" name="approach_set-MAX_NUM_FORMS" value="4" id="id_approach_set-MAX_NUM_FORMS"> </div> The specific problem is that the remove links do … -
convert array of strings inside of string into a python list
I've sent some form-data from my React client to my Django + DRF api. inside of the form-data I have an attribute date_strings which is an array of date-time strings. i.e. ["date1", "date2", "date3"] in order to send it to my Django api I converted the array of strings into a string using JSON.stringify const myForm = new FormData(); myForm.set("date_strings", JSON.stringify(dateStrings)); in the create method of my serializer, I'd like to convert this data into a list. def create(self, validated_data): stringified_array = validated_data.pop('date_strings') // stringified_array: '["date1", "date2", "date3"]' how can I convert an array of strings inside of a string into a python list? -
Is the default django development server secure or can others access it?
I'm new to django/python and want to make sure that if I'm learning django on my own from my work machine, it won't be some kind of security breech when django sets up its automatic development server. I'm using this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ And they have you set up the dev server as: $ python manage.py runserver which outputs: Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. November 17, 2018 - 15:50:53 Django version 2.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Can others access this server, either from within the network or just through the internet? How would one go about checking that? -
Only allow requests from single site in Django Rest Framework
For illustrative purposes let's say I have a website at https://www.signup.com that let's users sign up for an email list. After the user enters their email and hits 'Submit,' signup.com sends POST request to https://www.manager.com: { "email" : "fake@whatever.com" } Then the server adds that email to the database. My question is: what's the best way to ensure that only signup.com is able to successfully send POST requests to manager.com? -
Django autocomplete based on drop down selection
I am storing the autocompletion data in SomeObject objects and successfully use the following to autocomplete with a filter based on current user: views.py def get_autocompletion_list(request): if request.is_ajax(): q = request.GET.get('term', '') results = [] if len(q) > 0: my_words = SomeObject.objects.filter(owner=request.user.id) words = my_words.filter(word__startswith=q) for w in words: results.append(w.word) data = json.dumps(results) else: data = '' mimetype = 'application/json' return HttpResponse(data, mimetype) template: <form action="/" method="post" id=""> {% csrf_token %} {{form.category}} </form> <input id="searching"> javascript function: $(function() { var selection = $(category_id).val() $("#searching").autocomplete({ source: "/api/get_autocompletion_list/", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 1, }); }); Now I want to filter the autocompletion based on the selection of form.category drop down, I am able to get the current selection in the form, but how would I send it to the view where I can do the filtering? -
How to make a buttons with colors of the rainbow in my cycle in html?
My project is made on jango framework. {% for tag in tags %} <div class="btngroup" role="group" aria-label="tags"> <h3><a href="{{ tag.get_absolute_url }}" class="btn btn-primary">{{tag.title}}</a></h3> </div> {% endfor %} I will explain a little. In this cycle, I get link tags from the database, which I want to wrap in buttons of different colors of the rainbow. But how to do that ? -
How to create another column with filtered value in queryset
I have a query that retrieves 20 questions. The query then should add another column or data to the queryset that indicates which choice the user has answered. So in total there are 4 models, including a User model. class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) Query Question.objects.filter( Q(user=3))[:20] How do I add another column in this query to show which choice the user picked? -
using css/ bootstrap webtabs for django forms
I run into the following issue with my Django project: I have an profile edit page, where I want the user to be able to edit their profile information, which is seperated in tabs that they can navigate: Profile and Extended Information. However, the page loads at the Profile tab, but when I navigate to the Extended Information tab, it just opens this tab below the Profile tab, and it doesn't 'replace' the first tab with the second. Consequently, I get a MultiValueDictKeyError error when I only change something in the Extended Information form under that tab. How do I fix the error with the tabs opening below each other? I suspect that my MultiValueDictKeyError also disappears then (but I'm not sure). Html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <!-- Nav tabs --> <div class="container profile"> <div> <h1>Edit your details:</h1> <h3><strong><a href="{% url 'users:profile' %}">{{user.username}}</a></strong></h3> </div> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Profile</a> <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Extended information</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> <form method="post"> {% csrf_token %} {% bootstrap_form basic_form %} …