Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom form widget in django model admin change_form.html
I have implemented my own version of vertical filter that works for not just M2M fields but some custom data. I wanted to show it in my Django admin change_form.html. I wanted to know how to implement that, or turn it into a custom form widget. Here's my code. file.html <div class="row"> <div class="col-6"> <p onclick="choose(this)"> something </p> </div> <div class="col-6" id="chosen"> </div> </div> file.js var chosen = $("#chosen") function choose(p){ chosen.append(p); } this is how it looks The initial task is to have the left side of the div to be populated with the fields in some model, which I am getting through field_list = list() for i in AdqtHomescreen._meta.get_fields(): if hasattr(i, 'attname'): field_list.append(i.attname) elif hasattr(i, 'field_name'): field_list.append(i.field_name) I already know how to add custom media to Django Forms using class MyModelAdmin(admin.ModelAdmin): class Media: js = ('file.js', ) -
Image upload with fetch api not working in django
My views.py file def change_profile_picture(request): if not request.user.is_authenticated: return JsonResponse({"status": "403", "msg": "Unauthorized request"}) if request.method == 'POST': if request.is_ajax(): form = UploadPictureForm(request.POST) if form.is_valid(): customuser = request.user.customuser customuser.picture = form.cleaned_data['picture'] customuser.save() return JsonResponse( { "status": "200", "msg": "Successful", "data": f"{customuser.picture.url}" } ) else: return JsonResponse({"status": "400", "msg": "invalid form"}) else: return JsonResponse({"status": "401", "msg": "Bad request"}) else: return JsonResponse({"status": "403", "msg": "invalid request method"}) forms.py class UploadPictureForm(forms.Form): picture = forms.ImageField( label="Profile picture" ) Javascript code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $('.upload-btn').on('click', () => { document.getElementById('id_picture').click(); }) $('.close-btn').on('click', () => { document.getElementById('profile-picture').src = $('#profile-picture').data('target'); document.getElementById('submit-picture').style.visibility = 'hidden'; }) $('#submit-picture').on('click', () => { var picture = document.querySelector('input[type="file"]'); var formData = new FormData(); formData.append('csrfmiddlewaretoken', getCookie('csrftoken')); formData.append('picture', picture.files[0]); fetch('/auth/change-profile-picture/', { method: 'POST', body: formData, cache: 'default', mode: 'cors', credentials: 'include', headers: { "X-Requested-With": "XMLHttpRequest", } }) .then((res) => res.json()) .then((data) => { if(data.status … -
Non superusers unable to login and displaying password in admin - Django
In my Django project, I have a custom user class inside models.py of an app called "accounts": from django.db import models from django.contrib.auth.models import AbstractUser from localflavor.br.br_states import STATE_CHOICES class Company(models.Model): id = models.IntegerField(primary_key=True) class Client(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, default=0) role = models.CharField(verbose_name='Cargo', max_length=20) city = models.CharField(verbose_name='Cidade', max_length=20) state = models.CharField(verbose_name='Estado', max_length=2, choices=STATE_CHOICES) phone = models.CharField(verbose_name='Telefone', max_length=25) I have this variable set at my settings.py: AUTH_USER_MODEL = 'accounts.Client' But I am only able to login to the platform with a superuser. Non superusers get a wrong username or password (and they are active, I've checked). Also, in the admin page, it is showing the password of the Clients. Btw, I am using POSTGRES. 1) How can I make any user login into the platform (not admin page, but my main platform)? 2) How can I properly store their password and not show it in the admin page? Thank you. -
TypeError at /cart/cheese-grits/ update_cart() missing 1 required positional argument: 'qty'
I am trying to add more than one of the same item to a cart. I have been able to add one of each item to the cart, but when I tried to implement a quantity function, I get this error. When I was using a loop that made buttons, when I clicked them it would add one of that item to the order. I want to be able to add multiple of the same item. Thank you Views.py: def view(request): products = Product.objects.all() try: the_id = request.session['cart_id'] except: the_id = None if the_id: cart = Cart.objects.get(id=the_id) products = Product.objects.all() context = {"cart": cart, "products": products } else: context = {"empty": True, "products": products } template = "mis446/home.html" return render(request, template, context) def update_cart(request, slug, qty): try: qty = request.GET.get('qty') update_qty = True except: qty = None update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart = cart, product=product) if created: print ("yeah") if update_qty and qty: if int(qty) == 0: cart_item.delete() else: cart_item.quantity = qty cart_item.save() else: pass # if not cart_item in cart.items.all(): … -
Django AbstractBaseUser model not saving all the fields of the template in databse when information entered from registartion form?
enter image description here this is my forms code enter image description here This is my views code enter image description here this is my models code I am not sure what's wrong with my code it's only saving username , first name and last name data not other fields.enter image description here -
How to run Django app with Apache2, mod_wsgi and Anaconda?
I'm trying to run a django application with Apache2, wsgi_mod, Anaconda environment with Python3.8 in Ubuntu. When I run 'sudo service apache2 start' , the page keeps re-loading and the same error message is stacking at '/var/log/apache2/error.log'. Current thread 0x00007ff7b9507bc0 (most recent call first): [Thu Apr 02 20:02:27.236780 2020] [core:notice] [pid 24024:tid 140701942709184] AH00051: child pid 29871 exit signal Aborted (6), possible coredump in /etc/apache2 [Thu Apr 02 20:02:27.237711 2020] [core:notice] [pid 24024:tid 140701942709184] AH00051: child pid 29872 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' These are the sys.prefix and the sys.path (my_env) manager@ubserv01:/etc/apache2/sites-available$ python -c "import sys; print(sys.prefix)" /var/anaconda3/envs/my_env (my_env) manager@ubserv01:/etc/apache2/sites-available$ python -c "import sys; print(sys.path)" ['', '/var/anaconda3/envs/my_env/lib/python38.zip', '/var/anaconda3/envs/my_env/lib/python3.8', '/var/anaconda3/envs/my_env/lib/python3.8/lib-dynload', '/var/anaconda3/envs/my_env/lib/python3.8/site-packages'] This is the mod_wsgi-express module-config output: (my_env) manager@ubserv01:/etc/apache2/sites-available$ mod_wsgi-express module-config LoadModule wsgi_module "/var/anaconda3/envs/my_env/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so" WSGIPythonHome "/var/anaconda3/envs/my_env" Here is my /etc/apache2/sites-available/djangoProject.conf: LoadModule wsgi_module /var/anaconda3/envs/my_env/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so WSGIPythonHome /var/anaconda3/envs/my_env <VirtualHost *:80> ServerName opes.com ServerAdmin admin LogLevel warn DocumentRoot /var/www/opes/djangoProject <Directory /var/www/opes/djangoProject/djangoProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIPassAuthorization On WSGIDaemonProcess djangoProject python-path=/var/www/opes/djangoProject python-home=/var/anaconda3/envs/my_env WSGIProcessGroup djangoProject WSGIScriptAlias / /var/www/opes/djangoProject/djangoProject/wsgi.py ErrorLog "/var/log/apache2/djangoProject" CustomLog "/var/log/apache2/djangoProject" common </VirtualHost> /var/www/opes/djangoProject is the directory where manage.py is located. I enable this file … -
Does any body know how to fix this issue in Django login oathtoken
Environment: Request Method: POST Request URL: http://127.0.0.1:8000/api/login/ Django Version: 3.0.5 Python Version: 3.7.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authentication', 'rest_framework.authtoken', 'profilesapi'] Installed Middleware: ['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 "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (relation "authtoken_token" does not exist LINE 1: ...oken"."user_id", "authtoken_token"."created" FROM "authtoken... ^ ) was the direct cause of the following exception: File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/Users/XYZ/Documents/pycharm/DjangoChallenges/profile_project/profilesapi/views.py", line 130, in create return ObtainAuthToken().post(request) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/rest_framework/authtoken/views.py", line 46, in post token, created = Token.objects.get_or_create(user=user) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/XYZ/query.py", line 559, in get_or_create return self.get(**kwargs), False File "/Users/XYZ/profile_project/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get num … -
Specifying a custom user model in django and calling an object
Alright, so I'm a bit stuck here. I decided to create my own user model, which is turning out to be a huge head ache. And not to mention this is my first django project from scratch... So I am creating a dating app. I have a sample project of which I want to use some code and bring it over and adapt it to my project. I'm really not sure how to go about adapting some of the changes I need for my custom model. Here is the error I am getting: NameError at /mingle/ name 'models' is not defined Request Method: GET Request URL: http://localhost:8000/mingle/ Django Version: 2.2.3 Exception Type: NameError Exception Value: name 'models' is not defined Exception Location: /Users/papichulo/Documents/DatingApp/dating_app/views.py in mingle, line 113 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Server time: Fri, 3 Apr 2020 00:15:57 +0000 SAMPLE code try: user = (User.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user = None print(User.username) try: bio = models.UserProfile.objects.get(user=request.user).bio except models.UserProfile.DoesNotExist: create = UserProfile.objects.get_or_create(user = request.user) return redirect('profile') friend = models.UserProfile.objects.get(user=request.user).friends.all() context = dict(user = user, friend = friend) return render(request, 'index.html', context) My views.py def mingle(request): try: user = (Profile.objects.exclude(id=request.user.id).exclude(uservote__voter=request.user).order_by('?')[0]) except IndexError: user … -
How to query on the base_field of a Django ArrayField
Can I query the base_field of a Django ArrayField? For example, can I filter on "regions with a postcode that matches some regex" given the following model: models.py: from django.contrib.postgres.fields import ArrayField class Region(models.Model): postcodes = ArrayField(models.CharField(blank=True, null=True), blank=True, null=True) Something like Region.objects.filter(postcodes__contains__iregex=r'^SW1A.+') (obviously that doesn't work though) -
Django pgettext and format_lazy with raw regex string
As the title says... In Django 3.0 we can do: urlpatterns = [ path(format_lazy("{text_to_translate}", text_to_translate=pgettext("URL", "text_to_translate")), ] For actually translating text in the URL beyond the prefix added by i18n_patterns. However, what about re_path. What's the equivalent, if any, for being able to do: re_path(format_lazy(r"^{text_to_translate}/(?P<...>)/$", text_to_translate=pgettext("URL", "text_to_translate")), Since this is a raw string meant to be lazily compiled by re.compile. -
Different write and read operations with DRF
I am using Django Rest Framework for a project and I am running into a problem. When the frontend creates a Team they want to reference all relationships with an ID, but when getting the Team, they want the data from the relationship. How can I achieve this? models: class Team(models.Model): class Meta: db_table = "team" team_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class Organization(models.Model): class Meta: db_table = "organization" organization_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Position(models.Model): class Meta: db_table = "position" position_id = models.AutoField(primary_key=True) team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="positions") class Player(model.Model): class Meta: db_table = "player" player_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) positions = models.ManyToManyField(Position, related_name="players") serializers: class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = ["team_id", "name", "organization", "positions"] positions = PositionSerializer(many=True) # This is merely for output. There is no need to create a position when a team is created. organization = OrganizationSerializer() # Since an organization already exists I'd like to just give an organization_id when creating/editing a team. # I don't think the other serializers matter here but can add them on request. So when doing POST or PATCH on a team, I'd like the front end to be able to … -
Select all reverse relations Django ORM
My models are like this: class Credit(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey('Products', models.DO_NOTHING) class CreditStatus(models.Model): status = models.CharField(max_length=100) credit_id = models.ForeignKey('Credit', models.DO_NOTHING) class CreditCommision(models.Model): comission = models.CharField(max_length=100) credit_id = models.ForeignKey('Credit', models.DO_NOTHING) Is it possible to select all these tables in one query? Please note that I can't change Credit model. I tried: CreditStatus.objects.select_related('credit').filter(status='ACTIVE') But it select only 2 tables, but I need to select all? -
Not able to deplot Django restfule service using WAMP and mod_wsgi
I am trying to deploy an API built on Django rest-framework using mod_wsgi and WAMP. When I created a new Django project using 'django-admin startproject Predictor' and deployed it on WAMP, it was working fine as I can see the default Django window. Now I created an app in the project using 'python manage.py startapp Predictor' I built an API which accepts GET call and tested it using 'python manage.py runserver' and it was working fine. Now I started WAMP service again and try to go to 'localhost:8000' it keeps loading. And as soon as I stop WAMP service it crashes saying Unable to connect. Not sure what's happening. Can someone help what's wrong I am doing? FYI I am on windows and I have created and virtual environment for my Django project. This is how my .conf and wsgi files look like wsgi_windows.py activate_this = 'C:/Users/DELL/Envs/predenv/Scripts/activate_this.py' # execfile(activate_this, dict(__file__=activate_this)) exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('C:/Users/DELL/Envs/predenv/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('C:/Users/DELL/Envs/predenv') sys.path.append('C:/Users/DELL/Envs/predenv/Predictor') os.environ['DJANGO_SETTINGS_MODULE'] = 'Predictor.settings' os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Predictor.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() httpd.conf Listen localhost:8000 Listen [::0]:80 ServerName localhost:8000 LoadFile "c:/python376/python37.dll" … -
how to use django post_save signal
I have two models, client and contact model with foreign key relation, I using Django signals to create contact while the creation of the client, but I getting an error from the database : ( 1048, "Column 'client_id' cannot be null") when I check the database I found the contact and the client rows, so how to get rid of this error? models.py class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) @receiver(post_save, sender=Client_Data) def create_contact(sender, **kwargs): if kwargs['created']: conatact = Contact.objects.create(client=kwargs['instance']) post_save.connect(create_contact, sender=Client_Data) views.py def save_client_form(request, form,Contact_form, template_name): data = dict() if request.method == 'POST': if form.is_valid() and Contact_form.is_valid(): form.save() Contact_form.save() data['form_is_valid'] = True books = Client_Data.objects.all() data['html_book_list'] = render_to_string('Client_Section/partial_client_c.html', { 'client': books }) else: print(form.errors) print(Contact_form.errors) data['form_is_valid'] = False context = {'form': form,'contact_form':Contact_form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def client_create(request): if request.method == 'POST': form = ClientForm(request.POST) contact_form = Contact_Form(request.POST) else: form = ClientForm() contact_form = Contact_Form() return save_client_form(request, form,contact_form, 'Client_Section/partial_client.html') forms.py … -
Pass a single database entry from django to html template
Good Evening, hope you all are healthy during this critical times! I want to use the time to again work on my django web app. This time in addition to showing all my customers on the page I want to return the information for a single customer, that I selected on the website. I get the information about all the customers in the databse to show up on the website and when I use print in my views.py I see all the information from the single object. However, it will not show up in my template :( Here is my code (first the model): class PrivateCustomer (models.Model): WEIBLICH = 'W' MANNLICH = 'M' DIVERS = 'D' KEINEANGABE = 'K' GENDER =( (WEIBLICH, 'Weiblich'), (MANNLICH, 'Maennlich'), (DIVERS, 'Divers'), (KEINEANGABE, 'Keine Angabe') ) kundennummer = models.CharField(max_length=5, null=False, primary_key=True) vorname = models.CharField(max_length=30, null=False) nachname = models.CharField(max_length=30, null=False) adresse = models.CharField(max_length=50, null=False) postleitzahl = models.CharField(max_length=5, null=False) stadt = models.CharField(max_length=30, null=False) geschlecht = models.CharField(max_length=3, null=False, choices=GENDER) geburtstag = models.DateField(null=True) telefon = models.CharField(max_length=30, null=True) mobil = models.CharField(max_length=30, null=True) email = models.CharField(max_length=80, null=True) datum = models.DateField(null=False) # def __str__(self): # return self.nachname Then the function in the views.py: def showCustomer(request): if request.method == 'POST': kd = request.POST['kundennummer'] … -
Do a default save rather than override
I have a model that looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=160, null=True) avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path, validators=[validate_avatar], default="default/avatars/default.jpg") The model also has its default save method overridden to do some logic for the image that's uploaded. However, let's say the user signed up and has no image, so the default image is used instead. So when this happens Profile(user=22).save() I don't want to use the overridden save method because we are using the default image instead, so there's no extra logic needed. Is there a way I can save it normally in the database instead of it going through the overridden save method? -
'function' object has no attribute '_meta'
Internal Server Error: /credito/nuevo_solicitud/ Traceback (most recent call last): File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/views.py", line 56, in post return self.render_to_response(self.get_context_data(form1=form1, form2=form2)) # miercdero File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/views.py", line 23, in get_context_data contexto = super(Crear_solicitud_view, self).get_context_data(**kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/views/generic/edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) File "/Users/haroldtg/Documents/Desarrollo/shigab/shigab/apps/credito/forms.py", line 37, in init super().init(*args, **kwargs) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/forms/models.py", line 292, in init object_data = model_to_dict(instance, opts.fields, opts.exclude) File "/Users/haroldtg/Documents/Desarrollo/shigab/env/lib/python3.8/site-packages/django/forms/models.py", line 82, in model_to_dict opts = instance._meta AttributeError: 'function' object has no attribute '_meta' [02/Apr/2020 17:55:54] "POST /credito/nuevo_solicitud/ HTTP/1.1" 500 109540 -
Django ListView
It's my first time to use ListView and it doesn't work and give me error. I put get_query but they still give me same error. How can I fix the problem? And everytime when I write code in views.py I always used 'def' not 'class'. But could see many people use (and also django documents) 'class' for ListView. So for general render stuffs we use 'def' and for django.views.generic stuffs we use class right? Why they distinguished these two? This is error what I got. ImproperlyConfigured at /search/results ListView is missing a QuerySet. Define ListView.model, ListView.queryset, or override ListView.get_queryset(). urls.py from django.urls import path from django.conf import settings from django.views.generic import ListView, TemplateView from . import views app_name = 'search' urlpatterns = [ path('', TemplateView.as_view(template_name = "search/index.html")), path('results', ListView.as_view(template_name = 'search/results.html')), path('beerlist', views.beerlist, name='beerlist'), path('<int:beerinfo_id>', views.beerinfo, name='beerinfo'), ] views.py from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Q from django.views.generic import ListView, TemplateView from .models import Beerinfo # Create your views here. def index(TemplateView): template_name = 'search/index.html' def results(ListView): model = Beerinfo template_name = 'search/results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Beerinfo.objects.filter( Q(name__icontains = query) | Q(label__icontains = query) ) return obejct_list index.html <form action="{% url 'search:results' %}" … -
How to solve, dest virtualenv: error: the following arguments are required: dest error?
As the title says, I keep on having that error and I don't know how to solve it. The Error, as the title says is virtualenv: error: the following arguments are required: dest the command which I entered was virtualenv I am running this on MAC and on python -
How to properly configure Celery logging functionality with Django?
I use Django and Celery to schedule a task but I have an issue with the logger because it doesn't propagate properly. As you can see in the code below I have configured the Python logging module and the get_task_logger Celery module. import logging from celery import Celery from celery.utils.log import get_task_logger # Configure logging logging.basicConfig(filename='example.log',level=logging.DEBUG) # Create Celery application and Celery logger app = Celery('capital') logger = get_task_logger(__name__) @app.task() def candle_updated(d, f): logging.warning('This is a log') logger.info('This is another log') return d+f I use django-celery-beat extension to setup periodic task from the Django admin. This module stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime. As recommended in the documentation I start the worker and the scheduler that way: $ celery -A capital beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler celery beat v4.4.0 (cliffs) is starting. __ - ... __ - _ LocalTime -> 2020-04-02 22:33:32 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2020-04-02 22:33:32,630: INFO/MainProcess] beat: Starting... [2020-04-02 22:33:32,631: INFO/MainProcess] Writing entries... [2020-04-02 22:33:32,710: INFO/MainProcess] Scheduler: Sending due task Candles update (marketsdata.tasks.candle_updated) [2020-04-02 … -
Graphene says field name is invalid keyword
I'm using ModelFormMutation and Graphene says a field keyword is not valid, when itself is looking for those fields. I delete the field and error changed to another field 😬. -
DRF How to restrict (permissions) user by companies?
I mean User have a company and restrict views by companies. If user in company A he can't look on same view on company B. Any help with this? thx class Company(models.Model): name = models.CharField(max_length=255) class User(AbstractBaseUser): first_name = models.CharField(max_length=254) last_name = models.CharField(max_length=254) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) -
Django model method returning correct response when called from shell but not when called from template
models.py class player(models.Model): name = models.CharField(max_length = 100) rounds_played = models.IntegerField() rounds_missed = models.IntegerField() date_joined = models.DateTimeField(default = timezone.now) total_points = models.IntegerField() bio = models.TextField() user_ID = models.CharField(max_length = 10) user_m = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField(), def rounds_record(self): return int(100 * self.rounds_played / (self.rounds_played + self.rounds_missed)) def player_status(self): if self.is_active: return "Yes" return "No" def average_points(self): return int(self.total_points / self.rounds_played) def __str__(self): return self.name template snippet {% for player in players %} <div class = "grid-item"> {{player.player_status}} </div> {% endfor %} I'm developing a database web app (to learn django) in which players on a team and their statistics are tracked and stored in a psql database. When calling the player_status method from the manage.py shell it returns the correct response, say, for each user, 'yes', 'no'. However when the method is called from the template the method is returning 'yes', 'yes'. After some troubleshooting I found that it indeed is returning true for each response. What can I do to fix this problem. EDIT: I should specify I currently have 2 test users, one storing True and the other storing False in the is_active BooleanField -
NameError: name 'ProductTag' is not defined
models.py from django.db import models from django.contrib.auth.models import User class ActiveManager(models.Model): def active(self): return self.filter(active=True) class Product(models.Model): name = models.CharField(max_length=32) description = models.TextField(blank=True) price = models.DecimalField(max_digits = 5, decimal_places = 2) slug = models.SlugField(max_length=48) active = models.BooleanField(default=True) in_stock = models.BooleanField(default=True) date_updated = models.DateTimeField(auto_now=True) objects = ActiveManager() tags = models.ManyToManyField(ProductTag, blank=True) def __str__(self): return self.name class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE) image = models.ImageField(upload_to="product-images") thumbnail = models.ImageField( upload_to="product-thumbnails", null=True) class ProductTag(models.Model): name = models.CharField(max_length=40) slug = models.SlugField(max_length=48) description = models.TextField(blank=True) active = models.BooleanField(default=True) def __str__(self): return self.name def natural_key(self): return(self.slug,) The name error says ProductTag is not defined, whereas ProductTag itself a Class. I don't understand where I missed... appreciate for the help -
Getting info from django-debug-toolbar when using manage.py run_method?
Is there a way to get the information that django-debug-toolbar collects/compiles, namely the sql queries and their times, when running code via manage.py run_method? I can construct an artificial view around the code I am running, but it sure would be nice to just run my code directly. I swear I saw a SO question describing how to do this recently, but either I was mistaken or I'm unable to find it now.