Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot deactivate venv using 'conda deactivate' or 'deactivate' command
I've tried all these options but can't deactivate the virtual environment. (venv) C:\Users\dell\PycharmProjects\WeatherApp>deactivate DeprecationWarning: 'deactivate' is deprecated. Use 'conda deactivate'. (venv) C:\Users\dell\PycharmProjects\WeatherApp>conda.bat deactivate (venv) C:\Users\dell\PycharmProjects\WeatherApp>conda deactivate venv deactivate does not accept arguments remainder_args: ['venv'] (venv) C:\Users\dell\PycharmProjects\WeatherApp>conda deactivate (venv) C:\Users\dell\PycharmProjects\WeatherApp> -
how to django link url to decoupled react app
I have built my app with django as the backend and react as the frontend. I want to keep the two decoupled. However, I have an use case where I want to link from django to my react app. The frontend and backend will be hosted on different domains. While sending a password reset email, I need to link to a react page. The url is localhost:3000/reset/{code_here}/ I need to include this URL in an email (from the backend). I am not sure of what the best way to do this is. Should I hardcode the URL into my emails? Or is there any better way to achieve this? -
Auto logout specific users in Django
I know that we can implement auto logout with SESSION_COOKIE_AGE variable, but this method apply to all users. My question is: What is the best practice for implement auto logout system for specific users such as admin's or super admin's? -
Cannot execute runserver in Django VScode
I am using VScode to learn Django. I initially set up a virtual environment with Python 3.9. When I type python in Mac's terminal. It displays "python3.9" without any issue. However, when I type the same command in the terminal embeded in VScode. It shows python2.7 as below. Is it a problem of VScode or the settings? I am learning Django right now and when I run the command: python manage.py runserver It shows the error as below. I doubt that two issues were related, but cannot resolve it. Could anyone help me out? Tons of thanks. File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax -
How to get name instead of id in django queryset
I need to get customer_name but it returns id and please advise how to update my queryset to the related value class Orders(models.Model): customer_name = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Products, on_delete=models.CASCADE) qty = models.IntegerField() date = models.DateField(auto_now_add=timezone.now) def __str__(self): return "{}".format(self.customer_name) def get_absolute_url(self): return reverse('customer-orders', kwargs={'customer_name': self.customer_name}) and this is the view.py class OrdersListTotal(SuperuserRequiredMixin, ListView): model = Orders, User template_name = 'orders/orders_list_total.html' #<to change the template name to a existing one> context_object_name = 'orders' paginate_by = 10 def get_queryset(self): orders = Orders.objects.values('customer_name', 'product').annotate(qty=Sum('qty')) return orders and it returns id instead of customer name in html <table id="order-table" class="order-table"> <thead> <tr> <th></th> <th>Customer Name</th> <th>Product</th> <th>Qty</th> </tr> </thead> <tbody> <tr> <td></td> <td><a class="mr-2">{{ order.customer_name }}</a></td> <td><a class="mr-2">{{ order.product }}</a></td> <td>{{ order.qty}}</td> </tr> </tbody> -
Unable to create superuser after creating CustomUser and Manage in Django by using createsuperuser command?
I am working on a small Django project and stuck in very strange situation. I have create a CustomUser instead of using User available in Django itself, and implemented a CustomUserManager. First i am unable to create superuser by running python manage.py createsuperuser command,whenever i am running the command Django is not showing default console in terminal to create superuser, it showing me the following console:- enter image description here And when i tried to login in admin it says**:-** Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive. When i tried to create superuser by running the following script in shell i get AttributeError: Manager isn't available; 'auth.User' has been swapped for 'loginsignup.CustomUsers' >>> from django.contrib.auth.models import User >>> User.objects.create_superuser('admin', 'admin@gmail.com', 'pass') I am posting codes which i found useful to be here:- Model.py:- from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models from loginsignup.manager import CustomUserManager # Create your models here. class CustomUsers(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=40, unique=True) email = models.EmailField() password1 = models.CharField(max_length=10, blank=False) # is_admin = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] manager.py:- class CustomUserManager(BaseUserManager): def create_user(self, username, email, password, **other_fields): email = … -
django calculation problem with transaction
def createOrder(request, pk): OrderFormSet = inlineformset_factory(Manager, Order, fields=('product', 'status','count'), extra=10) manager = Manager.objects.get(id=pk) inventory = Inventory.objects.get(id=pk) current_amount = inventory.current_amount order = Order.objects.get(id=pk) count = order.count status = order.status formset = OrderFormSet(queryset=Order.objects.none(),instance=manager) if request.method == 'POST': formset = OrderFormSet(request.POST, instance=manager) if formset.is_valid(): formset.save() with transaction.atomic(): if status == 'Entering': current_amount-=count else: current_amount+=count inventory.save() return redirect('/suhyun/') context = {'form':formset} return render(request, 'accounts/order_form.html', context) #this is my code.. i want to calculate current_amount depending on the status when i create order and submit count in order table so.. how can i do that? -
Django Forms AttributeError 'NoneType' object has no attribute 'disabled'
I keep having trouble with a custom Django form that I am trying to implement. I really didn't know any way for getting the data from the frontend besides trying to pull the data by force through request.POST.get(), but once I started doing that I ran into an AttributeError that kept saying 'NoneType' object has no attribute 'disabled', and the error referenced the form.save() line as the problem in my views.py. Here is the code for the views.py @login_required def volunteer_instance_creation(request): form = VolunteerInstanceForm(request.POST or None, request.FILES) values_dict = { "organization": request.POST.get('organization'), "supervisor_Name": request.POST.get('supervisor_Name'), "supervisor_Phone_Number": request.POST.get('supervisor_Phone_Number'), "volunteering_Duration": request.POST.get('volunteering_Duration'), "volunteering_Date": request.POST.get('volunteering_Date'), "description": request.POST.get('description'), "scanned_Form": request.POST.get('scanned_Form'), } for i in values_dict: form.fields[i] = values_dict[i] if form.is_valid: obj = form.save(commit = False) obj.student_id = get_student_id(str(User.objects.get(pk = request.user.id))) obj.grad_year = get_grad_year(str(User.objects.get(pk = request.user.id))) obj.save() return redirect("submission_success") return render(request, "members_only/yes_form.html") Here is my models.py class VolunteerInstance(models.Model): student_id = models.CharField( blank = True, editable = True, default = 'No Student ID Provided', max_length = 255 ) grad_year = models.CharField( blank = True, max_length = 255, default = 'No Graduation Year Provided', editable = True ) organization = models.CharField( blank = False, max_length = 255 ) description = models.TextField( blank = False, ) supervisor_Name = models.CharField( blank … -
Django AbstractBaseUser Authentication-Login
this is my views.py file def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('user_home_url') else: messages.info(request, 'invalid username and password') return redirect('user_login_url') models.py class User(AbstractBaseUser, PermissionsMixin): """Database Model for storing users profile""" first_name = models.CharField(max_length = 15) last_name = models.CharField(max_length = 15) email = models.EmailField(max_length = 35, unique = True) username = models.CharField(max_length = 35, unique = True) is_active = models.BooleanField(default = False) is_staff = models.BooleanField(default = False) password = models.CharField(max_length = 25) phone = models.CharField(max_length = 13, null = False, blank = False, unique = True) phone_verified = models.BooleanField(default = False) otp = models.IntegerField(null = True) objects = UserProfileManager() USERNAME_FIELD='username' REQUIRED_FIELDS=['password','email','phone','first_name','last_name'] def get_full_name(self): """return full name of user""" return self.first_name + self.last_name def __str__(self): """return string representation of user""" return self.email settings.py AUTH_USER_MODEL = 'Users.User' Tried different methods using authenticate method but always getting invalid username and password def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] users = User.objects.all() for user in users: if user.email == email and user.password == password: return redirect('user_home_url') when I use this code in views.py instead of "authenticate" method it's working perfectly but the … -
How to remove catalogue from url string
What are the best method to have this url structure namedomain.com/ instead of namedomain.com/catalogue for Django Oscar. Do I have to create new app call frontpage or can I edit the myshop/urls.py such as this line? path('', include(apps.get_app_config('oscar').urls[0])), -
ValueError at /accounts/register The given username must be set
veiws.py from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth from django.contrib import messages from travello.models import Destination import traceback from django.core.files.storage import FileSystemStorage # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request,user) return redirect("/") else: messages.info(request,'invalid credentials') return redirect('login') else: return render(request, 'login.html') def register(request): if request.method == "POST": first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'EMAIL taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password1, first_name=first_name, last_name=last_name) user.save(); print("User created") return redirect('login') else: messages.info(request,'password not matching...') return redirect('register') else : return render(request, 'register.html') def logout(request): auth.logout(request) return redirect('/') def postdestination(request): if request.method == 'POST': try: f = request.FILES["img"] fs = FileSystemStorage() filename = fs.save(f.name, f) uploaded_file_url = fs.url(filename) name = request.POST['name'] # img = request.POST['img'] description = request.POST['description'] price = request.POST['price'] offer = request.POST.get('offer') if offer == "on": offer = True else: offer = False d = Destination.objects.create(name=name, desc=description,img=uploaded_file_url,price=price,offer=offer) d.save() except Exception as e: traceback.print_exc() return redirect('/') else: return render(request, 'post_destination.html') while registering this error is coming.how … -
Is it a bad practice not to use django forms?
I have watched a lot of django tutorials where some use the plain html form and some use django forms and model forms. Personally, I like using the plain html form because of the ease of customization. Other than validation, I don't really see any other advantages to using django forms. So, i just wanted to ask if it is a bad practice to use html forms rather than django forms? -
docker and django, DisallowedHost at / Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS
ubuntu 20.04 in the docker container python 3.8 after running the Django server python manage.py runserver In the browser, it said allowed_host I have changed the allowed host, restart the container, restart the django server, but the browser continuesly said "You may need to add '127.0.0.1' to ALLOWED_HOSTS." changed allowed host I have tried ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS = ['127.0.0.1','localhost'] Neither of them worked Also I have tried this which is also not working for me python manage.py runserver --insecure -
Pass a value from view.py to a url link in html
I am working on CS50 Web Development on the lesson of Django. I want to pass a string from view.py to HTML as the URL link here is the view.py def layout(request, name): randompage = random.choice(util.list_entries()) return render(request, "encyclopedia/layout.html", { "randompage": randompage}) and this is the HTML page <a href={% url "wiki/{{randompage}}" %}> Random Page </a> the error code is NoReverseMatch at / Reverse for 'wiki/{{randompage}}' not found. 'wiki/{{randompage}}' is not a valid view function or pattern name. I know I shall you templatetag URL, but I don't really understand how it works and I cant find anyone have a similar situation with me. -
What are the ways to make it possible to change contents of homepage through django admin?
I want to make it possible to easily modify the contents of my django site's homepage(and other pages too) through admin page directly. If I had multiple records of each instance I would definitely create a database model for it, which can then easily be modified through admin panel. But for things like the banner image, site description etc. which only have a single instance, am I supposed to have a database model with a single row or is there some better implementation for it? -
How to upload PDFs in Django-CKEditor?
I am trying to upload PDFs file in CKEditor for Django. Here are my settings in settings.py: CKEDITOR_CONFIGS = { 'default': { 'removePlugins': 'stylesheetparser', # Toolbar configuration # name - Toolbar name # items - The buttons enabled in the toolbar 'toolbar_DefaultToolbarConfig': [ { 'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', "BGColor"], }, { 'name': 'clipboard', 'items': ['Undo', 'Redo', ], }, { 'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', 'Outdent', 'Indent', 'HorizontalRule', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', ], }, { 'name': 'format', 'items': ['Format', ], }, { 'name': 'extra', 'items': ['Link', 'Unlink', 'Blockquote', 'Image', 'Update', 'Table', 'CodeSnippet', 'Mathjax', 'Embed', ], }, { 'name': 'source', 'items': ['Maximize', 'Source', ], }, ], # This hides the default title provided by CKEditor 'title': False, # Use this toolbar 'toolbar': 'DefaultToolbarConfig', # Which tags to allow in format tab 'format_tags': 'p;h1;h2', # Remove these dialog tabs (semicolon separated dialog:tab) 'removeDialogTabs': ';'.join([ 'image:advanced', 'image:Link', 'link:upload', 'table:advanced', 'tableProperties:advanced', ]), 'linkShowTargetTab': False, 'linkShowAdvancedTab': False, # CKEditor height and width settings 'height': '250px', 'width': 'auto', 'forcePasteAsPlainText ': True, # Class used inside span to render mathematical formulae using latex 'mathJaxClass': 'mathjax-latex', # Mathjax library link to be used to render mathematical formulae 'mathJaxLib': 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_SVG', # Tab = 4 spaces … -
Beautiful soup question, for loop problem
#Well this is my code and i have no idea why doesnt it show more results on the page, its grabs the price, link, title but shows 1 result, ident is ok, no erros, tried all the containers from find all , still one result, can you please advise me the mistake.Benn through this for a week import requests from bs4 import BeautifulSoup from django.shortcuts import render from urllib.parse import quote_plus #adding plus sign in search from . import models BASE_URL = 'https://www.olx.ua/list/q-{}' def home(request): return render(request,'base.html') def new_search(request): search=request.POST.get('search') #pull data out of search bar # that post request we are fetching #search model gives to searches to database models.Search.objects.create(search=search) #model creating search object with search argument is search and feeds to search request final_url = BASE_URL.format(quote_plus(search)) # response = requests.get(final_url) data= response.text #spit out text soup= BeautifulSoup(data, features='html.parser') final_postings= [] post_listings = soup.find_all("div", class_="rel listHandler") for post in post_listings: #looping through each post and show text post_titles = post.find('a',class_= ['marginright5 link linkWithHash detailsLink', 'marginright5 link linkWithHash detailsLink linkWithHashPromoted', ]).text post_url = post.find('a',class_= ['marginright5 link linkWithHash detailsLink', 'marginright5 link linkWithHash detailsLink linkWithHashPromoted']).get('href') if post.find('div',class_= 'space inlblk rel'): post_price = post.find('div',class_= 'space inlblk rel').text else: post_price= 'N/A' if post.find('img',class_='fleft').get('src'): post_image= … -
Django admin can't access to specific items
I'm working in Django with a model (Check) with foreign key. client_id = models.ForeignKey(Client, on_delete=models.CASCADE) Everything works fine with a regular admin register, but when I use class ChecksAdminSite, it crashes. Here is the Client model: class Client (models.Model): def __str__(self): return self.name + ' '+ self.surname name = models.CharField(max_length=120) surname = models.CharField(max_length=120, null=True) phone = models.PositiveIntegerField(null=True) mail = models.EmailField(null=True) sport = models.TextField(blank=True, null=True) gender_options=( ("F", "femenino"), ("M", "masculino"), ) gender = models.CharField(max_length=120, null=True, choices=gender_options) birth = models.DateField(null=True) def get_absolute_url(self): return reverse("clientes:cliente", kwargs={"client_id": self.id}) pass So, when I get into the admin specific item, it displays the following error: Field 'id' expected a number but got <Client: Juan Orjuela>. (Juan Orjuela is the name and the surname of that specific item). I just can't seem to find a solution or error. Can someone help me? Thanks! -
Django form missing none required field
I have a django admin form. The model contains a single field, called calculated. The calculated value is detemined by querying the database and performing some complex logic depending on the selection of some other field the user selects from a select box called pickme. So to make it much easier for the user, when they wish to alter an instance of the model, they select a pickme, and the system automatically calculates the required calculated field. The following code works for editing existing entries, however when I add a new entry, when I click save in the django admin interface it fails with ValueError: 'FooForm' has no field named 'calculated'. The error is raised within the Form._post_clean() method. I suspect it is because the form is not posting the value of calculated so it thinks its not a field. Looking at djangos code python3.8/site-packages/django/forms/forms.py, within _post_clean(): There seems to be a block that creates a DB instance: try: self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude) except ValidationError as e: self._update_errors(e) And then a block that cleans the instance, this is where it fails: try: self.instance.full_clean(exclude=exclude, validate_unique=False) except ValidationError as e: self._update_errors(e) I could try override _post_clean but it seems extremely … -
How do I inject an HTML string into executable html with Javascript?
I am using the Django framework to create a web app, and I am passing a variable which is a string of html (like 'hello world') to a template. In my template I create a to inject this string into actual executable html rather than text, which is where my error is occuring. It seems either there is something wrong with my injection code, something wrong with my use of Jinja to import the html string, or that this is the wrong way of doing things. Here is my current code: HTML (Javascript) <script> var htmlWrapper = document.querySelector('#graph_input'); var htmlstring = {{figure}}; htmlWrapper.innerHTML = htmlstring; </script> Views def home(request, symbol): file = open('saved_model_weights', 'r') model_json = file.read() loaded_model = model_from_json(model_json) loaded_model.load_weights('h5_file') predictions = loaded_model.predict(test) fig = Figure() ax = fig.subplots() ax.plot(predictions, linewidth=0.7) ax.plot(close, linewidth=0.7) ax.set_title(symbol) figure = mpld3.fig_to_html(fig) return render(request, 'mysite/home.html', {'figure': figure}) ^ figure is the html string I want to execute in my template, which is generated by mpld3.fig_to_html(), a matplotlib library to translate graphs into. -
ImportError: attempted relative import with no known parent package in Django
I have this folder structure: This is the full error message: Traceback (most recent call last): File "d:\jaime\Coding\Django\MyProjects\horus\app\core\erp\tests.py", line 1, in <module> from .models import Type ImportError: attempted relative import with no known parent package And this is the code: # from .models import Type from app.core.erp.models import Type t = Type(name="aaaa") print(t) And when in the erp tests.py I import my "Type" model, it gives me the title error, I don't understand what is wrong. -
Working wtih django sessions the right way
i was working with Django sessions and it was good until i wanted to modify it and explore it more. i have this code request.session['username_stored_in_session'] = user_name request.session['password_stored_in_session'] = pass_inp where it stores the username and the password on login if the user is using 2fac auth and redirect him to check the 2fac code and use them to auth the user if the code is correct, now i want to set expiry date to those sessions and how to secure them etc cause i'm planing on using them more, i know how to delete them using del and calling them, but not how to use expiry_date() and all the stuff on Django session docs. Thanks. -
Django - MongoDb - GraphQL query returning an empty array
This my first time using graphQL. I'm using django along with mongodb. this is my models.py from djongo import models class Car(models.Model): name = models.CharField(max_length=100) this is my schema.py import graphene from .models import Car from graphene_django import DjangoObjectType class CarType(DjangoObjectType): class Meta: model = Car fields = "__all__" class Query(graphene.ObjectType): allcar = graphene.List(CarType) def resolve_allcar(self, info): return Car.objects.all() schema = graphene.Schema(query=Query) setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'graph', } } after typing the follwing queny in graphql interface query { allcar { name } } the results are the follwing: { "data": { "allcar": [] } } in the terminal i can see : [12/Jun/2021 14:33:49] "POST /graphql HTTP/1.1" 200 22 my mongo database it has two records as mention in the picture bellow -
Heroku redis deployed backend does not cache data
First time deploying app. I'm trying to run my backend on Heroku url example:(this_is_my_app_name.herokuapp.com). I have my database deployed at AWS and connected to my backend. I've tested locally and everything seems to work. But now I have a problem when I'm trying to access my backend admin panel on deployed backend I can't access it with my login information (I can access by creating superuser but theres no data from database). I think it's redis problem and can't configure my redis right. I've tried importing urlparse and using like this : redis_url = os.environ.get('REDISTOGO_URL', 'http://localhost:6959') redis_url = urlparse.urlparse(redis_url) ......... 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), ........ For example this is my local redis cache working locally: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "REDIS_CLIENT_CLASS": "redis.client.StrictRedis", "REDIS_CLIENT_KWARGS": {"decode_responses": True}, # Custom serializer "SERIALIZER": "core.redis.JSONSerializer", }, } } This is my code deployed to Heroku I used this article 'Connecting in Django' (https://devcenter.heroku.com/articles/heroku-redis). I've tried aswell this article (https://devcenter.heroku.com/articles/redistogo#install-redis-in-python) but still it does not work. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), <-------------------- my change "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "REDIS_CLIENT_CLASS": "redis.client.StrictRedis", "REDIS_CLIENT_KWARGS": {"decode_responses": True}, # Custom serializer "SERIALIZER": "core.redis.JSONSerializer", }, } } -
how to store uploaded files for a web application while using AWS ECS FARGATE
I am very new to the concept of AWS EFS. As i am currently building a web application using Django with ECS - AWS Fargate backend and javascript with react front end, which is deployed to s3. About the backend, I am wondering what would be the best way for a user to: 1/ store/upload the images related to their profile? 2/ assuming the user also own a product in the app and each product has images, how to store these images as well... Would AWS S3 or AWS EFS be the most appropriate way to store 1 and 2 above? Thanks for the feedback