Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django check if any attr matches in a query
I have a "search" form, which searches for objects from my DB. This form has two fields, a Select (ChoiceField) where users can select which attribute they are searching by, and a text field they can fill. For example I can select "Search by name", and I type "Matt", so it will search for value "Matt" on column "name". Also I can search by other attrs. Everything work fine until here. The problem comes when I try to use my last search option, "Search by any coincidence", which should query for a match in any of the columns. forms.py: class BuscarAuxi(forms.Form): busqPor = forms.ChoiceField( required=False, widget=forms.Select, choices=SEARCH_AUXI, ) criterio = forms.CharField(max_length=100) busqPor.widget.attrs.update({'class': 'form-control'}) criterio.widget.attrs.update({'class': 'form-control col-7 m-2', 'placeholder': 'Criterio'}) views.py: def crudAuxi(request): if request.method == "GET": form = BuscarAuxi(request.GET) print('Entra a GET de BuscarAuxi. ') print(form.errors) if form.is_valid(): print('El formulario GET de BuscarAuxi fue válido. ') print(form.cleaned_data.get('busqPor')) critBusqueda = form.cleaned_data.get('criterio') tipoBusqueda = form.cleaned_data.get('busqPor') if tipoBusqueda == '1': try: busqueda = Auxi.objects.get(denom=critBusqueda) if busqueda: print('Encontró por nombre. ') except ObjectDoesNotExist: print('No se encontró por criterio nombre. ') if tipoBusqueda == '2': try: busqueda = Auxi.objects.get(nroDoc=critBusqueda) if busqueda: print('Encontró por DNI. ') except ObjectDoesNotExist: print('No se encontró por criterio DNI. ') if … -
How to test a `admin.site.login` changing in the middle of a test
I'm using a global setting to optionally change the admin.site.login value in an admin.py within my app: if settings.DJANGO_ADMIN_FORCE_ALLAUTH: # Enforce /admin to go through django-allauth for login admin.site.login = decorators.login_required(admin.site.login) And I'm testing as follows: import sys from importlib import reload from django.test import LiveServerTestCase, override_settings from django.urls import reverse from django.contrib.admin import sites from selenium.webdriver.firefox.webdriver import WebDriver class AdminTestCase(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() @override_settings(DJANGO_ADMIN_FORCE_ALLAUTH=False) def test_admin_allauth_workflow_disabled(self): # This raises an expected `AlreadyRegistered` error try: reload(sys.modules['my_app.users.admin']) except sites.AlreadyRegistered: pass self.selenium.get(f'{self.live_server_url}{reverse("admin:index")}') self.assertEqual(self.selenium.current_url, f'{self.live_server_url}{reverse("admin:login")}?next={reverse("admin:index")}') @override_settings(DJANGO_ADMIN_FORCE_ALLAUTH=True) def test_admin_allauth_workflow_enabled(self): # This raises an expected `AlreadyRegistered` error try: reload(sys.modules[my_app.users.admin']) except sites.AlreadyRegistered: pass self.selenium.get(f'{self.live_server_url}{reverse("admin:index")}') self.assertEqual(self.selenium.current_url, f'{self.live_server_url}{reverse("admin:login")}?next={reverse("admin:index")}') I'm only using selenium so I can see the output myself, it's really not necessary for this test. I'm forcefully reloading the admin module so that my optional code gets called when I override the settings, but the admin.site.login is still returning the same. Right now, test_admin_allauth_workflow_disabled works and test_admin_allauth_workflow_enabled shouldn't work (since they're identical just with a changed setting), but they both work. What else do I need to reload in order for the admin.site.login value to be updated? If I put my settings in separate files, or separate … -
how to fix "generator object cannot be interpreted as an integer
i am trying to create a cart for a shop. when trying to extend the shop base.html file i receive an error saying "generator object cannot be interpreted as an integer" on line 37 where the for loop begins. Also the form is not being displayed.This form is used to specify the quantity of projects the customer wants to purchase here is my cart detail.html template {% extends 'gallery/Base.html' %} {% load static %} {% block title %} Your Shopping Cart {% endblock %} {% block content %} <div class="container"> <div class="row" style="margin-top: 6%"> <h2>Your Shopping Cart <span class="badge pull-right"> {% with totail_items=cart|length %} {% if cart|length > 0 %} My Shopping Order: <a href="{% url "cart:cart_detail" %}" style="color: #ffffff"> {{ totail_items }} item {{ totail_items|pluralize }}, Kshs. {{ cart.get_total_price }} </a> {% else %} Your cart is empty. {% endif %} {% endwith %} </span> </h2> <table class="table table-striped table-hover"> <thead style="background-color: #5AC8FA"> <tr> <th>Image</th> <th>Product</th> <th>Quantity</th> <th>Remove</th> <th>Unit Price</th> <th>Price</th> </tr> </thead> <tbody> {% for item in cart %} {% with product=item.product %} <tr> <td> <a href="{{ product.get_absolute_url }}"> <img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/default.jpg' %} {% endif %}" alt="..." … -
Deploying gunicorn with upstart, thwarted by import error
I'm trying to configure gunicorn 19.9.0 (Ubuntu 14.04) with upstart, but I keep getting an import error in /var/log/upstart/gunicorn.log. The error is ImportError: cannot import name Celery. However, this module is installed in my virtualenv. E.g. if type celery when myenv is activated, I get the module's usage help. Hence there's this possibility that gunicorn.conf is not being run from inside the correct virtual env. That's perplexing because I've triple checked my config - I believe the error is elsewhere. Here's the config: description "Gunicorn application server handling my server" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/myapp/myproj/ exec /home/ubuntu/.virtualenvs/myenv/bin/gunicorn --chdir=/home/ubuntu/myapp/ -w 3 --timeout 60 --bind unix:/home/ubuntu/myapp/myproj/myproj.sock myproj.wsgi:application The traceback produced in /var/log/upstart/gunicorn.log is as follows: [2019-01-31 13:16:16 +0000] [5898] [INFO] Booting worker with pid: 5898 [2019-01-31 13:16:16 +0000] [5898] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/.virtualenvs/myenv/local/lib/python2.7/site-packages/gunicorn/util.py", line 350, in … -
Django uwsgi.ini file
So i've got problem , when writting text it wont save in base because of the error : invalid request block size: 4791 (max 4096)...skip i googled it and i guess problem is that i should increase buffer-size but i dont get where should i find this uwsgi.ini file , i searchd whole my folders there is nothing like this . am i missing something ? somewhere i also read that this file is not exists i manually should create it so, i did not get it can anyone help ? -
Architecture of a CBV with the ability to optionally load blocks with AJAX
I have a view that reponds with a very large response. Many templates involved, many variables, a lot of data, a lot of JS code to be executed. I have tried optimizing templates and queries the best I could but I feel I have reached a limit. The loading time is acceptable for smaller objects, but when bigger ones are involved it gets very bad. Therefore I have thought about using pagination and the like. My question is about the architecture of the CBV to implement optional AJAX handling. Let me explain: The idea is to set up the view and the most relevant templates or slower blocks so that when the object is too big, the block is requested asynchronously instead of including it in the main request: some_template.html <div id="content-a"> {% if object.is_big %} <script> $(function () { $.get(contentAURL, function (data) { $('#content-a').html(data); }); }); </script> {% else %} {% include 'content-a-template.html' %} {% endif %} </div> And in the view we would fetch the necessary data depending on what we need: # this would be the main CBV def get_context_data(self, *args, **kwargs): context = super(ScheduleMakerView, self).get_context_data(**kwargs) if not self.object.is_big: context['content-a-related'] = self.object.content_a.select_related().prefetch_related('users') # etc... So when the … -
How do I convert a string, represented as a list in MySQL database to a list in Django Template, so that I can iterate over it?
I have stored a list of mailing addresses in the MySQL database like ['1212 Los Angeles, CA', 'Nariman Point, Mumbai, India']. I expect to print each element of the list in my HTML template. Unfortunately, each character is being printed. Now, when I try to iterate over the list, in the Django template, I get each character instead of each list element. I have tried the Django library, django-mysql to implement native JSONField. Tried building a list in Django template, using in-built template filters, with, cycle, as list, among others. ` <div class="container"> {% if my_requests_queryset and my_requests_queryset|length > 0 %} {% for req in my_requests_queryset %} <div class="row mb-1"> <div class="col-lg-2"></div> <div class="col-lg-8"> <a href="#" class="card-link"> <div class="card text-center"> <div class="card-header"> {{ req.title|title|truncatechars:36 }} </div> <div class="card-body"> <h5 class="card-title"> {% for address in req.locations %} {{ address }} {% endfor %} </h5> </div> </div> </a> </div> </div> {% endfor %} {% endif %} </div>` I expect to print each element in a list as: 1212 Los Angeles, CA Nariman Point, Mumbai, India -
Override form field validation django
I have a Device for which many Scans are associated and are created via a form. class Device(models.Model): uuid = models.UUIDField(primary_key=True, verbose_name="UUID") # fields omitted for brevity class Scan(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) When a Scan is submitted via form, the UUID of the Device is included in the POST data. If the UUID exists, the Scan will be associated with the existing Device, otherwise a new Device will be created and the Scan associated with that. I am using generic forms: class DeviceForm(ModelForm): class Meta: model = Device class ScanForm(ModelForm): class Meta: model = Scan The view in question is this: @login_required def scan_test(request): if request.method == 'GET': device_form = DeviceForm() scan_form = ScanForm() # otherwise create a form instance and populate it with request data: elif request.method == 'POST': device_form = DeviceForm(request.POST) scan_form = ScanForm(request.POST, request.FILES) # is_valid is determining that UUID is not unique if device_form.is_valid() and scan_form.is_valid(): form_data = device_form.cleaned_data try: device = Device.objects.get(uuid=form_data['uuid']) except Device.DoesNotExist: device = Device( uuid=form_data['uuid'], ) device.save() scan = Scan(device=device, data=scan_form.cleaned_data['data']) scan.save() return HttpResponseRedirect(device.get_absolute_url()) return render(request, 'app/scan_form.html', {'device_form': device_form, 'scan_form': scan_form}) Creation of a new Device and associated Scan works OK. However when trying to submit with an existing Device … -
How to fix "image not being saved into my database(i.e image model field)"?
I am building a Portfolio web app with Django. I am unable to save an image into my database in my web app. Also, to replace an existing image in the database does not work. Note: I don't get any error message from Django. The web app will tell me no file being added. On the Django Admin section(Django site administration page "localhost:8000/admin" I am able to add a new image and change an existing one. How can I enable this functionality without going to django admin section. Here's my code views.py: from django.views.generic.edit import CreateView, UpdateView from django.urls import reverse_lazy from .models import Jobs class JobsCreateView(CreateView): model = Jobs fields = ['image'] template_name = "new_job.html" class JobsUpdateView(UpdateView): model = Jobs fields = ['image'] template_name = "change_job.html" success_url = reverse_lazy('home') models.py: from django.db import models from django.urls import reverse class Jobs(models.Model): image = models.ImageField(upload_to="images/") upload_date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('home', args=[str(self.id)]) If you need any additional information from me, please let me know or you can see the complete code of this project here -
List of users with first record for each user
class Contract(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) contract_start = models.DateField(null = True, blank = True) contract_end = models.DateField(null = True, blank = True) How would I go about getting the first contract belonging to each user? The current contract I have working with: active_contract = Contract.objects.select_related('user').filter(contract_start__lte=date_today, contract_end__gte=date_today) But for the life of me I can't find the way to filter correctly to get the first contract (contract_start)from each user. -
Django: Session_Cookie_Age
Assuming I set request.session['discount'] = discount_code and Session_Cookie_Age is set to two weeks. Is the session discount always renewed whenever I reload the page for another two weeks? Or can I set expiry dates individually? -
how to validate django-recaptcha with ajax form in django
I have a small contact form that is submitted via ajax. I added a recaptcha using the django-recaptcha module. When the form is validated it looks like the captcha field is missing. How can I validate the captcha-field manually? Or is the JS in message.html submitting the wrong field? forms.py from django import forms from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV2Checkbox from .models import Message class MessageForm(forms.ModelForm): """docstring for MessageForm.""" captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) class Meta: model = Message fields = ['name', 'from_email', 'message', 'captcha'] views.py from django.shortcuts import render, redirect from .forms import MessageForm def messageView(request): if request.method == 'POST' and request.is_ajax: form = MessageForm(request.POST) if form.is_valid(): message = form.save() form = MessageForm() else: print('form not valid') return render(request, 'contact/message.html', {'form': form}) else: form = MessageForm() return render(request, 'contact/message.html', {'form': form}) message.html {% load crispy_forms_tags %} <div class="form-container"> <form class="message-form" method="post" action=""> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit" name="button" class="btn btn-primary">Send</button> </div> </form> </div> <script> $(document).ready(function() { $('.message-form').on('submit', function(event) { event.preventDefault(); return create_message(); }); function create_message() { $.ajax({ url: 'contact/message/', type: 'POST', data: {name: $('#id_name').val(), from_email: $('#id_from_email').val(), message: $('#id_message').val(), captcha: $('#g-recaptcha-response').val(), csrfmiddlewaretoken: '{{csrf_token}}' }, success: function(json) { $('.form-container').html(json) } }) }; }); </script> -
Is there a way to print dictionary keys and respective list of values on my django based app?
Can Anyone answer this, This is my maketest.html Iam trying to print a dictionary with keys and respective list of values, Is there a module or a backend or function in django that can perform something like this? Is there a solution to this problem in python? {% extends 'TakeTestApp/base.html' %} {% block content %} <h3 class="display-6">{{ TestName }}</h3> <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <p class="display-6"> {% for q in quesBank %} {{ q }} {{ quesBank[q] }} {% endfor %} </p> </div> </div> </article> {% endblock content%} This is my ques.txt, Q: What is your name? opt1:Vineeth* opt2:Vineth opt3:Vinith opt4:Vinth Q: Where are u from? opt1:Hyderabad opt2:Secunderabad* opt3:Rajasthan opt4:vizag Q: What is the capital of india? opt1:* Delhi opt2: Telangana opt3: Madhya Pradesh opt4: Gujrat Q: What is 2+1? opt1: 0 opt2: 1 opt3:* 3 opt4: 6 Q: Python is a _____ language opt1: Markup opt2: not opt3:* programming opt4: English and my views.py is from django.shortcuts import render, redirect from Test.forms import TestForm # Create your views here. def MakeTest(request): file1 = open('ques.txt', 'r') lines = file1.readlines() file1.close() ques = [] options = [] ans = [] for line in lines: if "Q:" in line: ques.append(line) … -
Django - order on @property gives "no such column"
I want to order a list based on a model property class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def client_orders(self): return len(Orders.objects.filter(client=self.user.email)) Then, to order my list of clients orders: clients = sorted(Client.object.all(), key=lambda c: c.client_orders) It gives me this error: django.db.utils.OperationalError: no such column: accounts_client.client_orders All my migrations are done. What am I missing there? -
I can't do delete button to run delete() in db query in django. Help anything does not work
I can't do delete button in django_tables2. I think i try everything from google and does not work :/ i try generic views and another and nothing. In python script this work, but in the view of app not. Could you watch my code and tell me what i did wrong? urls.py from django.conf.urls import url from . import views app_name = 'carslist' urlpatterns = [ url('', views.carslist, name='carslist'), url(r'^delete-entry/(?P<pk>\.*)/$', views.DeleteView.as_view(), name='delete_view'), ] views.py def carslist(request): fleets = Fleet.objects.all() fleetTable = FleetTable(fleets, prefix='u_') RequestConfig(request, paginate=False).configure(fleetTable) payload = { 'fleetTable': fleetTable, } return render(request, 'carslist/car-list.html', payload) class DeleteView(SuccessMessageMixin, DeleteView): model = Fleet success_url = '/' success_message = "deleted..." def delete(self, request, *args, **kwargs): self.object = self.get_object() id = self.object.id request.session['id'] = id # name will be change according to your need message = request.session['id'] + ' deleted successfully' messages.success(self.request, message) return super(DeleteView, self).delete(request, *args, **kwargs) I try with code like: def delete(request, record_id): row = Fleet.objects.filter(id=record_id) row.delete() and doesnt work too :( tables.py import django_tables2 as tables from django_tables2 import TemplateColumn from regcar.models import Car, Brand, Fleet class FleetTable(tables.Table): producent = tables.Column(accessor='car.brand', verbose_name='Producent') class Meta: model = Fleet attrs = {'class': 'table table-sm'} sequence = ('id', 'producent', 'car', 'rok_produkcji', 'rodzaj_paliwa', 'pojemność_silnika_w_cm3', … -
Display message in admin panel when file already exists
My problem is how I can display a message in admin django (v 1.11) about the fact that the file that wants to put in the application exists. I have already written the code, but it works only in the model, i.e. in the console you can see that ValidationError appears. class ImageModel(BaseImageModel): desc = models.CharField(max_length=256, null=True, blank=True) def save(self, *args, **kwargs): self.has_all_mandatory_data = self._check_validity() if ImageModel.objects.filter(original_filename=self.file).exists(): raise ValidationError('This image already exists.') super(ImageModel, self).save(*args, **kwargs) How to show in admin messages.INFO("File already exists") instead of ValidationError? -
Django haystack woosh Zappa?
how to implement Django whoosh haystack with Zappa ? . How to create index and update it on aws lambda ? . When I run my view with haystack it is giving a write permission . Can someone guide me in this ? -
How to get two querysets in List View
I have 2 question models extending the base Question model: class Question(models.Model): title = models.CharField(blank=False, max_length=200) order = models.PositiveIntegerField(default = 0) is_actuve = models.BooleanField(default = False) class OptionQuestion(Question): is_bulletpoint = models.BooleanField(default=False) has_others = models.BooleanField(default=False) has_context = models.BooleanField(default=False) options = ArrayField(models.CharField(max_length=100), verbose_name='گزینهها') class ItemQuestion(Question): pass I originally had the Question class abstract but i needed a unique id across all questions, and now i am in need of a ListAPIView for both of them. I have 2 serializers for OptionQuestion and ItemQuestion respectively. I just need to implement a view which would handle a request for a list of questions and handling them with the proper serializer each. class QuestionListView(ListAPIView): serializer_class_OptionQuestion = OptionQuestionSerializer serializer_class_ItemQuestion = ItemQuestionSerializer def get_queryset_OptionQuestion(self): #??? -
Wizard django 2.1 : __init__() takes 1 positional argument but 2 were given
I use Django 2.1, I installed form tools, and I used the wizard module, the goal is to create a stepbystep page with several forms. I dont know if I have to change something, but I already lookup on other post, but unfortunatly I didnt solve my problem. forms.py from django import forms class FormStepOne(forms.Form): name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) phone = forms. CharField(max_length=100) email = forms.EmailField() class FormStepTwo(forms.Form): job = forms.CharField(max_length=100) salary = forms.CharField(max_length=100) job_description = forms.CharField(widget=forms.Textarea) views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .forms import FormStepOne, FormStepTwo from formtools.wizard.views import SessionWizardView @login_required class FormWizard(SessionWizardView): template_name = "createproject.html" form_list = [FormStepOne, FormStepTwo] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py from django.urls import path from . import views from dashboard.views import FormWizard urlpatterns = [ path('', views.dashboard, name='dashboard-home'), path('createproject/', views.FormWizard, name='dashboard-createproject'), ] I have this error : TypeError at /dashboard/createproject/ __init__() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost:8000/dashboard/createproject/ Django Version: 2.1.4 Exception Type: TypeError Exception Value: __init__() takes 1 positional argument but 2 were given Exception Location: /home/user/Desktop/venv/lib/python3.6/site-packages/django/contrib/auth/decorators.py in _wrapped_view, line 21 Python Executable: /home/user/Desktop/venv/bin/python Python Version: 3.6.7 Python Path: … -
How to count total objects of a database table in django?
My question is about django app, i have one app in one model in class employee ,i want to display how many employee register in fronted side in template. In below app user count is successfully worked. I want output like 4 employee register from template form and in template display 4 Employee registered at frontside views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm,AuthenticationForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django_adminlte.forms import EmployeeForm from django_adminlte.models import Employee def emp(request): if request.method == "POST": form = EmployeeForm (request.POST) # here "form" is one varible if form.is_valid(): try: form.save() return redirect("/show") except: pass else: form = EmployeeForm() return render(request,"employee/employee_index.html",{'form':form}) #i want like this below code(this code is working for count user in front side) def home(request): count = User.objects.count() return render(request,'index.html',{ 'count' : count }) model.py from django.db import models class Employee(models.Model): eid = models.CharField(max_length=20) ename = models.CharField(max_length=20) eemail = models.EmailField() econtact = models.CharField(max_length=15) class Meta: db_table = "employee" def __str__(self): return self.ename HTML Template {% extends 'adminlte/base.html' %} {% block content %} <div class="col-lg-3 col-xs-6"> <!-- small box --> <div class="small-box bg-yellow"> <div class="inner"> <h3>{{ count }}</h3> <p>User Registrations</p> </div> <div class="icon"> <i class="fas fa-user-plus"></i> </div> <a … -
How to see exceptions raised from a channels consumer
I begin to use django-channels and I find it fantastic. However debugging consumers is painful because when an exception is raised from inside a consumer, nothing is printed to the terminal, the websocket is simply disconnected. Is there a way to see those exceptions as any other ones? -
raise ValueError when enum class field is changed
Enum Class class QuestionValidationTag(Enum): FREE_TEXT = "Free text" model validation_tag = models.CharField(choices=[(tag.value, tag) for tag in QuestionValidationTag], null=True, max_length=200) I have change the enum FREE_TEXT class QuestionValidationTag(Enum): FREE_TEXT = "make free text" after that I have tried to run my application and raise Value Error. As well as I also try to run python manage.py makemigrations (though it's not needed as my understanding). But this also gives me the error. raise ValueError("%r is not a valid %s" % (value, cls.name)) ValueError: 'Free text' is not a valid QuestionValidationTag is there any suggestion how I resolve this issue? -
Pass dictionary data to another view
How to pass the dictionary to another view of another app? I have a view 1 of app_1 : def index(request): if request.method=='POST': formConnex =ConnexionForm(request.POST) if formConnex.is_valid(): nom_utilisateur = formConnex.cleaned_data['nom_utilisateur'] dicInfoCon = { 'utilisateur_key':nom_utilisateur, } return redirect('/app_1/', {'user_key':nom_utilisateur}) In view 2 of app_2: def index(request): return render(request, 'app_2/index.html') -
'NoneType' object has no attribute '_meta'
I am trying to build register api. Here i am stuck with the problem and hoping you guys will address my mistake and will lead me to right way. Anyway thanks in advance. Hoping for your soon response. Thank you . serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): """ Create and return a new user""" user = User.objects.create_user(**validated_data) return user models.py from django.db import models from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager from django.contrib.auth import get_user_model class UserRegisterManager(BaseUserManager): """ Helps django work with our custom user model """ def createUser(self, email, name, password=None): """ Creates a new user profile object """ if not email: raise ValueError("User must have an email address.") email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) # set_password helps to convert str into hash user.save(using=self._db) return user def create_superuser(self, email, name, password): """ Creates and saves a new superuser with given details. """ user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserRegister(AbstractBaseUser, PermissionsMixin): """ Represents a 'user register' inside our system """ … -
FieldError at /students/delete_gr/234/
FieldError at /students/delete_gr/234/ i am trying to delete gr its not working giving an error Cannot resolve keyword 'id' into field. Choices are: address, area_code, area_code_id, class_register, classes_A, classes_A_id, classes_C, classes_C_id, date_birth, fee, first_name, gardian, gender, gr_no, last_name, sections_A, sections_A_id, sections_C, sections_C_id, status views.py def delete_gr(request, pk): gr_register.objects.filter(id=pk).delete() gr = gr_register.objects.all() context = { 'gr' : gr } return render(request, 'students/home.html', context) viewdata.html {% extends 'authenticate/base.html' %} {% block content %} <div class="container"> <h2 class="text-center" style="font-family:sans-serif;">GR-Record</h2> <hr/> <div class="addgr text-right" style="margin-bottom: -50px;"> <button class="btn btn-dark" type="submit"><a href="{% url 'addgrregister' %}">Add-GR Register</a></button> </div> <form class="form-inline my-2 my-lg-2"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" value="{{search_term}}"> <button class="btn btn-outline-dark my-2 my-sm-0" type="submit">Search</button> </form> <br/> <div class="table-responsive "> <table class="table table-hover table-dark table-bordered table-sm"> <caption>List of GR-students</caption> <thead> <tr> <th>GR No</th> <th>First Name</th> <th>Last Name</th> <th>Date Of Birth</th> <th>Class Of Admission</th> <th>Section Of Admission</th> <th>Gender</th> <th>Current Class</th> <th>Current Section</th> <th>Address</th> <th>Area Code</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for gr in gr %} <tr> <td>{{gr.gr_no}}</td> <td>{{gr.first_name}}</td> <td>{{gr.last_name}}</td> <td>{{gr.date_birth}}</td> <td>{{gr.classes_A}}</td> <td>{{gr.sections_A}}</td> <td>{{gr.gender}}</td> <td>{{gr.classes_C}}</td> <td>{{gr.sections_C}}</td> <td>{{gr.address}}</td> <td>{{gr.area_code}}</td> <td>{{gr.status}}</td> <td> <a href="{% url 'editgr' gr.pk %}" class="btn btn-warning btn-sm" role="button"> Edit</a><br/> <a href="{% url 'delete_gr' gr.pk %}" class="btn btn-danger btn-sm" role="button"> Delete</a> </td> </tr> {%endfor%} </tbody> …