Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when creating super user in Django custom user model
Django: 3.0.5 Python: 3.7.3 I am rather new to Django's framework and I have been trying to create a custom user model so that the default username is an email. However, I cannot seem to create a superuser. I keep getting this error after calling py manage.py createsuperuser: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\base.py", line 320, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\core\management\base.py", line 294, in create_parser self.add_arguments(parser) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 55, in add_arguments field = self.UserModel._meta.get_field(field_name) File "C:\Users\User\Dev\tryDjango\lib\site-packages\django\db\models\options.py", line 583, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named '' Below is the codes for my custom user model, I have also placed AUTH_USER_MODEL = 'accounts.User' in my settings.py. class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an Email address") if not password: raise ValueError("Users must have a Password") user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password=None): user = self.create_user( email, password=password ) user.staff = True user.save(using=self._db) return user def … -
Apache, Django and wsgi, No module named 'encodings'
I've looked through many stack overflow questions with the same issues, but none of them solved my issue. I'm trying to deploy Django on AWS - Ubuntu 18.04 using Apache and WSGI. When running my website with Django's servers on port 8000, everything works fine. Then when I attempt to run on apache I get the following error in my logs. Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations Command line: '/usr/sbin/apache2' (2)No such file or directory: mod_wsgi: Unable to stat Python home /var/www/html/projects/venv Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' As it says clearly mod_wsgi and Python 3 are configured. I am using a virtual environment. My project is located at: /var/www/html/project/venv/mysite My Apache conf file is configured as: <Directory /var/www/html/projects/venv/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-path=/var/www/html/projects/venv/mysite python-home =/var/www/html/projects/venv WSGIProcessGroup mysite WSGIScriptAlias / /var/www/html/projects/venv/mysite/mysite/wsgi.py Alias /static /var/www/html/projects/venv/mysite/polls/static <Directory /var/www/html/projects/venv/mysite/polls/static> Require all granted </Directory> I'm not sure where to go from here. I don't fully understand what the error means. I have Python installed in … -
Custom path parameter parsing drf-yasg and Django
I'm trying to force dry-yasg to properly parse parameters from path. Let's say we have path('users/<int:user_id>/', whatever.as_view(...)) In swagger docs it is not treated as int, but string instead I have used swagger_auto_schema(manual_parameters = [ openapi.Parameter( name, openapi.IN_PATH, description=desc, type=openapi.TYPE_INTEGER, required=True ) ] but it's pretty annoying. I could not find a function/method/class responsible for parsing that. Is there a simple method to change behaviour of this parser based on path, so that if int occurs then openapi.TYPE_INTEGER will be returned instead of string? -
I cant view my form inputs in the django database
iam a learner in django. i have created my first form, but when i input data i dont see it in my database but see in in my shell. I have rechecked my code but it seem fine, yet still it wont save in my code in the database. Please help me out here.Thanks. <pre> from django.db import models # Create your models here. class Login(models.Model): first_name = models.CharField(max_length=200) second_name = models.CharField(max_length=200) email = models.EmailField() password = models.CharField(max_length=200) <pre>`from django.http import HttpResponse from django.shortcuts import render from .models import Login from .forms import login_form # Create your views here. def homeview(request): return HttpResponse("<h1>Hello There</h1>") def login_view(request): form = login_form(request.POST or None) if form.is_valid: form.save context ={ "form":form } return render(request, "login.html", context) <pre># html code {% block content %} <form action="" method="GET">{% csrf_token %} {{form.as_p}} <input type="submit" value="Login"/> </form> {% endblock %} <pre># form code from django import forms from .models import Login # This is the form code. class login_form(forms.ModelForm): class Meta: model = Login fields = [ "first_name", "second_name", "email", "password" ] -
Opening AdminAction in new tab, Django
I have an AdminAction that generates pdf and I would like to open it in new tab. How do I do that? So far I have used a redirect from that AdminAction to a url to a view function, but I can't seem to connect the view function(url) to some . -
Why are some inputs not rendering in this Django ModelForm?
I just started learning Django and have the following issue. I created a form to update a table in my DB and it has two fields that are ForeignKeys in the model. This two fields are not showing up (brand and model) in the template, they have labels but there is not an input to it, while the other two have their labels and inputs. Here is my code models.py class Computer(models.Model): serialNo = models.CharField(max_length=128, unique=True) description = models.CharField(max_length=255, null=True) brand = models.ForeignKey(Cat_Brand, null= True, on_delete=models.CASCADE, blank = True) model = models.ForeignKey(Cat_Model, null= True, on_delete=models.CASCADE) class Cat_Brand(models.Model): name = models.CharField(max_length=128, null=False) is_active = models.BooleanField(default=True) def __str__(self): return self.nombre class Cat_Model(models.Model): name = models.CharField(max_length=128, null=False) is_active = models.BooleanField(default=True) def __str__(self): return self.nombre forms.py class ComputerForm(ModelForm): class Meta: model = Computer fields =['serialNo', 'description', 'brand', 'model'] views.py def add_computer(request): form =ComputerForm() if request.method == "POST": form = ComputerForm(request.POST) if form_bien.is_valid(): form.save() return redirect("home") return render(request, '/add_computer.html', {'form':form}) The html template: <form method="POST" id="add_form" action="{% url 'add_computer' %}">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Add"> </form> Thanks! -
Deploy django project with module that's working with cdll
i'm needed to deploy django project that's working with cdll, i tryed deploy with docker and IIS Connection manager, but this methods has been crashed my sensivity module. (I call delphy methods from python and i thinking that lock memory and i give an many exceptions). at now i run my django server manual and port forwarding to my local port from remote. Maybe you have an ideas for normal deploy this project. -
Error when checking input: expected dense_1_input to have 2 dimensions, but got array with shape (1, 150, 150, 3)
I am trying to predict using saved model but getting the error expected dense_1_input to have 2 dimensions, but got array with shape (1, 150, 150, 3). original = load_img(file_url, target_size=(150, 150)) numpy_image = img_to_array(original) numpy_image = numpy_image/255 model = tf.keras.models.load_model('my_model.h5') numpy_image = np.expand_dims(numpy_image, axis=0) #print(numpy_image) prediction = model.predict(numpy_image) Here is the Architecture of the CNN model model = Sequential() model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_WIDTH, IMG_HEIGHT, 3))) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.20)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.20)) model.add(Conv2D(128, (3, 3), activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.20)) model.add(Flatten()) model.add(Dense(1024, activation='relu')) model.add(BatchNormalization()) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) -
ERR_TOO_MANY_REDIRECTS when login Django
My django application worked fine before using django-hosts, something i miss in the authentication system or redirection, before this error I was getting Reverse for 'login' not found. 'login' is not a valid view function or pattern name. then I add django-hosts resolver helper reverse_lazy in the settings.py LOGOUT_REDIRECT_URL = reverse_lazy('login') LOGIN_URL = reverse_lazy('login') # info PARENT_HOST = 'localhost:8000' SCHEME = 'http' ROOT_URLCONF = 'mysite.urls' ROOT_HOSTCONF = 'mysite.hosts' DEFAULT_HOST = 'www' here is my hosts.py from django.conf import settings from django_hosts import patterns, host host_patterns = patterns('', host(r'www', settings.ROOT_URLCONF, name='www'), host(r'services', 'application.urls', name='services'), host(r'agent', 'agent.urls', name='agent'), host(r'counter', 'counter.urls', name='counter'), ) here is my login views from django_hosts.resolvers import reverse as host_reverse class Login(View): def get(self, request): data = request.GET if request.user: if request.user.is_staff: url = host_reverse('admin_dashboard', host='agent') return redirect(url) url = host_reverse('counter_pick', host='counter') return redirect(url) else: if data: user = authenticate(request, username=data.get('username'), password=data.get('password')) if user is not None: login(request, user) if user.is_superuser or user.is_staff: url = host_reverse('admin_dashboard', host='agent') return redirect(url) url = host_reverse('counter_pick', host='counter') return redirect(url) else: messages.error(request, 'Username or password incorrect') return redirect('login') return render(request, 'agent/login.html') Root urls from agent.views import Login, LogOut from django.views.decorators.csrf import csrf_exempt from application.views.views import Home urlpatterns = [ path('login/', Login.as_view(), name='login'), path('logout/', LogOut.as_view(), … -
what is ? in pagination hyper links
Hi im reading a book about django and in pagination template i see a ? but i do not know why is it there.I searched but got no answer. Here is the template : <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages }}. </span> {% if page.has_next %} <a href="?page={{ page.next_page_number }}">Next</a> {% endif %} </span> </div> what is the question mark in the address of page in ??? -
how get process status or exception in container when use django-extensions RunScript
When i use RunScript, can not restart container when script.py throw exceptions. how get process status or exception in container when use django-extensions RunScript? -
How to properly use custom user model in django, with custom templates instead of forms.py
Can any one please tell me how to use Custom User model in django, so that user can register from front end. Or is there any way of creating new table for storing users and use the authentication of user model with that custom model. -
django models table value not able to see in html
I have created a django app which the quizz answers are saved in db with usser name nd given answers by user. What changes I should made in the views.py to render values in html page named as x.html models.py class Quizz(models.Model): name = models.CharField(max_length=50,default='') ans1=models.CharField(max_length=20,default='') ans2=models.CharField(max_length=20,default='') ans3=models.CharField(max_length=20,default='') views.py def Index(request): if request.method=='POST': username=request.POST['username'] password=request.POST['password'] x=authenticate(username=username,password=password) if x is not None: login(request,x) return render(request,'x.html') else: return redirect('home') else: return render(request,'index.html') def test(request): if request.method=='POST': name = request.POST['name'] ans1=request.POST['sky'] ans2=request.POST['cricket'] ans3=request.POST['river'] x=Quizz.objects.create(name=name,ans1=ans1,ans2=ans2,ans3=ans3) x.save() return redirect('test.html') return render(request,'test.html') html template {{quizz.ans1}} -
Combine 2 CharFields to form an attribute
I want combine the first_name and last_name fields to create a full_name field. Which will then be used to create the slug. I get NameError: name 'self' is not defined with this code. class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50, null=True, blank=True) full_name = self.first_name + " " + self.last_name slug = AutoSlugField(null=True, default=None, unique=True, populate_from='full_name') -
Django Mptt : How to nest another Model
I have two Models, reseller and customer. I can generate Tree hierarchy for reseller, But I want to list down Customers under their immediate parent reseller. from django.db import models from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Reseller(MPTTModel): reseller_name = models.CharField(max_length=40) reseller_email = models.EmailField(max_length=70,blank=True) reseller_code = models.CharField(max_length=40) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['reseller_name'] def __str__(self): return self.reseller_name class Customer(models.Model): customer_name = models.CharField(max_length=40) customer_email = models.EmailField(max_length=70,blank=True) customer_code = models.CharField(max_length=40) parent = models.ForeignKey(Reseller, on_delete=models.CASCADE, null=True, blank=True, related_name='cust_children') def __str__(self): return self.customer_name Here is the order I'm aiming to: reseller1 -reseller2 -customer1 --reseller3 ----customer2 -
Is there any spesific way Django Url variables?
My Code is below, if I pass posts data via context, than i get "Reverse for 'user_profil' not found. 'user_profil' is not a valid view function or pattern name." without any "context", i get no error. I have read lots of the comments but no one points out this problem! If someone can help me , I will be pleasure! view function: def user_profil(request, username): posts = postList.objects.all().filter(author__username__icontains=username) context = {} context['posts'] = posts return render(request, 'profile.html', context=context) Url_patters: urlpatterns = [ path('profil/<username>/', postlist_view.user_profil, name='page_of_user'), ] <form method="post"><a href="{% url 'page_of_user' username=post.author %}"><h3>{{post.author}}</h3></a></form> profile.html: ` {{post.author}} ` -
Django tutorial, How can I send multiple arguments?
I know something like this has been asked before but I never seen any answer that I can understand or that works. But I am very new on Django so maybe I could have missed it. But there must be an easy answer to my question. I am following the tutorial for Django and at section 4 they use the httpresponseredirect to go to next page after posting a form. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) The views page function looks like this: def detail(request, question_id): My question is: How can I send more parameters to the function? -
Why Liked button changes back to Like button when comment is Liked
i am new in django, i am working on a website where users can post comment and also liked comment. I am using Ajax to avoid page reload when comment is liked. The issue i am facing, when a user like a comment, it display 'LIKED' from 'LIKE'. it worked perfectly using Ajax, but when i reload my browser the button changes from 'LIKED' to 'LIKE'. I am thinking this problem maybe in the views. How do i stop LIKED BUTTON from changing to LIKE BUTTON when i reload my browser? Template: ajax_like_comment.html <form action="{% url 'site:comment_like' %}" method="POST" id="user-comment{{ comment.id }}"> {% csrf_token %} {% if comment.liked_comment %} <button type="submit" name="comment_id" value="{{ comment.id }}" class="like-comment"> Liked</button> {% else %} <button type="submit" name="comment_id" value="{{ comment.id }}" class="like-comment"> Like</button> {% endif %} </form> Template: home.html {% for comment in post.comments.all %} <div class="row comment-row"> <div class="user-comment-text truncate card-meta dark-grey-text"> <a href="{% url 'site:profile-view' comment.user %}"> {{ comment.user.username }}</a> {{ comment.comment_post }} </div> <div id="user-comment"> {% include 'ajax_feeds_comments.html' %} </div> </div> Views.py @login_required def home_view(request): all_comments = Comments.objects.filter( Q(user=request.user, active=True)| Q(user__from_user__to_user=request.user, active=True)| Q(user__to_user__from_user=request.user, active=True)| Q(user__profile__friends__user=request.user, active=True)) posts = Comments.objects.filter(pk__in=all_comments) for comment in posts: print(comment) print(comment.likes.filter(id=request.user.id).exists()) if comment.likes.filter(id=request.user.id).exists(): comment.liked_comment = True else: comment.liked_comment … -
For what do we need object storage spaces for django application in production?
This is first time that I am hosting some of application on server. Its a Django application that is being served on Digital Ocean. I am seeing couple of toturials that are suggesting me to use S3 storage spaces for serving static and media files. I am not getting why do I need a separate storage space? Can't django own static and media folder serve the purpose? Can anyone clearify? -
Django how to show audio video and image in html template?
`class Post(models.Model): post_media = models.FileField(blank = True, null = True, upload_to = 'post_media_store') title = models.CharField(max_length = 100,) description = models.CharField(blank=True, max_length = 800) location = models.CharField(blank = True, max_length = 100) date_posted = models.DateTimeField(default = timezone.now) original_poster = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) def __str__(self): return self.title -
Django Rest Framework, user models getting error
My project is simple blog app where users can post,comment and like posts. I used Django default user registration page, later I add Djoser (third party token authentication for Django rest framework) with custom user model, it result in crash, please look into this please note that if I avoid custom user for Djoser,my project works fine,ie I am able to register using token and session authentication FORMS.PY #for Django's default register view from django import forms #from django.contrib.auth.models import User from .models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields=['username','email','phone','first_name','last_name','password1','password2'] MODELS.PY # Djoser Custom user model from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): email = models.EmailField(verbose_name='email' ,max_length=223,unique=True) phone=models.CharField(null=True,max_length=11) REQUIRED_FIELDS = ['username','phone','first_name','last_name'] #USERNAME_FIELD = 'email' def get_username(self): return self.email -
--noinput error when deploying Django project to Heroku
I am deploying my Django App on Heroku. I have followed quite a few tutorials, including the Heroku official one but with no luck. This the error message I get: Successfully installed Django-3.0.6 asgiref-3.2.7 certifi-2020.4.5.1 chardet-3.0.4 dj-database-url-0.5.0 django-crispy-forms-1.9.0 gunicorn-20.0.4 idna-2.9 psycopg2-2.8.5 pytz-2020.1 requests-2.23.0 sqlparse-0.3.1 urllib3-1.25.9 whitenoise-5.0.1 remote: -----> $ python Pur-Beurre/manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "Pur-Beurre/manage.py", line 21, in <module> remote: main() remote: File "Pur-Beurre/manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 130, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 316, in listdir remote: for entry in os.scandir(path): remote: NotADirectoryError: [Errno 20] Not a directory: '/tmp/build_d6b6d9fab362a0d21ea87ebd0f7a85e2/Pur-Beurre/pur_beurre/settings.py/static' remote: remote: ! Error while running '$ python Pur-Beurre/manage.py collectstatic --noinput'. remote: See traceback … -
Django pages not getting paginated
I'm using Django-filters to filter results. The filter is working correctly, but now the pagination is not working. It's being rendered, but now all the products are being displayed in one page. I was using paginate_by = 6 as it is a class based view. Even after filtering results, for example there are 8 products matching the filter, everything is being displayed in one single page. Why is it not working? Can anyone please help me out? Thanks in advance! My views.py: class homeview(ListView): model = Item template_name = 'products/home.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = ItemFilter(self.request.GET, queryset=self.get_queryset()) return context My index.html: <div class="card mb-4"> <div class="card-body"> <div class="container"> <form method="GET"> {{ filter.form|crispy }} <button type="submit" class="btn btn-primary mt-4">Filter</button> </form> </div> </div> </div> <h1>List Of Items</h1> <div class="row mb-4"> {% for item in filter.qs %} <div class="col-lg-4"> <img class="thumbnail" src="{{ item.image_url }}"> <div class="box-element product"> <h6><strong>{{ item.title }}</strong></h6> <h6 class="text-success">Category - {{ item.get_category_display }}</h6> <hr> </div> </div> {% endfor %} </div> -
not showinf models value in html template django
I just created a one app in which i created a db named as Quizz. User come and give a test on website. The answers and username get saved in db columns. Not able to show this table info in html page html page {% for post in data %} {{Quizz.ans1}} {% endfor %} views.py def test(request): if request.method=='POST': user = request.user ans1=request.POST['sky'] ans2=request.POST['cricket'] ans3=request.POST['river'] x=Quizz.objects.create(user=user,ans1=ans1,ans2=ans2,ans3=ans3) x.save() return redirect('home') return render(request,'test.html',) models.py class Quizz(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ans1=models.CharField(max_length=20,default='') ans2=models.CharField(max_length=20,default='') ans3=models.CharField(max_length=20,default='') class Meta: db_table = 'quizz' -
Clickable row in Table
I have a backend written in Django and I'm using REST API for connecting it with React frontend. I have a table that is fulfilled with data that I'm getting from my API. The question is how to make those rows clickable so when I click on table row I get more info about what that row represents. I would need to open a new page which will display more information about that specific row.