Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change django-allauth email verification behaivior
Django has builtin User model is_active field. I assume that django-allauth sets this field to True after successful e-mail verification. I would manually enable the user and change this field to "true" via the Django admin interface instead. Is it possible to change this behavior from django-allauth? -
How to use firebase (or another database) to store and retrieve at random an image of a multi-choice question with answer stored with it (pyrebase)
Hey im trying to create a quiz where the program randomly selects an image. Each image is a multiple choice question and alongside the image, the answer is stored. Im using tkinter to display the question. The user clicks a button that corresponds to an answer (a,b,c, or d) and the program checks the input against the answer stored with the question in the database. Ive thought of three possible solutions to this: Multiple images of questions are stored in the database alongside the answer to it. The program randomly selects an image then displays it with tkinter. The users selected answer is then compared to the answer stored alongside the image. The program randomly selects an image like example 1, but this time using the images file name with a switch case statement (a custom made one as they are not in python) to check the answer If the question being an image is too complicated to store with the answer, ill just create a string with the question typed out, and have this string stored alongside its respective answer. Im currently intending on using pyrebase (the firebase wrapper for python) but am open to suggestions for other databases … -
Database schema changing when using pandas to_sql in django
I am trying to insert a dataframe to an existing django database model using the following code: database_name = settings.DATABASES['default']['NAME'] database_url = 'sqlite:///{database_name}'.format(database_name=database_name) engine = create_engine(database_url) dataframe.to_sql(name='table_name', con=engine, if_exists='replace', index = False) After running this command, the database schema changes also eliminating the primary key and leading to the following error: django.db.utils.OperationalError: foreign key mismatch Note: The pandas column names and the database columns are matching. -
I am trying to get the value in veiws.py django
I am making an eCommerce website and I am facing an issue, So whenever I click this show button I want to get that particular Products id in my views.py here is the views.py def Product_details(request): ctgs = categorie.objects.all() sctgs = sub_categorie.objects.all() ProductId = ? print(ProductId) Product = Products.objects.get(id=ProductId) print(Product) return render(request, 'product-details.html',{'ctgs':ctgs,'sctgs':sctgs, 'Product':Product}) I want product id here how can I get it? -
Updating Cart in Django Admin on adding and removing items
I have the following models in my application in which I add items to a cart and can remove them too. The adding and removing of a cart item has been achieved through my views but what i want is that about how can I do this in Admin. class Product(models.Model): product_name=models.CharField(max_length=32) price=models.IntegerField() class Cart(models.Model): cust_id=models.ForeignKey(User, on_delete=models.CASCADE) count=models.IntegerField(default=0) total=models.IntegerField(default=0) class Cart_Item(models.Model): item=models.ForeignKey(Product, blank=True, null=True, on_delete=models.CASCADE) quantity=models.IntegerField() cart=models.ForeignKey(Cart, on_delete=models.CASCADE) What I want to achieve in Admin is that that if I add or remove a Cart_Item object in Admin, it should update the corresponding values of count and total in Cart accordingly for that particular user -
How do people create apps with regional languages? [closed]
I want to know how do people create apps which function with regional languages. Let me take an example of google assistant. How does it speak in Arabic or Hindi. How do people create apps that use different languages. -
how do I fix the "bool object is not callabe" error in my Django website
So I am trying to fix a website that is not mine, for some reason when I click the button to register I get this error: File "C:\Users\eneko\Desktop\viveWeb\blog\views.py", line 20, in login_view if request.user.is_authenticated(): TypeError: 'bool' object is not callable This is the view that authenticates the user to register: def login_view(request): if request.user.is_authenticated(): return redirect(reverse('portada')) mensaje = 'El usuario no estaba registrado' if request.method == 'POST': username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate( username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect(reverse('portada')) else: return render(request, 'accounts/login.html', {'error_message': 'Your account has been disabled'}) else: mensaje = 'Se va a registrar un usuario' form = RegistroUserForm(request.POST, request.FILES) if form.is_valid(): cleaned_data = form.cleaned_data dia = form.cleaned_data['dia'] mes = form.cleaned_data['mes'] year = form.cleaned_data['year'] password = dia + mes + year + 'year' user_model = User.objects.create_user(username=username, password=password) user_model.save() user_profile = UserProfile() user_profile.user = user_model user_profile.save() username = request.POST.get('username') dia = request.POST.get('dia') mes = request.POST.get('mes') year = request.POST.get('year') password = dia + mes + year + 'year' user = authenticate(username=username, password=password) if user is not None: mensaje = 'Se va a registrar un usuario12' … -
i am using django version 3 and when i tried to work on model managers i got this error
models.py class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def features(self): return self.get_queryset().featured() def get_by_id(self, id): qs = self.get_queryset().filter(id=id) if qs.count() == 1: return qs.first() return None views.py class ProductDetailView(DetailView): template_name = "Products/details.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) print(context) return context def get_object(self, *args, **kwargs): request = self.request pk = self.kwargs.get('pk') instance = Product.objects.get_by_id if instance is None: raise Http404('Product does not exist') return instance error: AttributeError: 'Manager' object has no attribute 'get_by_id' -
Tricking with inspect module for unittests in Python
I have a following code snippet to extract request object from Python stack. import inspect for frame_record in reversed(inspect.stack()): if frame_record.function == 'get_response': request = frame_record.frame.f_locals['request'] break else: return None It loops through stack frames, and tries to find ‘get_response’ to fetch request object from there. It all works good but I need to write unitests for it, where we don’t have any request, get_reponse , etc in stack. Question is – is it possible to trick inspect somehow (genuinely or via Mock) by creating 'get_response' in stack and substituting frame_record.frame.f_locals['request'] with fake request, which is request = namedtuple('request', ['user', ]) Thank you. -
Django async view filtering
Hi, I want my view.py to send async data when the user filters list of products. I don't want to send data through json but through django view dynamically. As user selects any filter the list of data should be updated without page refresh. my views.py: from programs.models import Program from django.views.generic import ListView, DetailView from django.http import JsonResponse from django.views.generic.detail import SingleObjectTemplateResponseMixin from asgiref.sync import async_to_sync class ProgramListView(ListView, SingleObjectTemplateResponseMixin): model = Program template_name = 'programs/program_list.html' context_object_name = 'programs' sync_function = async_to_sync @async_to_sync async def get_queryset(self): url_parameter = self.request.GET.get('q') # if self.request.method == 'GET' and self.request.is_ajax(): if self.request.method == 'GET' and url_parameter is not None: queryset = Program.objects.filter(degree = url_parameter) return queryset if self.request.method == 'GET' and url_parameter is None: queryset = Program.objects.all() return queryset # def render_to_response(self, context, url_parameter='BSc'): # # Look for a 'format=json' GET argument # # if self.request.GET.get('format') == 'json': # # if self.request.is_ajax(): # if url_parameter=='BSc': # return JsonResponse(context) # else: # return super().render_to_response(context) -
I Have Two Models and i want those values which are not used by my another model by foreign key
## Bilty Model class tms_bilty(models.Model): bilty_no = models.CharField(max_length = 400,null=True, blank=True,default=increment_bilty_no) send_customer_code = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return str(self.bilty_no) class Meta: ordering = ['bilty_no'] ## Invoice Model class tms_local_invoice(models.Model): invoice_no = models.CharField(max_length=200,unique=True, default=increment_Job_no) bilty_no = models.ForeignKey(tms_bilty,related_name="tms_bilty_invoice",null=True,on_delete=models.CASCADE) I have Two Models Bilty and Invoice. Suppose I created three Bilty numbers and i created two invoice by passing two different Bilty numbers. So i want to return third Bilty no which are not used in invoice model. Any Query Regarding This So that i get those Bilty no which are not used by invoice model. Thanks -
Django Rest Framework Integrity Error at NOT NULL constraint fail
i'm trying to post a transaction via django rest framework, however it shows error in django log as below: IntegrityError at /api/item_trans/ NOT NULL constraint failed: chemstore_itemtransaction.bin_code_id it has no problem if I post the same data from the Django admin web. therefore I suppose the problem has happened at DRF any help is welcome, thank you models.py class BinLocation(models.Model): bin_code = models.CharField(max_length=10, unique=True) desc = models.CharField(max_length=50) def __str__(self): return self.bin_code class Meta: indexes = [models.Index(fields=['bin_code'])] class ItemMaster(models.Model): item_code = models.CharField(max_length=20, unique=True) desc = models.CharField(max_length=50) long_desc = models.CharField(max_length=150, blank=True) helper_qty = models.DecimalField(max_digits=10, decimal_places=4) unit = models.CharField(max_length=10, blank=False) def __str__(self): return self.item_code class Meta: verbose_name = "Item" verbose_name_plural = "Items" indexes = [models.Index(fields=['item_code'])] class ItemTransaction(models.Model): # trace_code YYMMDDXXXX where XXXX is random generated trace_code = models.CharField(max_length=20, unique=False) item_code = models.ForeignKey( ItemMaster, on_delete=models.CASCADE, related_name='+', blank=False, null=False) datetime = models.DateTimeField(auto_now=False, auto_now_add=False) qty = models.DecimalField(max_digits=10, decimal_places=4) unit = models.CharField(max_length=10, blank=False) action = models.CharField( max_length=1, choices=ACTION, blank=False, null=False) bin_code = models.ForeignKey( BinLocation, related_name='+', on_delete=models.CASCADE, blank=False, null=False) remarks = models.TextField(blank=True) def __str__(self): return f"{self.trace_code} {self.datetime} {self.item_code} {dict(ACTION)[self.action]} {self.qty} {self.unit} {self.bin_code}" serializers.py class ItemMasterSerializer(serializers.ModelSerializer): class Meta: model = ItemMaster fields = '__all__' class ItemTransactionSerializer(serializers.ModelSerializer): item_code = serializers.SlugRelatedField( slug_field='item_code', read_only=True ) bin_code = serializers.SlugRelatedField( slug_field='bin_code', read_only=True, allow_null=False ) … -
Sudden "unknown MySQL server host error" on AWS with Django
I am receiving a lot of error reports from my Django server throwing: (2005, "Unknown MySQL server host 'my-address.us-east-1.rds.amazonaws.com' (0)"). The server has been connecting to this database for more than a year without any issue. But this morning I suddenly started to receive this error, even though I didn't do any changes to the code. Furthermore, when I connect to my website, it actually loads data from the database fine. Apparently there is a random chance that it won't manage to connect? Any idea what can cause that and how to fix it? I am on Amazon lightsail. -
Subquery Count in Python Django
I have a problem with subquery count in Python Django... Query MySQL: SELECT usuario.name, COUNT(*) AS Groups,( SELECT COUNT(*) FROM group WHERE group.user_id=user.id and state = 'on going') AS Started FROM user INNER JOIN group ON (user.id=group.user_id) WHERE user.rol = 'Provider' GROUP BY group.user_id ORDER BY Groups desc; Views: connected = GroupModel.objects.values( 'usuario__name').filter( user__rol='PROVIDER'.lower(), estado=ESTADOS.'ON_GOING'.lower()).annotate( started=Count('user')) totals = GroupModel.objects.values( provider=Concat('user__name', Value(' '), 'user__subname')).annotate( ge_totals=Count('user'),ge_connected=Subquery(connected.values('started')[:1])).order_by( '-ge_connected') First query return: <QuerySet [{'user__name': 'James', 'started': 3}, {'user__name': 'John', 'started': 2}, {'user__name': 'Frank', 'started': 2}, {'user__name': 'Sara', 'started': 1}]> While second query return: <QuerySet [{'user__name': 'James', 'ge_totals': 10, 'started': 3}, {'user__name': 'John', 'ge_totals': 10, 'started': 3}, {'user__name': 'Frank', 'ge_totals': 12, 'started': 3}, {'user__name': 'Sara', 'ge_totals': 9, 'started': 3}]> I need the query to return the following: <QuerySet [{'user__name': 'James', 'ge_totals': 10, 'started': 3}, {'user__name': 'John', 'ge_totals': 10, 'started': 2}, {'user__name': 'Frank', 'ge_totals': 12, 'started': 2}, {'user__name': 'Sara', 'ge_totals': 9, 'started': 1}]> The problem is that the second query, always return 3, which are the connected that the user 'James', if in subquery I remove [:1] python gives me the following error: django.db.utils.OperationalError: (1241, 'Operand should contain 1 column(s)') I don't know where to continue, I'm a bit desperate, any help is good -
Django ORM in Views - How can I join multiple tables (models)
I am new to Django and went through the docs but still can't find a solution to my problem. I checked several tutorials regarding ORM and how to use it in my views but maybe I landed on basic queries. If any can recommend a tutorial regarding ORM and manipulating ORM or some ORM exercises to practice it would be much appreciated. Let's get back to the point: I need to create a view (my homepage - superidlist view) that sends the needed data to my template to be shown on a collapsible menu. I have 4 models for now. SuperID, ClientAccount, Entity, Transaction. The collapsible menu needs to show the entity_super_id, the accounts number for each entity and the transactions made for each account. How should write the view to show the specific transactions for each specific account on dropdown and not all the transactions. I will post the models.py, the view and part of the template models.py: from django.db import models from django.utils import timezone from django.forms import widgets from django.urls import reverse from django.db.models import Q class SuperIDQuerySet(models.QuerySet): def search(self, query=None): qs = self if query is not None: or_lookup = (Q(super_id__icontains=query) | Q(account_name__icontains=query) | Q(full_name__icontains=query) ) … -
django ckeditor is not working with model form. It is rendering html document instead of html form
I am trying to use ckeditor widget in my model form. And when I try to render the form in the browser whole html of that template gets printed. I tried using safe filter but that did not workout for me. However, everything works fine on django admin panel, widget is shown there but not for model form. models.py: import datetime import uuid from django.core.exceptions import ValidationError from django.db import models from django.contrib.auth import get_user_model # another way to import User from django.utils import timezone from django.urls import reverse from django.template.defaultfilters import slugify from ckeditor.fields import RichTextField STATUS = ( (0,"Draft"), (1,"Publish") ) now = timezone.now() class Post(models.Model): author = models.ForeignKey(get_user_model(), on_delete= models.CASCADE, related_name='blog_posts') title = models.CharField(max_length=200) thumbnail_img = models.ImageField(upload_to='thumbnail_path/') slug = models.SlugField(max_length=200) view_count = models.PositiveIntegerField(default=0) updated_on = models.DateTimeField('Date and Time', auto_now= True) created_on = models.DateTimeField(auto_now_add=False) status = models.IntegerField('Status', choices=STATUS, default=0) content = RichTextField() class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[self.pk]) views.py: class CreatePostView(CreateView): model = Post form_class = PostForm # fields = '__all__' content_type = 'posts' template_name = 'posts/newpost.html' success_url = 'users/profile' forms.py: from django import forms from django.contrib import admin from .models import Post from ckeditor.widgets import CKEditorWidget class PostForm(forms.ModelForm): content … -
django.urls path error: imageSaved() got an unexpected keyword argument 'folder'
I am running a python-django server on my local computer with django.urls i try to define a path to server that contains folder and file my code: from django.urls import path urlpatterns = [ path("", server.views.index, name="index"), path("imageSaved/<str:folder>/<str:picture>", server.views.imageSaved, name="imageSaved") ] Because the path is a string I defined it that way:<str:folder>/<str:picture> When i wrote a url: http://localhost:5000/imageSaved/fff/ddd I got error: TypeError at /imageSaved/dd/dd imageSaved() got an unexpected keyword argument 'folder' The Traceback is: Environment: Request Method: GET Request URL: http://localhost:5000/imageSaved/dd/dd Django Version: 3.1rc1 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'server'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Traceback (most recent call last): File "C:\Users\tovar.RCDC\AppData\Local\Programs\Python\Python38\lib\site-packages\django-3.1rc1-py3.8.egg\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\tovar.RCDC\AppData\Local\Programs\Python\Python38\lib\site-packages\django-3.1rc1-py3.8.egg\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /imageSaved/dd/dd Exception Value: imageSaved() got an unexpected keyword argument 'folder' Thanks!! -
*args and **kwargs in Django Model Methods
from hashlib import md5 from django.db import models class Url(models.Model): full_url = models.URLField(unique=True) url_hash = models.URLField(unique=True) def save(self, *args, **kwargs): if not self.id: self.url_hash = md5(self.full_url.encode()).hexdigest()[:10] return super().save(*args, **kwargs) Hello I am starting out in Django and Django Rest Framework. I am going through a tutorial but i am having trouble understanding why I need *args and **kwargs in the def save method. I know the *args and **kwargs basic grammar but I can't understand why you need *args and **kwargs as the argument. Thanks for your help in advance! -
Creating Cart in Django using ManToManyField()
I have three classes in my Models and all have prices on them. I want to create Cart object. How do i pass all 3 in one CartItem using ManToManyField. models.py class Women(models.Model): photo = models.ImageField(upload_to='media') title = models.CharField(max_length=20) description = models.CharField(max_length=150) price = models.IntegerField() objects = models.manager def __str__(self): return self.title class Meta: verbose_name_plural = 'Women' class Men(models.Model): photo = models.ImageField(upload_to='media') title = models.CharField(max_length=20) price = models.IntegerField() description = models.CharField(max_length=150) objects = models.manager def __str__(self): return self.title class Meta: verbose_name_plural = 'Men' class Kids(models.Model): photo = models.ImageField(upload_to='media') title = models.CharField(max_length=20) price = models.IntegerField() description = models.CharField(max_length=150) objects = models.manager def __str__(self): return self.title class Meta: verbose_name_plural = 'Kids' I want to create class Cart(models.Model): and class CartItem(models.Model): -
Django form to formset
I'm currently learning Django forms and I came across this post: https://simpleisbetterthancomplex.com/questions/2017/03/22/how-to-dynamically-filter-modelchoices-queryset-in-a-modelform.html One of the forms currently looks like this: What I'd like to do is to change Category into a formset and be able to render multiple dropdowns while creating a product. My models.py: class Category(models.Model): name = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=30) price = models.DecimalField(decimal_places=2, max_digits=10) category = models.ForeignKey(Category, on_delete = models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name My forms.py: class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('name', ) class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('name', 'price', 'category', ) def __init__(self, user, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['category'].queryset = Category.objects.filter(user=user) Current method in views.py: @login_required def new_product(request): if request.method == 'POST': form = ProductForm(request.user, request.POST) if form.is_valid(): product = form.save(commit=False) product.user = request.user product.save() return redirect('products_list') else: form = ProductForm(request.user) return render(request, 'products/product_form.html', {'form': form}) products_form.html: {% extends 'base.html' %} {% block content %} <h1>New product</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> <a href="{% url 'products_list' %}">cancel</a> </form> {% endblock %} What I tried is to make use of the modelformset_factory and change the method in views.py … -
Is it okay to make use threading pool inside django view?
Inside django view I need to make several parallel requests to the database (solr) and I want to use threading pool for this. Is this okay? My concern is that django might not like another threads inside threads. I tested my solution in gunicorn setup (with default worker type) and everything works fine. But I still have some doubts. Do you know any pitfalls? Here is simple example of the view: from multiprocessing.pool import ThreadPool def foo_view(request): with ThreadPool() as p: results = p.starmap(func_with_solr_request, [...params...]) return serialize(results) -
Django: Adding data through for-loop deletes the old data in model
In trying to get all the data in user's cart(Model) and looping through to create a placeorder(Model) record. items = CartItem.objects.filter(user=request.user) for item in items: checkout_instance = Placeorder(user=request.user, order_item=item) checkout_instance.save() This save the items and creates a row for each item in Placeorder Model, but it deletes the old data(previously placed order records) in Placeorder Model. I cannot figure out this behaviour. I am confused. Maybe I am missing something stupidly simple thing. Please help. -
ModuleNotFoundError: No module named 'AsaServer'
enter image description here i have (ModuleNotFoundError) while i have installed 'AsaServer' what should i do now? -
Inherit from abstract class Django
I am building a platform with 3 users roles: Admin, Creator and Brand. I redefined a default django User to be able to login by email. class AbstractUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=32, unique=True) first_name = models.CharField(max_length=32, blank=True) last_name = models.CharField(max_length=64, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) location = models.CharField(max_length=120, blank=True) bio = models.TextField(blank=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: abstract = True def __str__(self): return self.email I made this class an abstract one to be able to add new classes, inherit from the Abstract class and redefine their attributes. class PlatformAdmin(AbstractUser): pass class Creator(AbstractUser): email = models.EmailField(max_length=32, unique=True, error_messages={ 'unique': "A customer with that email already exists.", }) class Brand(AbstractUser): name = models.CharField(max_length=64) I also add in settings.py following: AUTH_USER_MODEL = 'users.PlatformAdmin' Now when I run makemigrations it will give the following output: users.Brand.groups: (fields.E304) Reverse accessor for 'Brand.groups' clashes with reverse accessor for 'Creator.groups'. HINT: Add or change a related_name argument to the definition for 'Brand.groups' or 'Creator.groups'. users.Brand.groups: (fields.E304) Reverse accessor for 'Brand.groups' clashes with reverse accessor for 'PlatformAdmin.groups'. HINT: Add or change a related_name argument to the definition for 'Brand.groups' or 'PlatformAdmin.groups'. … -
How to Iterate response value in combobox using inline jquery ? -Django
I have an object named data2 contains multiple data that I'm rendering from views.py to my HTML template. {% for item in data2 %} <tr> <td><input type="text" name="from" class="form-control input_data" value="{{item.from_age}}"></td> <td><input type="text" name="to" class="form-control input_data" value="{{item.to_age}}"></td> <td id ="gender_select"> <script>$(function() {$('#gender_select :input').each(function() { $("#gender option[data-value='" + '{{item.gender}}' +"']").attr("selected","selected"); });});</script> <select name="gender" id="gender" class="form-control input_data" > <option data-value="select" >Select</option> <option data-value="male" >Male</option> <option data-value="female" >Female</option> </select> </td> <td><a href='' class='remove'><span class=''></span></a></td> </tr> {% endfor %} In {{item.gender}}, on the first iteration, I have value 'Male' and on the second iteration, I have value "Female" so it should be automatically select the value but after executing the above code, I'm facing an error $ is not defined also can't see the values. Please let me know where i'm wrong ?