Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting the django rest auth token value from local storage after refresh the page once in reactjs django rest application
I have made a application using react redux & django rest frame work.when i get the token after successful login, I save the token into local storage and dispatch the action as "AUTH_SUCCESS". Now i want to make a page accessible when it gets the Authentication token. But when i login it gets the token value from local storage after refresh page once manually .I am using react hook. So i use useEffect method like componentDidMount. But the result is same.is there any efficient way to solve this problem?Thank. -
django.db.utils.ProgrammingError: relation "postgres_po_db_view" already exists
am developing an api based on database view and am trying to a create a model for a postgres database view with managed=False option in class meta of model, and am connecting my model to the same database view via db_table parameter in the same class meta, here my database view name is "postgres_po_db_view" and am getting an error when ever am trying to run migrations for the corresponding model, please don't bother about the view or the model code, everything is good and working but my concern is when ever am trying to connect my model with my database view through class meta configuration inside the model class,when i migrated the very first time it is running smooth, and then after trying to run one more migration for another model or again trying to run the same command migrate am getting relation postgres_po_db_view already exists error...any useful lead is much appreciable..am unable to apply further migrations due to this error... here is my model: class ProductionOrderView(models.Model): class Meta: managed = False, ordering = '-creation_time', db_table = 'postgres_po_db_view' DRAFT = 'draft' PLANNING = 'planning' NOT_STARTED = 'not_started' IN_PROGRESS = 'in_progress' CANCELLED = 'cancelled' DONE = 'done' FAILED = 'failed' STATUS_CHOICES … -
Having difficulties getting navigation to work in Django
I am trying to get my navigation to work in Django This is what my about.html looks like <ul class="dropdown-menu"> <li class="nav-item"><a class="nav-link" href="{% url 'courses' %}">Courses</a></li> urls.py from django.contrib import admin from catalog import views from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('', views.about, name='about'), path('', views.courses, name='courses') ] and views.py from django.shortcuts import render #home page view def index(request): return render(request, "index.html") #about page def about(request): return render(request,"about-us.html") #courses page def courses(request): return render(courses, "courses.html") -
Full JSON Isn't Receiving on Django REST Framework Registration
I have a Django REST Registration page with two additional boxes (first_name and last_name). The registration page works fine when I use the input boxes but when I try to do a POST to the Register page, I constantly get that the form is invalid. Upon inspection, it looks like only the first_name and last_name are in the cleaned_data, but the JSON I am posting through Postman looks like: { "email": "test@test.com", "first_name": "test", "last_name": "test", "password1": "testtest", "password2": "testtest" } and it's not just Postman, I have also been trying the same thing in an Android app via Volley. I can't figure out why some of the JSON isn't going through. Here is my views.py for the Register page: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, models from userauth.templates.registration.forms import RegistrationForm from rest_framework.authtoken.models import Token from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework.decorators import api_view, renderer_classes from django.http import * def index(request): return render(request, 'userauth/index.html') @csrf_exempt def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) print(form.data) if form.is_valid(): print('form valid') form.save() username = form.cleaned_data['email'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) token = Token.objects.create(user=user) responseData = { 'token': … -
Celery cannot launch due to connections problem in Redis
when trying to launch a celery worker with this command celery worker --app=back I keep having this error and I have no clue about how to debug it, redis-cli is working fine but I can't find any solution. [2019-12-02 17:59:12,250: CRITICAL/MainProcess] Unrecoverable error: ResponseError("unknown command 'SREM'",) Traceback (most recent call last): File ".../site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File ".../site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File ".../site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File ".../site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File ".../site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File ".../site-packages/celery/worker/consumer/mingle.py", line 40, in start self.sync(c) File ".../site-packages/celery/worker/consumer/mingle.py", line 44, in sync replies = self.send_hello(c) File ".../site-packages/celery/worker/consumer/mingle.py", line 57, in send_hello replies = inspect.hello(c.hostname, our_revoked._data) or {} File ".../site-packages/celery/app/control.py", line 154, in hello return self._request('hello', from_node=from_node, revoked=revoked) File ".../site-packages/celery/app/control.py", line 106, in _request pattern=self.pattern, matcher=self.matcher, File ".../site-packages/celery/app/control.py", line 477, in broadcast limit, callback, channel=channel, File ".../site-packages/kombu/pidbox.py", line 352, in _broadcast channel=chan) File ".../site-packages/kombu/pidbox.py", line 396, in _collect chan.after_reply_message_received(queue.name) File ".../site-packages/kombu/transport/virtual/base.py", line 546, in after_reply_message_received self.queue_delete(queue) File ".../site-packages/kombu/transport/virtual/base.py", line 542, in queue_delete self._delete(queue, exchange, *meta, **kwargs) File ".../site-packages/kombu/transport/redis.py", line 818, in _delete queue or ''])) File ".../site-packages/redis/client.py", line 2008, in srem return self.execute_command('SREM', name, *values) File ".../site-packages/redis/client.py", line 839, in execute_command return self.parse_response(conn, … -
Django templates don't show my all parameters
I have problem. I want create relationship in model Django. I would like every user to have a different product price. The product must be assigned to the user. It must is to display only after logging in. Unfortunately, the template does not show all parameters. offers/models.py class Product(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.title class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.ForeignKey(Product, on_delete=models.DO_NOTHING) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) if self.user.username else '' Products are to be displayed for logged in users. offers/views.py def index(request): context = { 'products': Product.objects.order_by('category').filter(is_published=True) } return render(request, 'offers/products.html', context) def userproduct(request): context = { 'userproduct': UserProduct.objects.filter(user_id=request.user.id), 'userproduct1': Product.objects.all() } return render(request, 'offers/userproducts.html', context) My template show only title, and price. template.html <!-- Offers --> <section class="text-center mb-4 py-4"> <div class="container"> <div class="row"> {% if user.is_authenticated %} {% if userproduct %} {% for product in userproduct %} <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="{{ product.photo.url }}" class="card-img-top" alt=""> <a href="{% url 'product' product.id %}"> <div class="mask rgba-white-slight"></div> </a> </div> … -
Populate MultipleChoiceField values from ManyToManyField
I'm wanting to use my ManyToManyField in a form. I read that you should use a MultipleChoiceField for this. How can I populate the choices from my ManyToManyField? models.py class BoatModel(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(Category) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Models" def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=50) category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title forms.py class CreateModelForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'category',) widgets = { 'title': forms.TextInput(attrs={'class': 'category-title-field', 'placeholder': 'Category title'}), 'category': forms.MultipleChoiceField(), } -
Pipenv shell fails to create virtual environment in Python 3.8
I'm new to Django, and I'm starting a tutorial for Django with React, and I'm struggling with creating the virtual environment by using pipenv shell as per the tutorial's instructions. I have seen similar questions, but they have been either with another python version or the error is just different, and the answers haven't helped me. The error says the following: Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\cli\command.py", line 385, in shell [pipenv.exceptions.VirtualenvCreationException]: do_shell( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 2155, in do_shell [pipenv.exceptions.VirtualenvCreationException]: ensure_project( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 570, in ensure_project [pipenv.exceptions.VirtualenvCreationException]: ensure_virtualenv( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 505, in ensure_virtualenv [pipenv.exceptions.VirtualenvCreationException]: do_create_virtualenv( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 934, in do_create_virtualenv [pipenv.exceptions.VirtualenvCreationException]: raise exceptions.VirtualenvCreationException( [pipenv.exceptions.VirtualenvCreationException]: Traceb I reinstalled pip (19.3.1) and pipenv to be sure, with no change, and my environment variables are correct, I think, they are as follows: Variable (PYTHONPATH) -
Django model for unknown length list of integers
How can I model a list of integers in Django. The actual length of the list is not known. The maximal length should be validated. -
Call back a submit form in Django
I have this Form bellow: FORMS.PY class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] and in my template i have TEMPLATE ... <div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body"> {{ form.as_p }} </div> </div> ... I need to something like this <div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body"> {{ form.as_p }} <input class="btn btn-primary" type="submit" name="add_idioma" value="New" /> #if add_idioma is activate, the same form is called again #form.as_p </div> </div> How I do this? Is there some documentation? -
MySQL-Python failed to installl
when I tried pip install MySQL-Python it shows me following error Collecting MySQL-Python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-Python Building wheel for MySQL-Python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /var/www/vhosts/midelivery-mmsc.com/httpdocs/venv/bin/python2 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_SZ6Pz/MySQL-Python/setup.py'"'"'; file='"'"'/tmp/pip-install-_SZ6Pz/MySQL-Python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-qgLn8q --python-tag cp27 cwd: /tmp/pip-install-_SZ6Pz/MySQL-Python/ Complete output (34 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/mysql/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o In file included from _mysql.c:44:0: /usr/include/mysql/my_config.h:3:2: warning: #warning This file should not be included by clients, … -
Migrate django project to new version
I have project build on django 1.8 and python 2.7 . i want to migrate to django 3.0 and python 3.6.8.Is there automatic tool to do so? Easy way to do so, for someone who has only java experience but no python? Thank You -
Javascript getElementbyId.value not returning any value
I've got a problem with my Django project when implementing Javascript to it. This is my HTML: <td> <h5 id="precioSinEnv">{{total}}</h5> </td> This is my JS: function calcular() { var radios = document.getElementsByName('envio'); var pTotal = parseInt(document.getElementById('precioSinEnv').value); console.log(pTotal) if (radios[0].checked) { document.getElementById("precioTotal").innerHTML = pTotal + " €"; } if (radios[1].checked) { document.getElementById("precioTotal").innerHTML = pTotal + 10 + " €"; } if (radios[2].checked) { document.getElementById("precioTotal").innerHTML = pTotal + 4 + " €"; } } The main problem is that {{total}} is obtained as a parameter in views.py, and the value shows up in screen, but at the time of parsint it to int, it doesn't work. Any ideas on how to solve it? -
Django serving static files even with Debug off and no web server set to serve
Based on all I've read in the docs and on various s/o questions, Django cannot serve static files in production (when DEBUG = False) and they have to be served by a web server. Yet, when I run my code my static files are showing up just fine even with debug turned off. This concerns because as we move to production, I can't imagine it will continue to serve those files without me setting it up so they're served by a web server and I don't want my dev environment to not give me an accurate picture of how it will work in production. How is it possible that my app is serving static files without a web server with DEBUG = False? I've included the relevant blurbs in my settings.py file and my command to collectstatic in my Dockerfile. It also serves the static files just fine when I have RUN python manage.py collectstatic and STATIC_ROOT commented out. settings.py STAT = os.path.join(BASE_DIR, 'static') DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [STAT] STATIC_ROOT = os.path.join(BASE_DIR, 'prod_static') Dockerfile RUN python manage.py collectstatic --noinput -
How to make dynamically URLs with Django
my new project needs to fetch URLs from database. Example: Backend add Categorys and URLs should work like: www.example.com/hardware if I make in Backend a new subcategory: www.example.com/hardware/notebooks If I add a article: ww.example.com/hardware/notebooks/lenovo-e410 or articlenumbers. But I didnt find out where I can add urls from SQL Queries. -
Extract month or year from mongo Datetime filed in Django
im using monogengine in my Django project and i want count() number of jobs in each year and each month. after each time users do some jobs, it will insert and save in my Database nicely. now i want to count them and use this number later in some charts in year-month format. this is my model from mongoengine import Document, EmbeddedDocument, fields class PortModel(EmbeddedDocument): idx=fields.StringField() protocolname=fields.StringField() protocolnumber=fields.StringField() description=fields.StringField(required=False, blank=True) class PortScanModel(Document): date=fields.DateTimeField() host=fields.StringField() ip=fields.StringField() Ports=fields.ListField(fields.EmbeddedDocumentField(PortModel)) i want something like group_by just on year and month for counting rows and extract how much users used it. my Date field is something like '2019-12-02T19:47:31.847170' and i want something like below: year-month | number of rows --------------------------- 2018-01 | 2 2018-02 | 7 2019-01 | 3 2019-05 | 14 i searched a lot for extracting year and month from date, but nothing i found. i don't know can i Extracting and Grouping in one Command or not in mongo, but it wasn't hard in SQL. thanks for your helps. -
How to list wagtail pages in Django template?
I have a site that is mostly made with Django but has a few content pages that need to be managed by Wagtail. How can I link to the pages created with Wagtail in Django templates? I don't want to have to hardcode any of the pages. The client should be able to make a page in Wagtail and a link should be created to that page in Django templates. The problem is that I don't know how to reference Wagtail pages through Django templates. -
How to Validate and Compare Data against the Database in DetailView - Django
I have a ChallengeDetailView which shows the details of a challenge like a blog post. I also have a form field on the same page and it supposed to get an answer of a challenge, and compare it to the database. So far here is what I did; class ChallengeDetailView(DetailView): model = Challenge def get_context_data(self, **kwargs): context = super(ChallengeDetailView, self).get_context_data(**kwargs) context['form'] = FlagForm return context class FlagFormView(): form_class = FlagForm success_url = reverse_lazy('challenge-detail') I try to implement a simple logic like the following; def get_flag(self, request): if self.request.method == 'POST': form = FlagForm(request.POST) if form.is_valid(): flag = form.cleaned_data.get('flag') if flag == Challenge.flag: return messages.success("You found the flag!") else: return FlagForm() I tried to include this in form_valid() method but couldn't make it work in the ChallengeDetailView. I'm open to any kind of suggestions. I'm coming from a Symfony background and pretty new to Django. -
Django model field for file system directory path
In the Django model field types reference I could not find a field for a file system directory path. With custom model fields it's possible to implement this. What should be considered w.r.t. validation? Can I extend Django's builtin model field types with a package? -
Django with cms model
hi i'm making a cms in django. I want users to be able to create pages from the admin panel. My model is like this, page properties -> designs on page -> data of designs. but I am doing too much database operation how do I optimize. I've reviewed Wordpress. I didn't quite get it. # Create your Page Models. class Page(models.Model): ID = models.BigAutoField(primary_key=True) page_title=models.TextField() page_contentmeta = models.ManyToManyField("ContentMeta") page_icon=models.ImageField() page_status=models.BooleanField(default=True) def __str__(self): return self.page_title class Content(models.Model): ID = models.BigAutoField(primary_key=True) name=models.CharField(max_length=500, blank=True, null=True) content=models.CharField(max_length=500, blank=True, null=True) image=models.ImageField(blank=True, null=True) def __str__(self): return self.name class ContentMeta(models.Model): ID = models.BigAutoField(primary_key=True) template=models.CharField(max_length=50) name=models.CharField(max_length=50) content = models.ManyToManyField("Content") def __str__(self): return self.template index.html template=Page model page->contentmeta->content {% extends 'base.html' %} {% block body %} {% for templates in template.page_contentmeta.all %} {{templates.template}} {% include templates.template %} {%endfor%} {%endblock%} Banner.html -->{{template|asd:"banner1,3"}} asd=template filter Banner1= content.name 3=contentmeta_name <section style="background: url(); background-size: cover; background-position: center center" class="hero"> <div class="container"> <div class="row"> <div class="col-lg-7"> <h1></h1><a href="#" class="hero-link">{{template|asd:"banner1,3"}}</a> </div> </div><a href=".intro" class="continue link-scroll"><i class="fa fa-long-arrow-down"></i> Scroll Down</a> </div> </section> template filter @register.filter("asd") def asd(value,args): first, second = args.split(',') return value.page_contentmeta.get(name=int(second)).content.get(name=first).content -
New to Django, mod_wsgi won't install
I am new to Django and have been making a portal to make access to a database easier. We are currently at the deployment stage and so tried configuring our apache server to host it using mod_wsgi. Immediately we ran into problems installing mod_wsgi using pip, with a little research we found it is important to make sure the root directory is set appropriately. Seeing as our apache server is distributed with xampp it looks like the correct folder is C:\xampp\htdocs, so we set that using 'set MOD_WSGI_APACHE_ROOTDIR=...' and got this error: C:\Users\administrator>set "MOD_WSGI_APACHE_ROOTDIR=C:/xampp/htdocs" C:\Users\administrator>pip install mod_wsgi Collecting mod_wsgi Using cached https://files.pythonhosted.org/packages/25/d8/1df4ba9c051cd88e02971814f0867274a8ac821baf98 3b6778dacd6e31f7/mod_wsgi-4.6.8.tar.gz Installing collected packages: mod-wsgi Running setup.py install for mod-wsgi ... error ERROR: Command errored out with exit status 1: command: 'c:\users\administrator\appdata\local\programs\python\python37\python.exe' -u -c 'import sy s, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-install-aum 8dfd1\\mod-wsgi\\setup.py'"'"'; __file__='"'"'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\pip-install-a um8dfd1\\mod-wsgi\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replac e('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-record-u1d5t3mo\install-record.txt' --single-version-externa lly-managed --compile cwd: C:\Users\ADMINI~1\AppData\Local\Temp\2\pip-install-aum8dfd1\mod-wsgi\ Complete output (33 lines): c:\users\administrator\appdata\local\programs\python\python37\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\mod_wsgi copying src\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi creating build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\apxs_config.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\environ.py -> build\lib.win-amd64-3.7\mod_wsgi\server copying src\server\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server creating build\lib.win-amd64-3.7\mod_wsgi\server\management copying src\server\management\__init__.py -> build\lib.win-amd64-3.7\mod_wsgi\server\management creating build\lib.win-amd64-3.7\mod_wsgi\server\management\commands … -
Whats the logic of importing models as `app_registry.get_model('app_name', 'ModelName')` in a custom migration
I am asking this question because I ran into this django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint when I was using django-hordak which uses MPPT models. The solution provided is hacky as it violates the common practice but it works. THE BASICS In django when writing custom migrations for example when creating baseline data. def forward_func(apps_registry, schema_editor): Model = apps_registry.get_model('app_name', 'ModelName') Model.objects.create(**{'field_1': 'field_1', 'field_2': 'field_2') # Do whatever you want with my Model In my situation django-hordak with the account model. That .objects.create(**data) raises theIntegrityError on the DB as specified above. Proposed solution The proposed solution is to import the model directly. def forward_func(apps_registry, schema_editor): # Model = apps_registry.get_model('app_name', 'ModelName') # lets forget about importing the standard way because it will raise integrity error. from app_name.models import ModelName as Model # Now we can proceed to deal with our model without Integrity Error. Model.objects.create(**data) This leaves me scared of possible undesirable side effects of importing models directly in migrations files. As there must be very good reasons why the model is not imported that way in the migration files. I am not looking for the reason why MPTT models fail when imported the standard way as that question … -
Using Checkbox in ListView
I'm trying to make Todo app. I want to make checkbox next to task, so when you select it, the task is set to done. The problem is, I can't really know how to change value of my BooleanField in Task Model. There are plenty of posts like this, but they are usually using functions inside views.py or use forms, but I can't relate do my form in ListView. views.py class TodolistView(LoginRequiredMixin, ListView): model = Todolist template_name = 'todolist.html' def get_queryset(self): return Todolist.objects.all().filter(user=self.request.user) def get(self, request, *args, **kwargs): todolist_objects = Todolist.objects.all() return render(request, 'todolist.html', {'todolist_objects': todolist_objects}) todolist.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <p><a href="{% url 'todolist_create' %}">Add new task</a></p> {% for todo in todolist_objects %} <div> <form action="" method="post"> <li> {{ todo }} <a href="{% url 'todolist_detail' todo.pk %}">see details</a></l> </form> </div> {% endfor %} {% endblock %} -
How can i know which button was clicked and get its value in my view
Search.py {% block search %} <form action="#" method="post"> <div class="container"> <br> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" name="bankname" type="submit" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Name </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for key , value in data_dict.items %} <a class="dropdown-item" value=key name="name" href="{% url 'details' %}">{{ key}} </a> {% endfor %} </div> </div> </form> {%endblock%} the number of items in data_dict is not always same , so some times it has 2 or 3 or even 10 different names which leads to 10 items in the drop down. I need to show details of the name clicked in the drop down in details .html Views.py def details(request ): request.GET('name') data_dict = request.session.get("data_dict") context = {"data_dict" : data_dict} return render(request , "details.html", context ) i want the value of the tab clicked in the drop-down in my view so i can display the details accordingly from my data_dict -
How to add new field or list to django queryset Object and output json as result without Django Rest Framework
I want to use Django as rest-API (that too without Django RestFramework) and also Django for rendering data to the template. Let me explain in-detail I have a single project when a user from website requests with header content-type as text/plain. I'll return Queryset Objects of the related model and when the request comes from mobile app header content-type will application/json than will send queryset data as JSON. I have accomplished this through Laravel Framework and wanted to the same in Django framework. While working I'm facing some of the below problems. I want to return JSON Data if header Content-Type is application/json. If not then return template with queryset. if request.META['CONTENT_TYPE'] == 'application/json': json = serializers.serialize('json', blogs) return HttpResponse(json) else: return render(request, template_path, context) I want to add field or dictionary or list to Queryset objects manually and send the response as JSON I have Tried below and it did not work for me. from blogs.models import BlogModel def json_1(request): blogs = BlogModel.objects.all()[0:5] for blog in blogs: blog.custom_field = 100 #`custom_field` is not show in json output blog.custom_dictionary = { "name" : "pavan" } #`custom_dictionary` is not show in json output json = serializers.serialize('json', blogs) return HttpResponse(json) Json Output …