Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass the id of a model that is related to other model with a foreign key in the url of delete view in django framework
I have models alumni, graduation, and graduation project class Alumni(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.user) class Graduation(models.Model): faculty = models.CharField(max_length=120) degree = models.CharField(max_length=120) yearOfGraduation = models.CharField(max_length=120) groupNumber = models.CharField(max_length=120) alumni = models.ForeignKey(Alumni, on_delete=models.CASCADE, related_name='graduation') def __str__(self): return str(self.faculty) class GraduationProject(models.Model): title = models.CharField(max_length=120) description = models.TextField() mark = models.IntegerField(blank=True, null=True) gitLink = models.CharField(max_length=120) graduation = models.OneToOneField( Graduation, on_delete=models.CASCADE, primary_key=True, related_name='projects') def __str__(self): return str(self.title) and I made the update view and the delete view of the graduation and graduation project class GraduationUpdateView(UpdateView): model = Graduation template_name = "graduation_edit.html" fields = '__all__' class GraduationDeleteView(DeleteView): model = Graduation template_name = "graduation_delete.html" success_url = reverse_lazy('AlumniList') class GraduationProjectUpdateView(UpdateView): model = GraduationProject template_name = "graduation_project_edit.html" fields = '__all__' class GraduationProjectDeleteView(DeleteView): model = GraduationProject template_name = "graduation_project_delete.html" context_object_name = "project" success_url = reverse_lazy('AlumniList') and in my urls I wrote them this way path('/<int:pk>/graduation/edit/', GraduationUpdateView.as_view(), name='editGraduation'), path('/<int:pk>/graduation/delete/', GraduationDeleteView.as_view(), name='deleteGraduation'), path('/<int:pk>/graduation/project/edit', GraduationProjectUpdateView.as_view(), name='editProjGraduation'), path('/<int:pk>/graduation/project/delete', GraduationDeleteView.as_view(), name='deleteProjGraduation'), and in my templates when I pass the id of the user I don't know how to pass also the id of the specific project and the specific graduation, it deletes the all graduation instead of the graduation project, here is how I wrote it <a href="{% url 'editGraduation' … -
django export to csv only exports data from current page
I am trying to export a django Listview to csv. I created a view for a ListView, which has a custom get_queryset() function to create the filtered result. The Listview itself uses pagination for displaying the data. For the export i created a subclass, inheriting the Listview, with a custom url and a csv template file. The Listview and the export process itself works pretty fine, but i do not get the complete queryset in the csv, but only the data present on the first page of the paginated Listview. Any suggestions what i am missing? -
Django ManyToMany Relationship and Auto Add
I have two classes Post and Category. They work fine. However, when I add a post belongs some categories, I also want those categories should insert posts that i added. Models.py: class Category(models.Model): title = models.CharField(max_length=40, verbose_name='Category') posts_of_category = models.ManyToManyField('Post',related_name="+",auto_created=True) def __str__(self): return self.title class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE, verbose_name='Author') title = models.CharField(max_length=60) content = models.TextField(verbose_name='Content') category= models.ManyToManyField('Category', verbose_name='Category') date = models.DateField(verbose_name='Date', auto_now_add=True) post_img= models.ImageField() def __str__(self): return self.title And please see image : Screenshoot -
Is there a way to convert the uploaded excel file to CSV using django pre_save signal?
I would like to know if it is possible to convert the user selected excel file to CSV using django pre_save signals. Suppose a user uploads 'test.xlsx', I would like to convert that file automatically using the pre_save signal. Once the user uploads the file, it should actually be 'test.csv' in my FileField. -
Django MySQL throws an error, Library not loaded: /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib
Yes, this seems like a common error. But something else is wrong with my environment. I have upgraded from MySQL 5.6 version to 5.7. I can access mysql5.7 by typing mysql into the console. I have updated the DYLD_LIBRARY_PATH to reflect new 5.7 location git:(parent-child) ✗ echo $DYLD_LIBRARY_PATH /usr/local/opt/mysql@5.7/lib/: But the error for reason still says it is trying to load from 5.6 version. Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module> import MySQLdb as Database File "/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib Referenced from: /Users/vineeth/envs/automize2.0/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found Notice the error says it still is trying locate /usr/local/opt/mysql@5.6/lib/libmysqlclient.18.dylib I have reinstalled almost everything since this error came. Tried several solutions Python mysqldb: Library not loaded: libmysqlclient.18.dylib rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib Nothing seems to change its reference. How do I make it refer to the newer one which is in /usr/local/opt/mysql@5.7/lib/ Help is welcome. Been struggling since a day. -
SMTPSenderRefused at /password-reset/
I'm having this error, I'm using Ubuntu Linux os here I made env variable at a home section named ".bash_profile" in which I saved my Gmail and pass. Now the problem is when I'm calling them in settings.py file they don't work but instead of it if I try to put email and pass there, it works fine and I get the reset email. Things that I've already tried are- List item The same name of both the variables from the env variable and in settings.py I'm not using 2FA so I allowed the less secure app. Tried to use 2FA and followed the different process. Mail id in Django user and this user is the same. Already looked for the different answers on stack overflow and other sites. code are as follows settings.py """ Django settings for blog_page project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key … -
How to access users socialaccount email within django
I am currently trying to access google users email using the allauth libraries in django. I have had no trouble getting common @gmail domains emails but I am currently trying to login through a .edu based domain and cannot get the email from the request in views through request.user.email I can see in the social accounts section of the django admin site that the users with this different domains email is within the extra_data section, is there anyway to access this extra_data in the social account and extract the email and then assign the users email to their account within the django application? Sorry, if this isn't asked in the best possible way I'm fairly new to coding and very new to django. -
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 …