Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
how to Set default value for author field in django form using views.py
Im developing a social website I have problem in creating new post I don't know how set author name as default of logged in user it always give option for all the previously logged in users I want to make it default for the logged in user I don't know how to set default value for that author field views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post forms.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author','title','text','Post_image') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent '}) } modesls.py class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() Post_image= models.ImageField(upload_to='media' ,blank=True ,editable=True) created_date = models.DateTimeField(default=timezone.now()) published_date = models.DateTimeField(blank=True,null=True) -
(Django) Creating a simple website with account signup/login WITHOUT using the basic Django auth/admin/csrf modules
I am supposed to make a basic Django app that receives user info(username, password, name, email) and checks they exist in the database already and returns 200 status if the info matches the one in the database. Also, if the database does not have such info, it should receive it on its signup page and stores in its database. The tricky part is that I am not supposed to use the Django functionalities like auth or admin or csrf. So basically, I have to emulate the Django functions from scratch. Below are what I have been working on so far. The project name is second_try directories account/models.py from django.db import models class Users(models.Model): username = models.CharField(max_length = 50) password = models.CharField(max_length = 300) email = models.CharField(max_length = 50) name = models.CharField(max_length = 50) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) def __str__(self): return self.objects.all() account/views.py import json from django.views import View from django.http import JsonResponse from .models import Users from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'index.html' class SignUp(TemplateView): template_name = 'signup.html' class AccountView(TemplateView): def post(self, request): data = json.loads(request.body) Users( username = data['username'], password = data['password'], email = data['email'], name = data['name'] ).save() return JsonResponse({'message':'SUCCESS'}, … -
How do I get the results of a multiple choice field from Django?
I set up a model multiple choice field, where a user can select multiple choices. I want to be able to get the choices that a user selected when filling out the form. What can I call to get the results that the user picked? Also, how would I iterate over those results (what does it return)? Here's the field: CHOICES = MyMultipleModelChoiceField(queryset=MODEL.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) Thanks! -
How to filter in Django DB based on calculations from different tables
I have 3 models from 3 different tables: class Profiles(models.Model): player_name = models.CharField(max_length=150) player_surname=models.CharField(max_length=200) class Meta: db_table='profiles' class Results_2019(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2019' class Results_2018(models.Model): player_name = models.CharField(max_length=150) profiless=models.ManyToManyField(Profiles) first_score=models.DecimalField(decimal_places=2,max_digits=1000) second_score=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='results_2018' The database is static. Player in all three models have the same names =['Alex','Chandler','Zach'] and they all have data belonging to them for all columns ( first_score,second_score) Profiles database look like : id player_name player_surname 1 Alex Chapman 2 Chandler Wellington 3 Zach Berg Results_2019 database look like : id player_name first_score second_score 1 Alex 70 68 2 Chandler 60 62 3 Zach 90 85 Results_2018 database look like : id player_name first_score second_score 1 Alex 78 81 2 Chandler 56 66 3 Zach 97 95 I want to apply statictic analysis to players which involves math calculation based on values from Results_2019 and Results_2018 such as i want to get: - players whos growth in first_score and second_score in 2019 and in 2018 were more than 20% and then get the name and surnames who met these criteria and print in template. The below formula of criteria though does not work i show as guidance of what i want to … -
Filtering django querysets
In a project I have a view wich displays in the browser as a searchbar to search recipes. I think there is a better way then how I'm doing it right now, but have no idea how. If I don't do what I'm doing right now, I get the error that you can't filter with None. I know I could use a try exept but then none of the values may be None or an error is raised. class SearchResultListViewOther(ListView): model = Recipe template_name = 'recipes/search_other.html' extra_context = { 'time': time, 'categorie': categorie, 'continent': continent, } def get_queryset(self): """ Filter out recipes by some other params like the title """ # Can not filter on None so set a value if no search params were given title = self.request.GET.get('title') if not title: title = '0' time_recipe = self.request.GET.get('time') if not time_recipe: time_recipe = 0 continent_recipe = self.request.GET.get('continent') if not continent_recipe: continent_recipe = '0' object_list = Recipe.objects.filter( Q(title__icontains=title) | Q(time__lte=time_recipe) | Q(continent__exact=continent_recipe) ) return object_list -
Docker Pytest containers stay up after completing testing process
I've set my django project and now I'm trying to test it with pytest. What is issue running pytest withing my containers doesn't kill it at the end of the process. So at the end of day I'm stuck with multiple running containers from pytest and often postgreSql connection problems. My docker-compose file: version: '3' services: license_server: build: . command: bash -c "python manage.py migrate && gunicorn LicenseServer.wsgi --reload --bind 0.0.0.0:8000" depends_on: - postgres volumes: - .:/code environment: DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" env_file: .env ports: - "8000:8000" restart: always postgres: build: ./postgres volumes: - ./postgres/postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_PASSWORD: postgres DATABASE_NAME: "${DATABASE_NAME}" DATABASE_USER: "${DATABASE_USER}" DATABASE_PASSWORD: "${DATABASE_PASSWORD}" DATABASE_PORT: "${DATABASE_PORT}" DATABASE_HOST: "${DATABASE_HOST}" command: "-p 8005" env_file: .env ports: - "127.0.0.1:8005:8005" restart: always nginx: image: nginx:latest container_name: nginx1 ports: - "8001:80" volumes: - .:/code - ./config/nginx:/etc/nginx/conf.d depends_on: - license_server What I want to achieve is automatically closing containers after the testing process is finished.