Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set a backend in django auth LoginView in urls.py
As I am using social_auth as well, how can I set the auth backend to LoginView? urls.py path('login/', django.contrib.auth.views.LoginView.as_view ( template_name='login.html', ), name='login'), settings.py AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.linkedin.LinkedinOAuth2', ) Some say that if the auth ModelBackend is before the social auth, it will go through it, somehow this is not working out. -
add custom action button in django admin
Now I'm working on deleting files from s3 at django admin page. I would like to delete files in s3 when I click 'remove' button that I added as a custom button. The 'remove' button is located next to file download link at django admin front page as shown in the following link (image): custom UI screenshot (step 1) When I click the 'remove' button, (step 2) I want to make the front-end admin page to send a request to the back-end web server which uses boto3 library. (step 3) Once the request arrives at the back-end, I want the boto3 to communicate with S3 so that the requested file is deleted in S3 side. (step 4) Then, S3 should respond to the boto3 back, saying the requested delete operation is done. To achieve these steps, I think I need to define/implement an interface in the web-server side and make the listener on the 'remove' button to send a request to the web-server side interface I created. However, I can't find a way to do so. Any suggestions or documentations that I can get some help on this issue? Here I give you the corresponding code section of admin.py file. … -
Using multiple slugs in urls.py
I'm trying to use two slugs in my urls but I keep getting Reverse for 'tithe' with arguments '(2018, 'February')' not found. 1 pattern(s) tried: ['tithe/(?P<year>[0-9]{4})-(?P<month>[\\w-])/$']. urls.py `from django.contrib import admin from django.urls import path,include,re_path from django.conf.urls import url from tithe import views from django.views.generic import RedirectView from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', RedirectView.as_view(pattern_name="account_login"), name="index"), path('accounts/', include('allauth.urls')), path('dashboard', views.Dashboard.as_view(), name='dashboard'), url(r'^tithe/(?P<year>[0-9]{4})-(?P<month>[\w-])/$',views.TitheView.as_view(), name='tithe'), ]` dashboard.html <a href="{% url 'tithe' currentYear realMonth %}" class="waves-effect"><i class="zmdi zmdi-format-underlined"></i> <span> Tithe </span> </a> -
django: search by ingredients
I'm creating a site where users can search for recipes for ingredients, but I can only search by typing 1 ingredient, when I type more than one, the search returns empty. The right search would be the user to insert multiple ingredients and return the recipes that contain those ingredients. I cannot find what's wrong :( Here are my models.py class Fotos(models.Model): id = models.AutoField(primary_key=True) linkfoto = models.ImageField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'fotos' class Ingredientes(models.Model): id = models.AutoField(primary_key=True) ingrediente = models.TextField() nomes = models.ForeignKey('Nomes', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'ingredientes' class Nomes(models.Model): id = models.AutoField(primary_key=True) # AutoField? nome = models.TextField() class Meta: managed = False db_table = 'nomes' views.py from django.shortcuts import render from .models import Ingredientes, Nomes, Fotos def post_list(request): termo_busca = request.GET.get('pesquisa') if termo_busca: a = Ingredientes.objects.all().filter(ingrediente__contains=termo_busca) # a = a.exclude(ingrediente__icontains=termo_busca!=termo_busca) busca = [p.nomes_id for p in a] lista = [] for i in busca: nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) else: a = Nomes.objects.all()[:10] cont = len(a) lista = [] for i in range(1, cont): nome = Nomes.objects.get(id=i) ingredientes = Ingredientes.objects.filter(nomes_id__in=[i]) foto = Fotos.objects.get(id=i) lista.append([nome, ingredientes, foto]) … -
Django: cannot update css changes
After running my server, my page doesn't show the updates that I've made in the CSS file. My navbar won't recognize a css rule: .navbar-bg {background-color: black;} (i've just tested this rule). However, If I paste this same HTML and CSS code in a site like CodePen it works (my navbar gets a black background). https://codepen.io/ogonzales/pen/KbKzQo The same happens if I run the HTML and CSS from a directory in my PC, so I think it has something to do with Django. What could it be? I've tried also this other answer: python manage.py collectstatic --noinput --clear from here without results: Django won't refresh staticfiles base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% block metadescription %}{% endblock %}"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {# <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css"#} {# integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">#} <title>Title</title> </head> <body> <div> <div class="container"> {% include 'navbar.html' %} <div class="container-fluid nav-bar-fixed-top my_top_navbar_div"> {% block content %} {% endblock %} </div> </div> {% include 'footer.html' %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="{% static 'js/jquery-3.2.1.slim.min.js' %}"></script> <script src="{% static … -
Many-to-many field vs New Model Django
I'm trying to make followers/following functionality and I've thought of two ways. I can't seem to find solution as to which one is the better way. Solution 1 class User(AbstractUser): followers = models.ManyToManyField('self', symmetrical=False) Solution 2 class Follow(models.Model): following = models.ForeignKey(User, related_name="who_follows") follower = models.ForeignKey(User, related_name="who_is_followed") follow_time = models.DateTimeField(auto_now=True) Thanks -
Error with Mysql datetime in django extract return None
Image captured when i try with django manage.py shell I try to extract month,day from Datetime field django model. But it return None. Help me. I have no idea. -
Created new project in django using virtualenv and its running fine but when I trying to create new app using 'startapp' and again running project
Created new project in django using virtualenv and its running fine but when I trying to create new app using 'startapp' and again running project by command : python3.6 advertisement/manage.py runserver localhost:8000 then throw error : Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f57db4171e0> Traceback (most recent call last): File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/ravinder/advertisement/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'core' Note : I already added app in setting.py installed app. Please help me to reoslve this issue. -
Why is my Django Unittest failing to load with "ImportError: Failed to import test module: tests"
I cannot figure out what I am doing wrong. I added this simple unit test: from django.test import TestCase from blog.myapp.models import * class AllTests(TestCase): def FooBarTest(self): foo1 = Foo.objects.create(name='foo1') bar1 = Bar.objects.create(name='bar1') FooBar.objects.create(foo=foo1,bar=bar1) foo_from_db = Foo.objects.filter(bar__id=bar1) self.assertEqual(foo1.id,foo_from_db.id) Here is my project layout: . ├── blog │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── myapp │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── 0001_initial.py │ ├── models.py │ ├── serializers.py │ ├── templates │ │ ├── myapp │ │ │ ├── index.html │ │ │ └── post_detail.html │ │ └── post_list.html │ ├── tests.py │ ├── urls.py │ └── views.py I am using PyCharm and here is how I have the test configured: Now when I run my test I get this output: Testing started at 6:21 PM ... C:\Users\plankton\PycharmProjects\blog\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2018.2\helpers\pycharm\_jb_unittest_runner.py" --target tests.AllTests Launching unittests with arguments python -m unittest tests.AllTests in C:\Users\plankton\PycharmProjects\blog\blog\myapp Error Traceback (most recent call last): File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor yield File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\case.py", line 615, in run testMethod() File "C:\Users\plankton\AppData\Local\Programs\Python\Python37-32\lib\unittest\loader.py", line … -
ManyToManyField relationship retrieving no data
I've one structure like this: 1. Author 2. Book 3. AuthorType 4. AuthorBookType A book can have more than one author, and it can have functions inside the book, Author, Co-Author, Part, Helper, Etc: class Book(models.Model): title=models.CharField(max_length=100) class Author(models.Model): name=models.CharField(max_length=100) books=models.ManyToManyField(Book, through='AuthorBookType') class AuthorType(models.Model): description=models.CharField(max_length=100) class AuthorBookType(models.Model): author=models.ForeignKey(Author, on_delete=models.CASCADE) book=models.ForeignKey(Book, on_delete=models.CASCADE) author_type=models.ForeignKey(AuthorType, on_delete=models.CASCADE) My database should looks like this: AUTHOR: __________________________ | ID | NAME | |========================| | 1 | Jhon Doe. | | 2 | Charles Albert | | 3 | Matt Greg | | 4 | Anne Engel | -------------------------- BOOK: __________________________ | ID | NAME | |========================| | 1 | Paradise City | | 2 | Profaned Apple | -------------------------- AUTHOR_TYPE: __________________________ | ID | DESCRIPTION | |========================| | 1 | Author | | 2 | Co-Author | -------------------------- AUTHOR_BOOK_TYPE: _____________________________________________ | ID | AUTHOR_ID | BOOK_ID | AUTHOR_TYPE_ID | |===========================================| | 1 | 1 | 1 | 1 | | 2 | 2 | 1 | 2 | | 3 | 3 | 1 | 2 | | 4 | 3 | 2 | 1 | | 5 | 4 | 2 | 2 | --------------------------------------------- On my views.py i did: class AuthorsListView(ListView) model = Author … -
Load a field in html template with data from a selected ChoiceField
I'm getting stuck in the next situation about loading in real-time a field in the template of Sale Model. I have two models (Item and Sale) related by a ForeignKey. Sale Model class Sale(models.Model): sale_item = models.ForeignKey(Item, on_delete=models.CASCADE) new_price = models.IntegerField() def saveSale(self): self.save() def __str__(self): return self.sale_item.name Item Model class Item(models.Model): name = models.CharField(max_length=40) desc = models.CharField(max_length=150) price = models.IntegerField(max_length=7) pic = models.ImageField(upload_to='items_store') element_choice = ( ('USB', 'USB'), ('PC', 'PC'), ('TEXT', 'Book'), ) element = models.CharField(choices=element_choice, max_length=10) stock = models.IntegerField() is_sale = models.BooleanField(default=False) def saveItem(self): self.save() def __str__(self): return self.name I created a form for the Sale Model class formSale(forms.ModelForm): sale_item = forms.ModelChoiceField(queryset=Item.objects.all(), label='sale_item') new_price = models.IntegerField(label='new_price') class Meta: model = Sale fields = ('sale_item','new_price') In my view, I can save the data of Sale form (loaded in template) just fine but I was in need of a real-time update of a new field called "Current Price" added in the template (it is not saved in the Model, is just to see the data) . It'll get loaded with the price inside the Item selected in the ChoiceField. Ex: I select "USB Reader" from the ChoiceField and the Current Field in the template will load with the price of … -
callback on delete from database?
My Django app uses Amazon S3 storage for the user's data files that they have uploaded. I store a pointer (using the uuid) to the file in the model: model.py: class Gedcom(models.Model): """Gedcom model.""" user = models.ForeignKey(User, on_delete=models.CASCADE) filename = models.CharField(max_length=100, default="") title = models.CharField(max_length=100, default="") uuid = models.CharField(max_length=36, default="") Is there a way to perform a callback of sorts when a gedcom item is deleted (say through either the admin interface or via my other code) that a method is called so that I can delete that file from S3? I could run a management function as part of a cron job that delete unlinked file on S3 if they no longer exist in the local database, but I'm wondering if there is another way to do this that is cleaner? -
Path does not redirect to the right page - Reverse for 'moviesofcinema' with no arguments not found
I am new to Django and I am building a website in which there are different Cinemas and each Cinema has several movies. I am having an issue regarding the path from a specific cinema to its movies. 1) In http://127.0.0.1:8000/cinemas/allcinemas the user can see all the cinemas in a card format 2) If the user clicks a card, he should be redirected to http://127.0.0.1:8000/cinemas/8/movies/moviesofcinema where he can see all the movies of that specific cinema. If I copy and past the links in the searchbar, they work. However, if I click in a cinema card, it does not redirect me to the page in which there are all the movies of that cinema. Instead I get the error message: Reverse for 'moviesofcinema' with no arguments not found with the highlighted error: <a href="{% url 'moviesofcinema' %}" > The error message is in the detailofcinema.html Such html page contails the cinema cards. In each cinema card I created a link so that if the user clicks it, he should be redirected to see all the movies of that specific cinema: <a href="{% url 'moviesofcinema' %}" > <p>Which are the movies offered by this cinema?</p> </a> My cinema urls.py is: from … -
Django m2m produce Unnecessary inner join, that change sql result.
Django 2.1.4 (the like behavior exist on 2.0.4 too) Models: class Application(models.Model): # many fileds name = models.CharField(max_length=255) seers = models.ManyToManyField('Agency', through='ApplicationAgencySeer') class ApplicationAgencySeer(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) agency = models.ForeignKey('Agency', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) now I wanna filter # count 0 Application.objects.filter(seers__agency__id='c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24').count() # 0 # but count 1 ApplicationAgencySeer.objects.filter(agency__id='c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24').count() # 1 SELECT * FROM "app_application" INNER JOIN "app_applicationagencyseer" ON ("app_application"."id" = "app_applicationagencyseer"."application_id") INNER JOIN "app_agency" ON ("app_applicationagencyseer"."agency_id" = "app_agency"."organization_ptr_id") INNER JOIN "app_agency" T4 ON ("app_agency"."organization_ptr_id" = T4."parent_id") WHERE T4."organization_ptr_id" = 'c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24' if remove INNER JOIN "app_agency" T4 ON ("app_agency"."organization_ptr_id" = T4."parent_id") all be right. i found the bug <djangoproject> but 6 years ago. I think it already fixes before 2.1.4 release. How to me compose right filter query, or avoid this situation. help me I am stuck. -
How to make django admin interface display the correct number for a (Big)Integer field (and not a rounded one)
I'm looking for a way to disable the rounding when displaying a number on the django (2.1) webinterface. Using images, here is what I see when I load the admin interface for an instance of my model: models.py : class DXXXXXUser(models.Model): dXXXXXd_id = models.BigIntegerField(primary_key=True, unique=True) # This is the field that get rounded when displayed on the admin interface abcd = models.CharField(max_length=200) efgh = models.IntegerField() # [...] -
Testing builtin `contrib.auth.login` with a Client.get() request
My goal : accessing the loging URL with Test Client with posting username/password to log a user in. I use built-in contrib.auth.login in Django 2.1.4 test.py : from django.contrib.auth.models import User from django.contrib import auth from django.test import Client from django.urls import reverse def test_login_valid(): U = {'username': 'bob','password': 'bobbobbob'} u = User.objects.create(**U) C = Client() r = C.post(reverse('login'), U) su = auth.get_user(r.wsgi_request) print(u) print(r) print(su) print(su.is_authenticated) print(r.wsgi_request.user) print(r.wsgi_request.user.is_authenticated) Running test: pytest --capture=no a14n/tests.py::test_login_valid (…) bob <TemplateResponse status_code=200, "text/html; charset=utf-8"> AnonymousUser False AnonymousUser False . registration/login.html: <form action="{% url 'login' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py: from a14n import views as a14n_views urlpatterns = [ path('signup/', a14n_views.signup, name='signup'), path('', include('django.contrib.auth.urls')), ] On the other hand in a Django shell it works perfect : >>> from django.contrib.auth.models import User >>> from django.test import Client >>> from django.contrib import auth >>> from django.urls import reverse >>> U = {'username': 'bob','password': 'bobbobbob'} >>> C = Client() >>> r = C.post(reverse('login'), U) >>> u = User.objects.create(**U) >>> su = auth.get_user(r.wsgi_request) >>> print(u) bob >>> print(r) <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/profile/"> >>> print(su) bob >>> print(r.wsgi_request.user) bob >>> print(r.wsgi_request.user.is_authenticated) True >>> print(su.is_authenticated) True Why tests gives ma a … -
A search bar in my web app that returns a list of results from my models in Django
I'm creating a web application that will allow people to search book titles, authors, publishers etc. from a a database. The database is loaded and ready to go in Django, but I'm struggling to find out how to proceed. I assume I need to create a webpage with a form that accepts keywords that the user wants to search for, but how do I then search the database (which Django file would this code go into?) for the keyword and output the result in a list? Sorry if this is super broad. If this is a common question, I can delete it. I would appreciate any help and/or links that could help. Thanks! -
Django "no handlers could be found for logger"
I am developing a Django application where I defined in settings.py (following the instruction of the official docs https://docs.djangoproject.com/en/2.1/topics/logging/ ) my logging config like that LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } Everything seems to work fine, I have my debug.log file created and I can see the requests and the query(if DEBUG mode) printed on it. Then, in my view I try to print manually something on it doing the following: import logging logger = logging.getLogger(__name__) logger.error("example") But, when this gets called, I got "no handlers could be found for logger 'package.className' " and nothing gets printed in my file. I don't really get why. My understanding was that the logging called in the view should automatically take the configuration from the settings.py . Am I missing something? -
How to post data with HttpResponseRedirect in Django?
How to post data with HttpResponseRedirect? def response_change(self, request, obj): ### response if "_peer-test" in request.POST: url = request.POST.get('obj', '/export') return HttpResponseRedirect(url) The first line def response_change(self, request, obj): has data so if i type obj.name I wil get dat object. What I want is to redirect to another view en post de information. -
Querying from sql with dynamic model name and fields in Django
I'm new in Django and struggling with some dynamic solutions. I am trying to make an application that user can create table from UI and import data into this table from flat file and then user can be able to browse that data by clicking url(for example, if user create a table for employee, then user should be able to have a url like this for employee : localhost/employee). I will work on import part later but for now, i am trying to find a solution to browse data. And below query is almost do this. But i am not able to use alias instead of column names. Is there any way to build something like that dynamic? def employee(request): entries = Employee.objects.annotate(First Name=F('FirstName')). only('FirstName','Email') print(entries) return render_to_response('employee.html',{'employees': serializers.serialize("json",entries, fields=('First Name','Email'))}) Above query give me below result. I have only email information here. So there is no First Name because annotate is not working. [{"model": "client.employee", "pk": 1, "fields": {"Email":"employe1@gmail.com"}}] -
Django REST Framework NOT NULL constraint failed
when I try to create a new Post by posting the following JSON: { "text": "test", "location": 1 } I get the following error: NOT NULL constraint failed: grapevineapp_post.location_id models.py: class Location(models.Model): name = models.CharField(max_length=80) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Post(models.Model): text = models.CharField(max_length=512) owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) location = models.ForeignKey(Location, related_name='posts', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text views.py: class PostList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer Serializers.py class PostSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) text = serializers.CharField(required=False, allow_blank=True, max_length=512) owner = serializers.ReadOnlyField(source='owner.username') location = serializers.PrimaryKeyRelatedField(many=False, read_only=True) def create(self, validated_data): return Post.objects.create(**validated_data) def update(self, instance, validated_data): instance.text = validated_data.get('text', instance.text) instance.location = validated_data.get('location', instance.location) instance.save() return instance class UserSerializer(serializers.ModelSerializer): posts = serializers.PrimaryKeyRelatedField(many=True, queryset=Post.objects.all()) class Meta: model = User fields = ('id', 'username', 'posts') DB has already been cleared. Locations have been created by using the admin interface. I know that the issue is something trivial, but I just can't get it to work. -
Django many-to-many relationship between interests and users
I am trying to build a matchmaking website in Django. The main idea is to match users with the most interests in common. Thus, I have created a Hobby class and a Profile class. They are linked through a many-to-many relationship. However, I am doing something wrong because a user can select a Hobby multiple times. For example, Fishing can be added 'n' times. Also, I have to add the Hobbies in Django admin explicitly and only afterwards, the users can choose hobbies when registering. Below is the models.py file: class Hobby(models.Model): HOBBIES = ( ('Skiing', 'Skiing'), ('Fishing', 'Fishing'), ('Hunting', 'Hunting'), ('Golf', 'Golf'), ('Reading', 'Reading'), ('Football', 'Football'), ('Automobiles', 'Automobiles'), ('Fitness', 'Fitness'), ('Politics', 'Politics'), ('Fashion', 'Fashion'), ('Art', 'Art') ) hobby = models.CharField(choices=HOBBIES, max_length=20, null=True) def __str__(self): return self.hobby class Profile(models.Model): ..... ..... hobby = models.ManyToManyField(Hobby) Besides that, when I try to display the hobbies associated with the user I get the following: Hobby.None. Thanks in advance! -
getting name error when try to define urls in Django
I want to define URLs in Django but get an error: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), ] the error is: nameError(name'view' is not defind) please inform me. thanks, Saeed -
Adding html to a crispy form in django
I want to customize one of my fields from my form. I would like to add a span tag to one of the input fields and apply a div and some classes. How do I apply these changes to a form rendered with crispy forms? -
AttributeError: '__proxy__' object has no attribute 'set_attributes_from_name' when using ArrayField in Django
I tried setting lazy translations in my models for an ArrayField. Something like this: from django.utils.translation import gettext_lazy as _ class MyModel(models.Model): choices = ArrayField( _('choices'), models.CharField(max_length=255), blank=True, null=True, help_text=_('Comma-delimited list.') ) However, I get this error: AttributeError: '__proxy__' object has no attribute 'set_attributes_from_name' Should it be verbose_name instead, and if so, why? ArrayFields are not relations.