Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap 3 split dropdown button creation
I'm trying to create a split dropdown button for my Django website and I'm using Bootstrap 3. Following is my code for the same: <li> <div class="btn-group"> <button type="button" class="btn btn-default navbar-btn">Action</button> <button type="button" data-toggle="dropdown" class="btn btn-default navbar-btn dropdown-toggle" aria-haspopup="true" aria-expanded="false"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li><a href="#">Separated link</a></li> </ul> </div> </li> But I'm getting this kind of weird output. I'm stuck at this problem from an hour. What am I doing wrong here? Why does the split arrow is not showing properly? -
Multiple forms in crispy-form Layout object?
I'm trying to use a crispy-forms Layout object on my project for form rendering. However, my main form includes a bit of a complicated layout: Fieldset Form1 Field1 Form1 Field2 Fieldset Column1 Form2 Field1 Form2 Field2 Column2 Form3 Field1 Form3 Field2 Fieldset Form1 Field3 Except it includes an assortment of columns and rows. On the Django side I'm covered - adding multiple forms to the view is no problem, however, utilizing the crispy-forms Layout object has me stumped. Since both Form1 and Form2 are separate model forms, I can't seem to combine them into a single Layout object. The advice that I've seen is mostly render the templates separately, i.e.: {% crispy form1 %} {% crispy form2 %} But, due to my required layout I can't really do that - if I do that, I will likely need to render most of the fields manually anyway so the Layout object is no help. Is there any way to embeded a Layout from another ModelForm in another one? Or make an external FormHelper with Layout that refers to fields from multiple forms? I've looked at FormSet solutions thinking they might be similar but I haven't found any solutions. Thanks for any … -
How to create a trip calculator in Django?
I'm working on a personal project. I need to add a trip calculator at the home page. How can I create the calculator functionalities? I intend to use BeautifulSoup to grab the daily fuel price from a site in a separate file, import the function that prints the fuel price into the calculator file and assign it to a variable to add it to the cost determining calculation. User will insert the fuel economy and approximate distance in text boxes. When user clicks on a ' calculate ' button, the total trip cost will appear in another text box or as a strong heading. I want to put the calculator inside a bootstrap class. Is a separate form for calculator be a better idea? -
Serializer vs Renderer in Django Rest Framework
I'm having trouble noticing the difference between serializer and renderer in django rest framework. I thought serializer is for converting the python object to JSON (or other data formats). But renderers, such as JSONRenders, are said to do the simillar thing, e.g. making(rendering) JSON object! Could you tell me the difference between those two? -
I'm having trouble with my bootstrap cdn in pycharm it's making my website look ugly lol
<link crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" rel="stylesheet"> suggested fix by pycharm <link crossorigin="anonymous" href="{% trans "https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" %}" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" rel="stylesheet"> When I paste the top it gives me an error saying unexpected token then I do the recommended fix which It fixes the problem but when I test my index.html it shows nothing centered and my navbar doesn't go across the page like set it If anyone knows how to fix this issue please help -
Django filter problem with date calculation
Django model has birth_year, birth_month, birth_day and death_year, death_month, death_day fields. model.py class person(models.Model): birth_year = models.SmallIntegerField() birth_month = models.SmallIntegerField() birth_day = models.SmallIntegerField() death_year = models.SmallIntegerField() death_month = models.SmallIntegerField() death_day = models.SmallIntegerField() I have to get the count of persons who lives less than 1 month. views.py return render(request, 'report.html', {'count': count}) how can I query in view.py I hope django expert's help. :) -
Django context processors model not found
I am trying to implement a context_processor in Django via a custom app. I am failing due to Module not found error. My app name is brand. My context processer looks like this: from .models import ContactDetail def contact(request): contact = ContactDetail.objects.first() return { 'contact' : contact } My app is included in installed apps and the model has been migrated. I have included my context processor into the context_processors list as per documentation: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'mysite', 'templates'),], 'OPTIONS': { 'context_processors': [ 'brand.context_processors.contact', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.template.context_processors.csrf', 'django.template.context_processors.tz', 'sekizai.context_processors.sekizai', 'django.template.context_processors.static', 'cms.context_processors.cms_settings', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader' ], }, }, ] The Error I am getting is: Django Version: 1.11.16 Exception Type: ModuleNotFoundError Exception Value: No module named 'brand.context_processors' I have tried searching for solutions but most of the questions are for previous versions of django ( <= 1.8 ) I am using 1.11.16. I have read through the docs and it is unclear what I am missing. Any help is apreciated. -
django-rest-auth registration/account-confirm-email/ how to use it to verify the user
I have used django allauth for user sign up and once the user registers, an email with the following url is sent to the user: http://127.0.0.1:8000/rest-auth/registration/account-confirm-email/MTY:1ggGpL:n8gHmRfOzgjR2vZTHopxiUkCe-w/ according to this: https://github.com/Tivix/django-rest-auth/issues/292 "You should override this view/url to handle it in your API client somehow...", but my question apart from overriding is that how this string "MTY:1ggGpL:n8gHmRfOzgjR2vZTHopxiUkCe-w/" in the sent email can be used to validate the email, Thanks, -
"Unknown type \"CreateAccountInput\". with graphene_django when trying to mutate/create new object
I'm new to graphQL and I've just been trying to create a new account object with it. This is my code right now but it the GUI for graphQL I keep getting the "Unknown type \"CreateAccountInput" error. schema.py from authentication.models import Account import graphene from graphene import relay, ObjectType from graphene_django import DjangoObjectType from graphene import InputObjectType class AccountGraphQL(DjangoObjectType): class Meta: model = Account interfaces = (relay.Node, ) class Query(graphene.ObjectType): username = graphene.String(argument=graphene.String(default_value="stranger")) email = graphene.String(argument=graphene.String(default_value="stranger")) password = graphene.String(argument=graphene.String(default_value="stranger")) first_name = graphene.String(argument=graphene.String(default_value="stranger")) info = graphene.String() def def_resolve_create_account(self, info, argument): return account.objects.create_user() class CreateAccountInput(InputObjectType): username = graphene.String(argument=graphene.String(default_value="stranger")) email = graphene.String(argument=graphene.String(default_value="stranger")) password = graphene.String(argument=graphene.String(default_value="stranger")) first_name = graphene.String(argument=graphene.String(default_value="stranger")) class CreateAccount(relay.ClientIDMutation): class Input: account = graphene.Argument(CreateAccountInput) new_account = graphene.Field(AccountGraphQL) @classmethod def mutate_and_get_payload(cls, args, context, info): account_data = args.get('account') # get account data from args account = Account() new_account = update_create_instance(account, account_data) return cls(new_account=new_account) class Mutation(ObjectType): create_account = CreateAccount.Field() schema = graphene.Schema(query=Query) result = schema.execute('{ create_account (argument: "graphql"') my mutation: mutation CreateNewAccount($input: CreateAccountInput!) { createAccount(input: $input) { newAccount { username email password first_name } clientMutationId } } my query {"input": {"account": { "username": "graphql", "email": "graphql@gmail.com", "password": "graphql", "first_name":"charles" } }} I'm not sure what the problem is here, as far as I'm concerned I've … -
ValueError: not enough values to unpack (expected 2, got 1) in Django
I'm having a problem in saving data to two tables of my database which is PurchaseOrder and PurchaseOrderLineItems using the generic view of Django the CreateView. I'm getting this error: ValueError: not enough values to unpack (expected 2, got 1) and I don't know where in the code is the error. I'm getting the data from a html table ( it has checkbox per row ) that is generated by another table called Masterlist that will save in PurchaseOrderLineItems. Here's what I tried by searching of how can I save the data. I created a post function inside the CreateView class. class PurchaseOrderCreateView(LoginRequiredMixin, CreateView): model = PurchaseOrder fields = ['project_site', 'supplier'] def form_valid(self, form): form.instance.prepare_by = self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): kwargs['object_list'] = Masterlist.objects.all() return super(PurchaseOrderCreateView, self).get_context_data(**kwargs) def post(self, request, *args, **kwargs): po = PurchaseOrder.objects.all() if request.method == 'POST': get_list = request.POST.getlist('checks[]') for item in get_list: get_id = Masterlist.objects.filter(item[0]) save_to_pol = PurchaseOrderLineItems(item_no=get_id.item_no, description=get_id.description, dimension=get_id.dimension, unit=get_id.unit, quantity=get_id.quantity, cost=get_id.cost, total=get_id.cost * get_id.quantity, po_fk=pk) save_to_pol.save() return super().post(request) What I want is when the user fills up the fields for the PurchaseOrder and then checked the items in the html table (generated by Masterlist) and hit the button, it will save the the … -
django how to use property to create a column entry
I have a django model class Process(models.Model): start_utc = models.TimeField(db_column='start', null=True, blank=True) end_utc = models.TimeField(db_column='end', null=True, blank=True) and I want to add a property should_run I tried to use the @property method as shown in https://docs.djangoproject.com/en/2.1/topics/db/models/ where the @property is used without having an attribute in the class definition class Process(models.Model): start_utc = models.TimeField(db_column='start', null=True, blank=True) end_utc = models.TimeField(db_column='end', null=True, blank=True) @property def should_run(self): now = dt.datetime.utcnow().time() print(self.__str__(), now, self.start_utc, self.end_utc) return self.start_utc < now < self.end_utc But this way there is not column entry created at all. I also tried to do it the classic way class Process(models.Model): start_utc = models.TimeField(db_column='start', null=True, blank=True) end_utc = models.TimeField(db_column='end', null=True, blank=True) _should_run = models.BooleanField(default=False, db_column="should_run") @property def should_run(self): now = dt.datetime.utcnow().time() print(self.__str__(), now, self.start_utc, self.end_utc) return self.start_utc < now < self.end_utc @should_run.setter def should_run(self, val): self._should_run = val This way, when I render the table I get from the Model, I have a column should_run but it appears the getter is never called and the column value will always be the initial default. How can make this work such that it would create a column with values it gets from the @property getter? -
How to safely wrap an object into an array in TypeScript?
I am trying to submit an angular form to a backend API implemented in Django. when I submit the form it shows the following error "string indices must be integers" Post Request method postEntries(formData: MeasurementChange): Observable<any> { return this.http.post(this.baseUrl + this.postDataUrl, formData); } Post request sends in the following format {id: 2, percent_complete: 45} id: 2 percent_complete: 45 API accepts the following format [{ "id":1, "percent_complete": 33 }] How can I wrap my object in API accepted format/Array? -
django model id not changing through for look
so I have a for loop in my Django template that loops through a product in my products model. The product model has an amount attribute that is supposed to change when the user clicks on the 'add' button. I have made a hidden form that launches the upvote method which takes a request and a pk and increases the amount attribute by 1. The problem is that when I click on the add button, only two of the product's amount increase. I can't get the rest of the products' amount attribute to increases. Here's the Django template code: <div class="card-deck d-flex justify-content-start container-fluid"> {% for product in products %} <div class="card lead m-3" style="min-width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <h6 class="card-subtitle mb-2 text-muted">{{ product.product_id }}</h6> <hr> <p class="card-text"> Expiration date: {{ product.expiration_date }} </p> <p class="card-text"> amount: {{ product.amount }} <a href="javascript:{document.getElementById('upvote').submit();}"><button class="btn btn-primary btn-sm">+</button></a> </p> <p class="card-text"> tags: {% for t in product.tag.all %} <span class="badge badge-primary">{{ t.name }}</span> {% endfor %} </p> </div> </div> <form action="{% url 'upvote' pid=product.id %}" method="POST" id="upvote"> {% csrf_token %} <input type="hidden"> </form> here's the upvote method in the views.py file: def upvote(request, pid): if request.method == "POST": product = … -
Angular / Django: CSRF Token (Cookie) Added by Safari Service Worker, Not Chrome Service Worker, Not Wanted
Bottom Line, Safari Service Workers are Adding an unwanted Cookie and I have no idea why. I have a website which works with any iOS mobile, Chrome, iPhone app, and Android app. But Safari Desktop with a service worker gives me strange behavior. When I execute a POST a request, I get the response CSRF Failed: CSRF token missing or incorrect. But only in Safari on desktop. My POST request looked normal until I inspected the service worker. I use JWT. All POST requests below have the JWT token. But the Safari request adds a Cookie from the service worker. Safari Request - No Cookie Safari Service Worker making request on behalf of Safari - Added Cookie Chrome Request - No Cookie Chrome Service Worker making request on behalf of Chrome - No Cookie Below is a screenshot of all and some code. I'm at a loss, let me know what information you need. Front end uses angular. It executes a post with: import { HttpClient, HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), }; this.http.post<Place>(this.placesUrl, place, httpOptions) I use Django 2.1 with Django Rest Framework, CORSHeaders, and Django Rest Framework JWT. 'rest_framework.authentication.SessionAuthentication' is … -
pipenv install django==2.1 does not create Pipfile and Pipfile.lock
I installed django in my project directory hello. It showed Pipfile and Pipfile.lock. Then, I deleted directory hello with "rm -r hello". Now, I have an interesting bug. When I try "pipenv install django==2.1" in new folder, say hello2, installation "succeeds" but both Pipfile and Pipfile.lock files are missing! Here's what I've tried so far: uninstall both pipenv and django 2.1 and re-install them again. Bug lives. Someone asked a similar question on git (https://github.com/pypa/pipenv/issues/1286) but answers were not helpful. -
How do I get related objects in nav tabs in django
I have three related models that I want to get the related objects in tabs under the navigations The view def quiz_department(request, dept_id): department = get_object_or_404(Department, id=dept_id) subject = department.subject_set.all() return render(request,\ "multiquiz/department.html",\ {"department":department, "subject":subject}) def subjects(request, subject_id): subject = Subject.objects.get(id=subject_id) return render(request, 'multiquiz/subjects.html', {"subject":subject}) department.html {% extends "base.html" %} {% block content %} <h1>{{department.department}}</h1> <ul class="nav nav-tabs"> {% for sub in subject %} <li class="nav-item"> <a class="nav-link" href="{% url "multichoice:subjects" sub.id %}">{{sub.subjects}}</a> </li> {% endfor %} </ul> {% endblock %} subject.html {% extends "base.html" %} {% block content %} <h1>{{subject.department.department}}</h1> <ul class="nav nav-tabs"> <a href=""></a> </ul> <div class="container"> <div class="col-lg-6"> <div class="jumbotron"> {% for question in subject.question_set.all %} {{question.text}} {% endfor %} </div> </div> </div> {% endblock %} Now I was wondering i've tried couldn't figure this one out. how to get something like this image. any suggestion, pointers will be most gratefully welcomed by me. ps: igonore the image typo ;) -
Obtain auth token using email instead of username
I'm trying to obtain auth token using email instead of username, i have changed serialized to accept just email but i think that i have something wrong. class AuthTokenSerializer(serializers.Serializer): """Serializer for user authentication object""" email_or_username = serializers.CharField() password = serializers.CharField(style = {'input_type' : 'password' }, trim_whitespace = False) def validate(self, attrs): """Validate and authentiate the user""" email_or_username = attrs.get('email') password = attrs.get('password') user = authenticate(request = self.context.get('request'), username = email, password = password) if not user: msg = _('Unable to authenticate with provided credentials.') raise serializers.ValidationError(msd, code='authorization') attrs['user'] = user return attrs And the View class LoginViewSet(viewsets.ViewSet): """Check email and password and returns an auth token.""" serializer_class = serializers.AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES def create(self, request): """Use the ObtainAuthToken APIview to validate and create a token.""" return ObtainAuthToken().post(request) when i make a test def test_create_token_for_user(self): """Test that a token is created""" parametrs = {'email' : 'test@noah-lc.com','email' : 'test@noah-lc.com', 'name' : 'test', 'password' : 'testPASS@123'} create_user(**parametrs) res = self.client.post(TOKEN_URL, parametrs) print(res.data) self.assertIn('token', res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) I got this error AssertionError: 'token' not found in {'username': [ErrorDetail(string='This field is required.', code='required')]} -
to use the functions of the postgresql window in django ORM with arithmetic calculations?
I use postgresql window functions like LAG in some queries that I need to do in Django. I have it working in raw SQL, but I'm not sure how to do it in the ORM. Simplified it looks like this: SELECT fecha_registro, hora, produccion_neta, produccion_neta - LAG (produccion_neta,1) OVER (PARTITION BY hora ORDER BY hora ASC,fecha_registro ASC) AS prod_dia_anterior FROM crudo_produccionoperadadiaria INNER JOIN crudo_horaregistroproduccion ON crudo_produccionoperadadiaria.tiempo_produccion_id = crudo_horaregistroproduccion.id In django like that: def produccion_operada_dia_list(request): #prod_oper_dia = ProduccionOperadaDiaria.objects.order_by('fecha_registro') prod_oper_dia=ProduccionOperadaDiaria.objects.annotate(variacion=Window( expression=Lag(F('produccion_neta'),1), order_by=[F('tiempo_produccion').asc(), F('fecha_registro').asc()], partition_by=F('tiempo_produccion'))) context = {'prod_oper_dia': prod_oper_dia} return render(request, 'crudo/produccion_operada_dia_list.html', context) However I do not know how to implement the subtraction to have the variation: SELECT fecha_registro, hora, produccion_neta, ***produccion_neta - LAG (produccion_neta,1)*** OVER (PARTITION BY hora ORDER BY hora ASC,fecha_registro ASC) AS prod_dia_anterior FROM crudo_produccionoperadadiaria INNER JOIN crudo_horaregistroproduccion ON crudo_produccionoperadadiaria.tiempo_produccion_id = crudo_horaregistroproduccion.id how can I do? -
Wagtail: Page content on search results page?
Is there some way to access the content of a Page on the search results page? In this configuration, the title, url, and Search Description fields are available. def search(request): search_query = request.GET.get('q', None) if search_query: search_results = Page.objects.live().search(search_query) # Log the query so Wagtail can suggest promoted results Query.get(search_query).add_hit() else: search_results = Page.objects.none() return render(request, 'website/templates/search_results.html', { 'search_query': search_query, 'search_results': search_results, }) What can I add to access the other fields of a Page in search_results? -
django using multiple SESSION ENGINE?
i currently want to use redis and encrypted_cookies (https://github.com/brightinteractive/django-encrypted-cookie-session/) as SESSION_ENGINE in my project settings.py file but how can i set both of them for my Django Application?? Is there actualy any need to use encrypted cookies if i use redis? settings.py ... SESSION_ENGINE = 'encrypted_cookies' ... -
Update specific cell via python in html
im making a website that displays an object from the database with associated items(foreginKey). As of now i list the components in a table and it works fine. Also works with refresh to update the values. But i want only the cell with the dynamic value to update without calling the refresh to reload the whole page to stop flickering images etc. Havent really tried much as im not so good at this, tho i figured that i need som "id" on the to make it targetable perhaps? Also i think i need to put the .value outside the initial for loop and maybe loop it seperatly inside SetInterval function. But how do I do that? I am using Django 2.1.4 / Python 3.7.1 / Win10 / MSSQL running on localhost at the moment. Also my first question here so hope the formatting is good. <h2>{{ object.name }}</h2> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>Description</th> <th>Name</th> <th>Fabrikat</th> <th>Type</th> <th>Value</th> </tr> </thead> <tbody> {% for komponent in object.komponent_set.all %} <tr> <td>{{ komponent.beskrivning }}</td> <td>{{ komponent.namn }}</td> <td>{{ komponent.fabrikat }}</td> <td>{{ komponent.typ }}</td> <td>{{ komponent.value }}</td> </tr> {% endfor %} <script> var myVar = setInterval(valueRefresh, 5000); function valueRefresh() { {% … -
How to wrap an object into an array in TypeScript
I am trying to submit an angular form to a backend implemented in Django. When I make a post request I get the following error "string indices must be integers". enter image description here enter image description here -
Multiple User Models with different fields and login pages?
I already have a model called User which looks like this: class User(AbstractBaseUser): email = models.EmailField( unique=True, ) first_name = models.CharField( max_length=30, ) last_name = models.CharField( max_length=150, ) objects = UserManager() USERNAME_FIELD = 'email' This User model has the following login page on the website: example.com/login/ Now I want to create another model called Employee The Employee model basically looks like the User model with some additional fields like company, salary etc. The Employee user can only login on a specific page and not on the same page like the User model: example.com/employee-login/ My question is how should I build the Employee model. Is it good to create a complete separate model for the Employee that has nothing to do with the User model? And can I use still use the Login, Register, Password Reset etc. views from from Django that I used for the User model? -
Django Count and Group By Two Field's Values
I have a model like this : CLASS_TYPE = ( ("A","A Class"), ("B", "B Class") , ("C", "C Class") , ("D", "D Class") ) class Student(models.Model): systemId = models.CharField(max_length=15, unique=True ) studentNo = models.CharField(max_length=15, unique=True ) country = models.CharField(max_length=10) clasType = models.CharField(max_length=2, choices=CLASS_TYPE ) recordDate = models.DateField() ... And have a lot of records. I am interesting with two fields only "country" and "classType". I want to count all class types, according to country and sum . I want to get this list of dictionaries from "Student" model : [ { "country":"USA" , "A" : Count_Of_A_Class_in_USA , "B" : Count_Of_B_Class_in_USA , "C" : countCinUSA , "D": count_D_in_USA , "Total" : total_students_in_USA } , {"Country":"England" , "A" : A_in_England ...., "C":C_in_England... , "Total" : students_in_England } ] How can i get this ? -
Add an annotation value to select_related
I'd like to add an annotation to a field that I fetch with select_related. I know that you can do that with prefetch_related like this: vote_qs = Vote.objects.annotate(my_count=Count('a_field')) queryset = MyModel.objects.prefetch_related( Prefetch('votes', queryset=vote_qs) ) What I like to do is something like user_qs = User.objects.annotate(my_count=Count('a_field')) queryset = MyModel.objects.select_related( Select('user', queryset=user_qs) ) Django doesn't support that. But how can I do that and avoid raw SQL as far as possible? (I couldn't find any information via Google.) To clarify, this might be a workaround but then I can't do another filter or something anymore: queryset = list( MyModel.objects .annotate(my_count=Count('user__a_field')) .select_related('user') ) for obj in queryset: obj.user.my_count = obj.my_count