Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Edit a cell in the table save to the django model
I have a table of employees. I am loading data using $http and using ng-repeat to print it on the webpage. I want to edit each row content. HTML: tbody ng-repeat="list in data" > <tr ng-hide="edit" ng-click="edit=true"> {% verbatim %} <td> {{$index + 1}}</td> <td>{{ list.associate_nbr }}</td> <td>{{ list.per }}%</td> <td>{{ list.count }}</td> <td>{{ list.sample_per }}%</td> <td>{{ list.sample}}</td> <td><input type="text" value="{{ list.focused }}"></td> <td><input type="text" value="{{ list.random_field }}"></td> </tr> {% endverbatim %} MAIN.JS (function(){ 'use strict'; angular.module('sampling.demo',[]) .controller('SamplingController', ['$scope','$http',SamplingController]); function SamplingController($scope,$http) { $scope.data = []; $http.get('/sample/').then(function(response){ $scope.data = response.data; }); } }()); I want to edit the last two fields when user clicks on it. -
Django media files not loading
I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below. models.py from django.contrib.auth.models import User from django.db import models from django.contrib.auth.models import AbstractUser class profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='media/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' profile.html <!DOCTYPE html> {% extends 'base2.html' %} {% load crispy_forms_tags %} {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>profile</title> </head> {% block content %} <body style="margin-left: 300px"> <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png"> </div> </div> </body> {% endblock %} </html> settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' print(MEDIA_ROOT) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] urls.py(the main urls.py, not of app users) from django.contrib import admin from django.urls import path, include from users.views import profile from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls'), name='index'), path('profile/', profile, name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Django: bulk_destroy returns "400: Bad request"
I have a Django viewset MyModelViewset that extends MultipleDBModelViewSet (from the base viewsets). The base viewset contains the following method that is not overwritten in MyModelViewset: def bulk_destroy(self, request, *args, **kwargs): ids = json.loads(request.query_params.get("ids")) if not ids: return super().destroy(request, *args, pk=kwargs.pop("pk"), **kwargs) else: return super().bulk_destroy(request, *args, **kwargs) I am assuming that this method means I can pass a parameter called ids and all of the objects with those ids will be deleted? I've tried sending a delete request to the associated URL: v1/mymodel?ids=["4cea187e-56af-439c-96a7-e001d85c5000","3d7bd2ac-bc27-4a1b-acfd-9b651852114e"] -> this returns a 200 response and behaves like a GET request v1/mymodel?ids=["4cea187e-56af-439c-96a7-e001d85c5000","3d7bd2ac-bc27-4a1b-acfd-9b651852114e"]/ -> this returns a 400 response "Bad request" MyModels with these ids do exist in my DB. What am I doing wrong? -
django rest framework serialize a dictionary without create a model
My data is like this, I want to serialize them without creating model for them. [ {'form': 1, 'count': 1}, {'form': 2, 'count': 3} ] serilize to [ {'form': 'my form name 1', 'count': 1}, {'form': 'my form name 2', 'count': 3} ] I want to serialize it with serializer, get form name form model by pk. class EavForm(models.Model): name = models.CharField(max_length=300) order = models.IntegerField(default=1) # serializer class CustomSerializer(serializers.Serializer): form = serializers.PrimaryKeyRelatedField(queryset=EavForm.objects.all()) count = serializers.IntegerField() Some error like 'int' object has no attribute 'pk' -
Perform CRUD operations on product class?
I'm a newbie to Django-oscar and I'm trying to develop a simple CRUD operation on Product. I've forked the catalogue app and created a views.py file I fired the query Product.objects.create(title='Hello') and a product does get created with the following error: AttributeError: 'NoneType' object has no attribute 'attributes' product_title = 'MyPhone' upc=987654321 product_class = ProductClass.objects.get_or_create(name='Phone') def createProduct(request): line1 product.name = product_title product.product_class = product_class product.upc=upc product.save() When I put product=Product() in line1 I get the following error: Cannot assign "(, False)": "Product.product_class" must be a "ProductClass" instance. When I put product = Product.objects.create(upc=upc) I get the following error : NoneType' object has no attribute 'attributes' Anyone guide me on how to write a simple create operation? -
Template not rendered when request made from java script to view function using ajax
The django template calls a java-script function on click of a submit button.This java-script function redirects the request to a django view function where a template is to be rendered. The java-script function is being called but the the django view function doesn't render the template even though both the functions are found to be called when debugged. Django template: <button type="submit" id ="b" name="b" onclick="edit(document.myform.checks,5)" formmethod="get" class="btn btn-danger" disabled>&nbsp &#9998; &nbsp</button> Django view function: def edit(request,i,unique_key): add=False template ='pms_app/form.html' form=Myform(instance=(Mymodel.objects.get(id=unique_key))) if request.method=="POST": form=Myform(request.POST,instance=( Mymodel.objects.get(id=unique_key))) if form.is_valid(): form.save() return redirect ('pms_app:display',i=i) else: print(form.errors) return render(request, template, context={'form':form,'unique_key':unique_key}) Javascript function: function edit(chk, i) { var len = 0; var x=0; for (j = 0; j < chk.length; j++) { if (chk[j].checked == true) { len++; if (len > 1) { break; } x = chk[j].value; } } var edit_url = 'edit/' + i + '/' + x; if (len > 1) { alert("Please select only one record to edit!") } else { alert(edit_url); $.ajaxSetup({ data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ url: edit_url, type: "GET", success: function () { alert("requested access complete"); }, error: function () { alert("requested access failed"); } }) } } Any idea/help on why the … -
How to convert user selected date time to milliseconds
How to convert user selected date time to milliseconds. I am rendering date time from HTML page and stored into datetime_obj variable. How to convert variable date to milliseconds.Help me to do that. views.py def datetime1(request): if request.method == 'POST': form = DatetimeForm(request.POST) if form.is_valid(): datetime_obj = request.POST.get('datetime') dt = datetime(datetime_obj) milliseconds = int(round(dt.timestamp() * 1000)) print(milliseconds) return render(request, 'datetime.html', {}) return render(request, 'datetime.html', {}) datetime.html <form action="#" method="post"> {% csrf_token %} <input type="datetime-local" name="datetime" > <button type="submit">Submit</button> </form> urls.py urlpatterns = [ path('datetime/', views.datetime1, name="datetime1"), ] -
ProgrammingError at / relation "Django-Personal-Website_project" does not exist LINE 1: ..."Django-Personal-Website_project"
So for heroku i couldn't use dbsqlite3 as my database, so I tried switching it to Postgre and I encountered a problem which I also received from deploying my Personal Website on Heroku. I have had so much trouble and have no idea how to fix it. I am trying to add a projects panel to my Website but whenever I add this HTML to the site I get an relation does not exist error. I believe it is because I switched to PostgreSQL but dont know why the problem is what it is. Someone please help!! DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django', 'USER': 'chrisrosales', 'PASSWORD': 'notgonnashowlol', 'HOST': 'localhost', 'PORT': '5432', } } The problem is this portfolio... <section id="portfolio" class="pfblock"> <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> <div class="pfblock-header wow fadeInUp"> <h2 class="pfblock-title">My works</h2> <div class="pfblock-line"></div> <div class="pfblock-subtitle"> </div> </div> </div> </div><!-- .row --> <div class="row"> {% for project in list_projects|slice:":2" %} <div class="card col-xs-12 col-sm-5 col-md-5"> <div class="grid wow zoomIn"> <figure class="effect-bubba"><a href="{{ project.url }}" target="_blank"> {% with 'Django-Personal-Website/images/'|add:project.img_name as image_static %} <img class="card-img-top" src="{% static image_static %}"></a> {% endwith %} </figure> <div class="card-block"> <h2 class="card-title">{{ project.title }}</h2> <p class="card-text">{{ project.description }}</p> <div class="tools"> {% … -
How can i put values in a modelformset field?
I have a modelformset which takes attendance of students. The models.py looks like: class Attendance(models.Model): Student = models.CharField(max_length=100, blank=False) Hour = models.CharField(max_length=1, blank=False) Subject = models.CharField(max_length=8, blank=False) Date = models.DateTimeField(default=timezone.now) Presence = models.BooleanField(default=False, blank=False) def __str__(self): return f'{self.Student}' And my views.py: ef academics(request): if request.user.is_staff: formset = modelformset_factory(Attendance, fields=('__all__'), extra=60) if request.method == "POST": form=formset(request.POST) form.save() form = formset(queryset=Attendance.objects.none()) return render(request, 'console/academics.html',{'form':form}) else: context = { 'attends': Attendance.objects.all().exclude(Date=timezone.now()), 'todays': Attendance.objects.filter(Date=timezone.now())[:8] } return render(request, 'student/academics.html',context) How can I set the values of Students field values to the names of the User.objects.filter(profile__Year='SY',profile__Department='CSE'), which contains the names of the students of a department and a year. -
installed django-redis in python virtualenv, redis-cli command not found
I just install redis-cli using pip in python virtualenv,but when I type redis-cli, shows me redis-cli command not found. I'm pretty much sure redis-cli has been installed sucessfully. need your help thx in advance -
django redirects not working in electronjs
I am creating an account management app for my father's company. I integrated Django with electron like this=> mainWindow.loadURL('http://localhost:8000') And in package.json. I did this in scripts => "start": "start python manage.py runserver && start electron ." In my createView, DetailView, DeleteView. I added this => success_url = reverse_lazy('home') If i open this in chrome browser it works absolutely fine no worries. But if i do this in electron. It show this msg => Page not found (404) Request Method: GET Request URL: http://localhost:8000/delete/11 Raised by: accounts.views.EntryDeleteView plz help! -
ModuleNotFoundError psycopg2 when deploying in heroku even though psycopg2 is installed
I migrated my website from sqlite3 to postgresql. I'm deploying my website in heroku but this error came up when I'm executing command push heroku master -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.3 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Installing python-3.7.2 -----> Installing pip -----> Installing dependencies with Pipenv 2018.5.18… Installing dependencies from Pipfile… -----> Installing SQLite3 -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
in Django where we call function or class
def display(request): return render(request, 'base.html') I have curiosity about where we call this is working why not need to call the function -
Angular 8: not able to get message from Rest Api
Following those links https://grokonez.com/python/django-angular-6-example-django-rest-framework-mysql-crud-example-part-2-django-server and https://grokonez.com/frontend/django-angular-6-example-django-rest-framework-angular-crud-mysql-example-part-3-angular-client I created a django rest API and angular app that calls this rest. Considering that I'm new in such kind of development I created as a first step an App that just displays customers list. Django rest API is fine working. I tested it with the browser: But my problem is with the angular app, seems that it's not able to get message with the same URL: http://localhost:8000/customers Below is my angular code: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule, routingComponents } from './app-routing.module'; import { AppComponent } from './app.component'; import { CustomersListComponent } from './customers-list/customers-list.component'; @NgModule({ declarations: [ AppComponent, routingComponents, CustomersListComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CustomersListComponent } from './customers-list/customers-list.component'; const routes: Routes = [ { path: 'customers', component: CustomersListComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } customer.ts export class Customer { id: number; name: string; age: number; active: boolean; } customer.service.ts import { … -
chat socket is closing unexpectedly (django-channels)?
i have gone through as it mentioned in the docs(channels) it worked fine until i pasted the code of channel_layers in settings.py i installed all the specifications mentioned in channel_layers ASGI_APPLICATION = 'mysite.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } why is my chat_server closing unexpectedly -
Submit a form after two clicks on submit Django
I'm doing a quiz site, and I have several questions. I currently access a certain category and is shown one question after another after clicking submit. But I would like to click once, show the response on the same screen, and after clicking it again go to the next question. How would I do that? This is my views.py file: class Perguntas(FormView): form_class = QuestaoForm template_name = 'certificacoes/pergunta.html' template_name_result = 'certificacoes/finalizado.html' def dispatch(self, request, *args, **kwargs): self.dominio = get_object_or_404(Dominio, slug=self.kwargs['slug_dominio']) try: self.user_logado = self.request.user.is_authenticated() except TypeError: self.user_logado = self.request.user.is_authenticated if self.user_logado: self.sessao = Sessao.objects.usuario_sessao(request.user, self.dominio) return super(Perguntas, self).dispatch(request, *args, **kwargs) def get_form(self, *args, **kwargs): if self.user_logado: self.questao = self.sessao.pegar_primeira_questao() form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(Perguntas, self).get_form_kwargs() return dict(kwargs, questao=self.questao) def form_valid(self, form): if self.user_logado: self.form_valid_usuario(form) if self.sessao.pegar_primeira_questao() is False: return self.resultado_final_usuario() self.request.POST = {} return super(Perguntas, self).get(self, self.request) def form_valid_usuario(self, form): progresso = Progresso.objects.get_or_create(usuario=self.request.user) hipotese = form.cleaned_data['respostas'] is_correta = self.questao.checar_correta(hipotese) if is_correta is True: self.sessao.adicionar_ponto(1) else: self.sessao.add_incorreta(self.questao) # Tenho que mexer aqui para gerar uma nova questão self.anterior = { 'resposta_escolhida': self.questao.alternativa_escolhida(hipotese), 'resposta_correta': is_correta, 'questao_resposta': self.questao.enunciado, 'respostas': self.questao.pegar_alternativas(), 'alternativa_correta': self.questao.alternativa_correta(), 'fundamento': self.questao.alternativa_fundamento(hipotese) } self.sessao.add_usuario_resposta(self.questao, hipotese) self.sessao.remover_primeira_questao() def get_context_data(self, **kwargs): context = super(Perguntas, self).get_context_data(**kwargs) context['questao'] = self.questao … -
Django: Get dropdown value and select dynamic form fields for Class Based views
I would like to ask how I can retrieve a drop-down GET value to be used as a Form select logic within a Class Based FormView. By calling the Context as a function works fine (see fully functional code below) but I cannot retrieve the GET value to be used within a logic for a Class Based View. E.g. now I call it as a function: path('cooking/', cooking, name="cooking") But would like to call it as a Class Based FormView instead, such as: path('cooking/', CookingView.as_view(), name="cooking") I am struggling to translate the GET select logic (see code below) into my new CookingView(FormView): class CookingView(FormView): form_class = CookingForm template_name = 'form/cooking.html' def get_context_data(self, **kwargs): """ # some logic to get a desired form, such as ingredients_form = [] if recipe_choice == '1': ingredients_form = HamburgerForm(request.POST) elif recipe_choice == '2': ingredients_form = PancakeForm(request.POST) """ context = super(CookingView, self).get_context_data(**kwargs) context['ingridients_form'] = ingredients_form return context **Below I provide complete code that works. views.py def cooking(request): context = {} recipe_choice = request.GET.get('recipe_select', False) ingredients_form = [] if recipe_choice == '1': ingredients_form = HamburgerForm(request.POST) elif recipe_choice == '2': ingredients_form = PancakeForm(request.POST) context['cookbook_form'] = CookingForm(request.GET or None) context['ingridients_form'] = ingredients_form return render(request, 'form/cooking.html', context) models.py class Ingridients(models.Model): … -
Django, CBVs and pk_url_kwarg is missing
I am learning django. I have the latest django and Python 3.7.x. I have a question about self.pk_url_kwarg and how it is created and when. I have seen the doc at: https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-single-object/ but am not finding the answer I hope for. Specifically, I have an entry in a url.py file like: ... path( 'Student/createFromProfile/<uuid:profile_id>', student.CreateFromProfile.as_view(), name="student_create_from_profile" ), ... I have a CBV for this that starts: @method_decorator(verified_email_required, name='dispatch') class CreateFromProfile(CreateView): model = Profile success_url = '/Members' def get(self, request, *args, **kwargs): try: account_holder = Profile.objects.get( id=self.kwargs["profile_id"] ) except ObjectDoesNotExist: messages.error( request, "Unknown Profile ID." ) return HttpResponseRedirect(self.success_url) Notice in the get method the try and the section id=self.kwargs["profile_id"]. I was trying to use id=self.kwargs[self.pk_url_kwarg] but I get a django debug page that says that it has no idea what pk_url_kwarg is. I can stop in the PyCharm debugger and inspect self and indeed, it has no entry for pk_url_kwarg. This is extra special strange because I am using this in other views. What am I missing? -
Django Signal.disconnect raises 'function' object has no attribute 'lock' error
I have a function that is the receiver of signals from all models of the system. I want the signals to be interrupted when I am making an database dump population through a Django command, so it wouldn't be invoked when model instances are created by this mean. This is my receiver function: @receiver(post_save) def trigger_payment(sender, instance=None, created=False, **kwargs): from TreasuryManagementApp.models import PaymentApplicationTrigger if instance.__class__.__name__ not in trigger_models: return strategies = EventStrategies() application_triggers = PaymentApplicationTrigger.objects.filter(event_name__in=trigger_models[instance.__class__.__name__]['event_names']) for application_trigger in application_triggers: strategies.execute(application_trigger, instance) And this is the code of my command where I attempt to disconnect the function from signals: class Command(BaseCommand): help = _("""Run this command to import partners and operators from plane files""") def execute(self, *args, **kwargs): from TreasuryManagementApp.controllers import trigger_payment Signal.disconnect(trigger_payment) self.import_partners() self.import_operators() self.import_dead_ones() The problem is that this call to Signals.disconnect() raises the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/taxistas/GeneralApp/management/commands/startdatabase.py", lin e 21, in execute call_command('import_people') File "/Users/hugovillalobos/Documents/Code/TaxistasProject/TaxistasVenv/lib/python3.7/site-packages/django/core/managemen t/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/Users/hugovillalobos/Documents/Code/TaxistasProject/taxistas/GeneralApp/management/commands/import_people.py", lin e 433, in execute Signal.disconnect(trigger_payment) … -
How to prevent Django form being reset after clicking page buttons
I have a Django form that takes input values from users. The values are then used in making query to a table, which finally returns a list of filtered results. Since the results might be a long list, I added a pagination function with "Prev" and "Next" buttons. My problem is that when I click "Prev" or "Next" button, the form gets restored into default values. How do I prevent this from happening? I think the form gets reset because of "form1 = QueryForm()" when a request is not "POST". However I just have difficulty coming up with a neat solution. In views.py: def search(request): if request.method == "POST": form1 = QueryForm(data=request.POST) layer_dict = [] if form1.is_valid(): inp_ct = form1.cleaned_data['country'] q1 = ResourceBase.objects.filter(country_name__iexact=inp_ct) for layer in q5: down_url = 'xxxxxxx'.format(layer.title) view_url = 'xxxxxxx'.format(layer.title) layer_dict.append((layer.title, down_url, view_url)) layer_dict = sorted(layer_dict, key = lambda x:x[0]) paginator = Paginator(layer_dict, 10) page = request.GET.get('page', 1) try: layers = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. layers = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. layers = paginator.page(paginator.num_pages) context = {'form1': form1, 'layers': layers} else: form1 = QueryForm() context … -
in django SignupForm signup method is not being overrided
I have this working SignupForm in Django==1.10.6. The form is working because when I change a label it gets reflected in the form, but the signup method is never executed. I've been struggling with this for a while now, what am I missing here? The output is never printed, the user is not saved properly and the ipdb module does not start. # -*- coding: utf-8 -*- from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Field, Fieldset, ButtonHolder, Submit, HTML, Div from crispy_forms.bootstrap import TabHolder, Tab, Accordion, AccordionGroup from alistate.core.utils import LowerField from allauth.account.forms import SignupForm as SignupFormBase from django.contrib.auth import get_user_model class SignupForm(SignupFormBase): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Div( Div(Field('username'), css_class='col-md-12'), Div(Field('email'), css_class='col-md-12'), Div(Field('password1'), css_class='col-md-12'), Div(Field('password2'), css_class='col-md-12'), css_class='row'), Div( Div(Field('nombre1'), css_class='col-md-6'), Div(Field('apellido1'), css_class='col-md-6'), css_class='row'), Div( Div(Field('nombre2'), css_class='col-md-6'), Div(Field('apellido2'), css_class='col-md-6'), css_class='row'), Div( Div(Field('telefono'), css_class='col-md-12'), css_class='row'), Div( Div(Field('fecha_religiosa', css_class="datetimepicker-signup"), css_class='col-md-12'), css_class='row'), Div( Div(Field('como_conocio'), css_class='col-md-12 register-know'), css_class='row'), ) nombre1 = LowerField(label="Nombreeee 1 (novia/o).", required=True, max_length=50) apellido1 = LowerField(label="Apellido 1 (novia/o).", required=True, max_length=50) nombre2 = LowerField(label="Nombre 2 (novia/o).", required=True, max_length=50) apellido2 = LowerField(label="Apellido 2 (novia/o).", required=True, max_length=50) fecha_religiosa = forms.DateTimeField(required=True) telefono = LowerField(label=u"Teléfono", required=True, max_length=50) como_conocio = forms.CharField(label=u"¿Cómo … -
Javascript button not responding when clicked
I am attempting to use listjs in a django project i am making. But even when running a snippet taken from the documentation, django refused to run it properly. Take this pen for example. I copy this and put it in my html template. The template now has the following <script src="//cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script> <script type="text/javascript"> var options = { valueNames: [ 'name', 'born' ] }; var userList = new List('users', options); </script> <div id="users"> <input class="search" placeholder="Search" /> <button class="sort" data-sort="name"> Sort by name </button> <ul class="list"> <li> <h3 class="name">Jonny Stromberg</h3> <p class="born">1986</p> </li> <li> <h3 class="name">Jonas Arnklint</h3> <p class="born">1985</p> </li> <li> <h3 class="name">Martina Elm</h3> <p class="born">1986</p> </li> <li> <h3 class="name">Gustaf Lindqvist</h3> <p class="born">1983</p> </li> </ul> </div> Result is the page loads fine with no errors in the console but the button or the search do not work at all. I think it is something obvious i am missing here but cant seem to track it. -
pytest with database details from command line and fixtures
I am trying to initialize the db for pytest through values passed from command line. I cannot specify the values in a different test setting.py, nor can I specify it in TEST option in settings.py; it is only available through command line. I have setup extra command line options in confttest.py, to get the db details: def pytest_addoption(parser): parser.addoption( "--dbconnection", action="store", default = "novalue", help="test db value" ) Is there any way I can access these values in conftest.py? AFAIK, I can use fixtures to get the value in the test, but I would like to override django_db_modify_db_settings to change the database, with these command line arguments. Is this possible? Is the database initialized before the command line is processed? I tried some experiments and it does look so. Is there any other workaround to getting this working? -
How to protect SELECT * FROM var1 WHERE var2 statements from SQLInjection
I am making a website in django where I want the user to put in a table id and group id and then return the table and group that the put in. However, I have only found statements that are prone to SQL injection. Does anybody know how to fix this? mycursor = mydb.cursor() qry = "SELECT * from %s WHERE group_id = %i;" % (assembly_name, group_id) mycursor.execute(qry) return mycursor.fetchall() Or do something that achieves the same thing? -
Django-recurrence with Vuejs
I am using a django backend with a vuejs frontend and I am trying to get the django-recurrence form to work inside a vue template with no luck. I am trying to generate recurrences to send to the backend. Is there a way to make this work or would I need to create my own form just for generating the recurrence field?