Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "<SimpleLazyObject
class ProductDetailSlugview(ObjectViewedMixin, DetailView): queryset = Product.objects.all() template_name = "products/product_detail.html" def get_context_data(self, *args, **kwargs): context=super(ProductDetailSlugview, self).get_context_data(*args , **kwargs) cart_object, new_object = Cart.objects.new_or_get(self.request) context['cart']=cart_object return context this is my view ValueError at /product/list/blackberry Cannot assign ">": "ObjectViewed.user" must be a "User" instance. Request Method: GET Request URL: http://127.0.0.1:8000/product/list/blackberry Django Version: 2.1.3 Exception Type: ValueError Exception Value: Cannot assign ">": "ObjectViewed.user" must be a "User" instance. Exception Location: /home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in set, line 210 Python Executable: /home/wiwigi/Desktop/django-virtual/bin/python3 Python Version: 3.6.5 Python Path: ['/home/wiwigi/Desktop/ecommerce_sample', '/home/wiwigi/Desktop/ecommerce_sample', '/home/wiwigi/Desktop/django-virtual/lib/python36.zip', '/home/wiwigi/Desktop/django-virtual/lib/python3.6', '/home/wiwigi/Desktop/django-virtual/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages', '/home/wiwigi/pycharm-2018.1.2/helpers/pycharm_matplotlib_backend'] Server time: mar, 26 Fév 2019 11:31:14 +0000 and my error code please help me -
Adding a Recaptcha form to my Django login page
I'd like to add Recaptcha to my login form. I'm following this repository but i'm having some problems: i added this to my views.py: from django import forms from captcha.fields import ReCaptchaField class FormWithCaptcha(forms.Form): captcha = ReCaptchaField() But i don't really know where to go from here. I suppose i need to add something to my login.html page but i don't know what. Can anyone give me some help? Note that i already added my public and private keys to my settings.py file. -
Django oscar Api is not setting status in OSCAR_ORDER_STATUS_PIPELINE
I am using django oscar API, and my question is on creating an order using the /checkout/ api method, the order is created but the status is not taken from my OSCAR_ORDER_STATUS_PIPELINE it just sets it to 'new'. In my settings.py file: OSCAR_INITIAL_ORDER_STATUS = 'Pending' OSCAR_INITIAL_LINE_STATUS = 'Pending' OSCAR_ORDER_STATUS_PIPELINE = { 'Pending': ('Processing', 'Cancelled',), 'Processing': ('Shipped', 'Cancelled',), 'Shipped': ('Delivered', 'Returned', 'Cancelled',), 'Returned': (), 'Delivered': (), 'Cancelled': (), } OSCAR_ORDER_STATUS_CASCADE = { 'Processing': 'In progress', 'Shipped': 'Shipped', 'Delivered': 'Delivered', 'Returned': 'Returned', 'Cancelled': 'Cancelled' } The initial line status is set correctly to Pending, the problem is only in the order status.Is there some settings that I am missing? -
django ecommerce admin site
46 29 I'm starting to organize a new project and let's say i'll have a few models like products and catalogs. I will allow my clients (not visitors, only specific clients) to login on Django Admin site to create, edit and delete their own catalogs. Lets say I create a model called "Shop", create every shop (name, address, logo, contact info and etc.) and create an admin user binded to that shop. Now I want this new admin (who's not a site admin, but a shop admin -- probably an user group) to see and edit only the catalogs linked with his shop. -
Order by with specific rows first
I have a generic ListView in django 1.11 and I need to return the object ordered by alphabetical order, but changing the first 2 : class LanguageListAPIView(generics.ListCreateAPIView): queryset = Language.objects.all().order_by("name") serializer_class = LanguageSerializer And I'd like to return ENGLISH, FRENCH then every other languages in the database ordered by name. Is there a way to achieve this with django ORM ? Thank you, -
How to use Django static tag to load static files in Angular templates?
I'm using Django 2 and Angular 6. I'm trying to find a way to load static files (especially images) in Angular templates and inside the CSS file. Example: <img src="{% static 'svg/icons/icon.svg' %}"> Is it possible? -
Enable context processors based on response status in Django
In custom context processor I have a heavy calculated variable. I want not to calculate it if response status is not 200. # middleware.py if some_condition return render(request, 'base.html', status=404) # settings.py def my_custom_processor(request): a = # some heavy calculations return {'a': a} I don't want to calculate a if response status is not 200. -
Django Model __str__ called several times
I have created a Django Model as follow : class Profile(models.Model): user = models.OneToOneField(User,related_name='people', on_delete=models.CASCADE) is_holding = models.BooleanField(default=False) has_write_permission = models.BooleanField(default=False) phone_number = models.CharField(max_length=17, blank=True, null=True) country = models.ForeignKey(to=Country, on_delete=models.SET_NULL, null=True, blank=True) And I have define __str__ like this: def __str__(self): return self.user I have include a print before my return and I have observed that when saving an object, __str__ was called several times (4 times to be exact). I am wondering why is that the case ? Is it normal ? I have explored the source code of save here, line 658, but cannot find the answer. This is not a question related to queries to database. -
Django equivalent for MySQL bit datatype
I am facing issues with "makeflag" field which is bit(1) type in my database(MySQL). I have tried using booleanField and bit1booleanfield with below syntax. But i am getting error with both. when i try POST request with json data on this model, I get error as "Data too long for column" on passing 1 or 0 as value. And when i give true or false as value, then i get 400 Bad request. Can someone please help me understand how can i post data using django and json for bit field (of mysql). makeflag=models.BooleanField(db_column='MakeFlag',default=1) makeflag=Bit1BooleanField() My model is class Product(models.Model): productid = models.AutoField(db_column='ProductID', primary_key=True) name = models.CharField(db_column='Name', max_length=50) productnumber = models.CharField(db_column='ProductNumber', max_length=25) makeflag = models.TextField(db_column='MakeFlag', max_length=1) color = models.CharField(db_column='Color', max_length=15, blank=True) safetystocklevel = models.SmallIntegerField(db_column='SafetyStockLevel') reorderpoint = models.SmallIntegerField(db_column='ReorderPoint') standardcost = models.FloatField(db_column='StandardCost') -
Django website with secondary SQLite databse local
I have created a webframework in Django. There is however the problem that the webframework contains data that I can't put in an online environment, but has to stay in a local SQL storage. The webframework has to run on three computers that do not have access the command prompt, therefore I can't run a local Django project on each of the computers Is the following possible? Host a Django website (just a shell) with user authentication and an online database that just manages the users. Each computer has its own local SQL storage that Django is accessing i.e. SQLlite file that is present on the desktop. In this case, the worst case scenario would be that someone breaks into the webframework but can not access the files since they are only available locally. Am I overlooking anything or is this possible? I'm aware that this is very unusual and not very pratical, but it is the only think I can think of. If there is better alternative I would be open to suggestions. Regards -
Run javaScript if form.is_valid() with variable from views.py
I'm trying to use a javaScript to print a varible to a Dymo printer. I have tested the javaScript code and it works, but I don't know how I'm going to access and run this javaScript from my views.py. Maybe I can do it from the template, but the varible that I try to print contains some database information that is created when the form is valid. Please ask if anything is unclear! Thanks! Views.py def CreateWasteView(request): if request.method == 'POST': form = CreateWasteForm(request.POST) if form.is_valid(): waste = Waste_Item(material=form['materialList'].value(), height=form['height'].value(), width=form['height'].value()) waste.save() waste.code = form['materialList'].value() + str(waste.pk) waste.save() return render(request, 'waste/home.html') else: form = CreateWasteForm() context = { 'form': form } return render(request, 'waste/new.html', context) Template {% extends "waste/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <div class="col-md-6"> <fieldset class="form-group"> <legend class="border-bottom mb-4">New Waste-Item!</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Create</button> </div> </div> </form> </div> {% endblock content %} javaScript <script type="text/javascript" src="http://labelwriter.com/software/dls/sdk/js/DYMO.Label.Framework.3.0.js"></script> <script type="text/javascript"> function startupCode(code) { dymo.label.framework.trace = 1; var printers = dymo.label.framework.getPrinters(); if (printers.length == 0) throw "No DYMO printers are installed. Install DYMO printers."; dymo.label.framework.getPrintersAsync().then(function(printers){ // Successful result, printers variable has a list of … -
pipenv uwsgi django psycopg2
Just trying to start a django project with uwsgi it always fail. I've followed the tutorial: https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html The first hello world is running, also the runserver of the django project. But wsgi start fail: uwsgi --http :8000 --module project.wsgi --virtualenv /home/tec1/.local/share/virtualenvs/backled3-CB5DtoE6 Would result in: *** Starting uWSGI 2.0.18 (64bit) on [Tue Feb 26 11:06:17 2019] *** compiled with version: 8.2.0 on 26 February 2019 08:18:52 os: Linux-4.19.0-1-amd64 #1 SMP Debian 4.19.12-1 (2018-12-22) nodename: tec1 machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /mnt/DB/dj/backled3 detected binary path: /home/tec1/.local/share/virtualenvs/backled3-CB5DtoE6/bin/uwsgi *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 63225 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 4 spawned uWSGI http 1 (pid: 14046) uwsgi socket 0 bound to TCP address 127.0.0.1:35605 (port auto-assigned) fd 3 Python version: 3.7.2 (default, Jan 3 2019, 02:55:40) [GCC 8.2.0] Set PythonHome to /home/tec1/.local/share/virtualenvs/backled3-CB5DtoE6 *** Python threads support is disabled. You can enable it with --enable-threads *** Python main interpreter initialized at 0x55cbc1940ca0 your … -
i am new on django guide me how to make buttons working
I am new on Django and making a simple webpage navigation button on top which will take me to another page. I have tried my best but it is not working please guide me in this so that I may move ahead of this issue. ******views.py******** from django.shortcuts import render from django.views.generic import TemplateView def home(request): return render(request,"index.html") def aboutus(request): return render(request,"aboutus.html") ******urls.py********* from django.contrib import admin from django.urls import path from firstapp.views import home,aboutus urlpatterns = [ path('admin/', admin.site.urls), path('home/', home), path('about/', aboutus), ] ****html page***** <link rel="stylesheet" href="indexcss.css"> <meta charset="utf-8"> <title></title> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active" id="topnav"> <a class="nav-link" href="#">Account <span class="sr-only">(current) </span></a> </li> <li class="nav-item active" > <a class="nav-link" href="#">Contact</a> </li> </ul> </div> Please, someone, help me out with this issue. I just want to jump to other page using django submit button -
Django: Multiple bulk create within a transaction
I want to do multiple bulk creates(independent) within a transaction. with transaction.atomic(): if x: X.objects.bulk_create(x_objs) if y: Y.objects.bulk_create(y_objs) if z: Z.objects.bulk_create(z_objs) Now I want X to rollback if Y or Z fails. How do I do that? -
Django Queryset Filter by number of objects in related set
I have a model with a related set, something like follows: class User(models.Model): '''other stuff''' class Message(models.Model): user = models.ForeignKey('app.User') chat = models.ForeignKey('app.Chat') # Refers to Chat model below. class Chat(models.Model): ''' other stuff'''... So when I want to filter my Chats by existence of some message sent by some user within for example, I use something like: usr = User.objects.filter(pk=123) chats = Chat.objects.filter(message__user=usr) That's fine and dandy, but I want to filter by whether a chat contains a certain minimum number of messages (Eg. min. 3 messages in the chat). Ideally I want to use just the .filter function, without going through annotate. How can I do this? -
Django custom cache_page decorater returns error on the only first run afterwards it's ok
I created custom cache_page decorator for my app. It doesnt work on the first run and throwing error related to middleware: content_encoding = response.get("Content-Encoding", "") AttributeError: 'bool' object has no attribute 'get' But on the second and further run, it works because the cache has been set. I installed django debug_toolbar and added cors middleware to my middlewares. Can anyone help on this? Here is my custom decorator func: def cache_page(timeout): """custom cache page decorator""" def decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): print("wrapp", request) cache_key = hashlib.md5( iri_to_uri(request.build_absolute_uri()).encode('ascii') ).hexdigest() cached_data = cache.get(cache_key) if cached_data is not None: return cached_data response = func(request, *args, **kwargs) if (isinstance(response, Response) and response.status_code in (200, 301, 302, 304)): cache_timeout = timeout() if callable(timeout) else timeout if hasattr(response, 'render') and callable(response.render): response.add_post_render_callback( lambda r: cache.set(cache_key, r, cache_timeout) ) else: cache.set(cache_key, response, cache_timeout) return response return wrapper return decorator -
Authentication credentials were not provided. Django Rest Framework/JWT and React native iOS
axios.get( url, { headers: { Authorization: "Bearer " + access_token } } ) This is the request currently I'm sending to the server on my react native project. When It runs on Android It works without any problem. But on iOS it Shows Authentication credentials were not provided. What's wrong with this. Only it happens when I try to send Bearer token with the request. otherwise, axios works on ios too. Please help me to find out the problem. thank you. -
Django - 500 internal server error after a collectstatic
trying a switch in production mode (debug=False in setting.py), I launched the python manage.py collectstatic command. from that moment when I try to connect to the site it gives me an internal error 500 even if I start the command via python manage.py runserver 0.0.0.0:8000 this is my setting.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'Game/template/game') MEDIA_DIR = os.path.join(BASE_DIR,'game/media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '**************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['<server-ip>','<server-domain>',] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Accounts', 'Game', 'marketing', 'Blog', 'contactus', 'django_filters', 'widget_tweaks', 'debug_toolbar', 'tempus_dominus', 'bootstrap3_datetime', 'django_summernote', 'session_security', ] SUMMERNOTE_THEME = 'bs4' #SESSION SECURITY SETTINGS SESSION_SECURITY_WARN_AFTER = 540 SESSION_SECURITY_EXPIRE_AFTER = 1800 SESSION_EXPIRE_AT_BROWSER_CLOSE = True MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' ROOT_URLCONF = 'CicloPost.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'CicloPost.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases # Password … -
Get Logged In User Info Inside Django-tempatetags inclusion tag method?
I'm trying to render the navigation Menu having Logged In User Name In It by making a user of custom templatetags. PFB the code, @register.inclusion_tag('kpt/navbar.html') def getmenu( params ): raw = params.split("|") active_item = raw[0] menus = [ {"name": "Home", "url": "/kpt/", "class":""}, {"name": "High CPC", "url": "/kpt/hcpc", "class":""}, {"name": "Trending Keywords", "url": "/kpt/tcpc","class":""} ] for menu in menus: if menu["name"] == str(active_item): menu["class"] = "active" return {'menus':menus, "user":raw[1] } I want to retrieve the Logged In User Full Name inside this method without having any dependency to pass it from the template as there then I would require to concatenate a variable with a static string, to do so. Which is not supported in Jinja! Something like this: {% getmenu "Home|MD Danish" %} Where MD Danish will be in {{user.get_full_name}} Please help! -
I am trying to run migrations but when i run migrate.py I get a type error?
i GET A BIG ERROR BUT THE MAIN THING I GET IS : Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions, subscribe Running migrations: Applying app.0019_auto_20190224_0449...Traceback (most recent call last): File "C:\Users\Ubaid Parveez\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\dateparse.py", line 106, in parse_datetime match = datetime_re.match(value) TypeError: expected string or bytes-like object Here,s the models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from tinymce import HTMLField class Category(models.Model): title = models.CharField(max_length = 20) def __str__(self): return self.title class Post(models.Model): image = models.ImageField() title = models.CharField(max_length = 100) body = HTMLField() published_date = models.DateTimeField(auto_now_add = True) categories = models.ManyToManyField(Category) featured = models.BooleanField(default = False) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog',kwargs = { 'pk':self.pk }) @property def get_comments(self): return self.comments.all() class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments") name = models.CharField(max_length = 200) body = models.TextField() def __str__(self): return self.name class Upload(models.Model): image = models.ImageField(upload_to = 'images') content = models.FileField(upload_to = 'images/%Y/%M/%d') -
Updateview does not restrict only to the id of the logged in user
I am using UpdateView, but I need only that when the user that is logged in can change, just the photo of it. As it is now if I type in the browser http://127.0.0.1:8000/change-photo/26/ it changes the photo of the user 26, even though I am logged in with the user 12 I want only the logged in user to be able to change their photo and not the photos of other users View.py class PhotoUpdate(UpdateView): model= Usuario fields = ['foto'] template_name='change-photo.html' def get_success_url(self): return reverse('sistema_index') url.py url(r'^change-photo/(?P<pk>\d+)/$', views.PhotoUpdate.as_view(), name='sistema_change_photo'), change-photo.html {% if user.is_authenticated %} {{ user.usuario.pk }} <form method="post" action="{% url 'sistema_change_photo' user.usuario.pk%}" class="form-signin" enctype="multipart/form-data"> {% csrf_token %} <div class="form-row "> <div class="form-group col-md-12 "> {{ form.foto }} </div> </div> <div class="form-row"> <div class="form-group col-md-12"> </div> <input type="submit" class="btn btn-primary" > </form> -
jQuery ajax call “Not Found” error with django
i have 3 dependent dropdownlists country city road. where country is pre-populated from the database and based on the selection of the first the second will display the related cities. i am able to select from the country list and it display the related cities, but when i try to select the city and display the below error : Not Found: /getdetails2 how to fix this error where /getdetails2 is a function in views.py models.py class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class City(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country,on_delete=models.CASCADE , related_name = 'cities') def __str__(self): # return'id : {0} MouhafazatID :{1} Name :{2}'.format(self.id,self.MouhafazatID,self.name) return str(self.name) class Road(models.Model): Vil = models.CharField(max_length=100) city= models.ForeignKey(City,on_delete = models.SET_NULL, null=True) city= models.ForeignKey(City,on_delete = models.CASCADE, related_name='roads') country= models.ForeignKey(Country,on_delete = models.SET_NULL,null=True) def __str__(self): return str(self.Vil) home2.html $('select#selectcities').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var city_name = optionSelected.text(); data = {'ct' : city_name }; $.ajax({ type:"GET", url:'/getdetails2', // data:JSON.stringify(data), data:data, success:function(result){ console.log(result); $("#selectroads option").remove(); for (var i = result.length - 1; i >= 0; i--) { $("#selectroads").append('<option>'+ result[i].Vil +'</option>'); }; }, }); }); }); </script> views.py def getdetails2(request): if request.method == 'GET' and request.is_ajax(): city_name = request.GET.get('ct', None) print ("ajax city_name … -
Django admin, how to hide a specific model field during view and edit
I have a django model A, this model is registered on the django admin from where the admin user can add/edit data. #models.py class A(models.Model): eth_address = models.CharField( max_length=100) private_key = encrypt(max_length=100)) Now I want that, once the data is added to db, while editing or viewing, I not want private_key field to be visible on the UI. I tried using the following snippet in admin : #admin.py ... def get_form(self, request, obj=None, **kwargs): self.exclude = ("private_key", ) form = super(AAdmin, self).get_form(request, obj, **kwargs) return form ... However, if I open a model in edit view and hit save, it replace private_key to NULL in the db, it meant this value was not passed from the front end which is true, since we excluded the field, however while saving it's value was overridden to NULL, any idea how to fix this? -
Display a message if loop is empty
I would like to display a message like "no content" using a "if" in my template. I tried : views.py {% for links in links_list %} {% if links is None %} <p>No content</p> {% else %} <p>some content</p> {% endif %}{% endfor %} It does not work, thanks. -
Adverts in Django
I want to create a Django website where the users can watch adverts, maybe even click on some pages which are advertised and earn in game points for watching the video/clicking on the link. What's the best way of achieving this? Would something like Google ads be the best way?