Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
favicon icons not found , djabgo website with bootstrap at front , its a simple website
favicon icons not found , djabgo website with bootstrap at front , its a simple website . it was working a few minuts ago i tried chanding the whole boot strap code . the log i am getting when the django server is runing and i use the users profile: Not Found: /favicon.ico [06/Feb/2021 08:53:13] "GET /favicon.ico HTTP/1.1" 404 4502 Session data corrupted this is were the bootstrap static is coming though in the page: {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> -
"Database is Locked" error while deploying django webapp on azure
I am trying to deploy an django webapp on azure, it shows on web totally functional, except one thing, It doesnt let me create superuser on webssh, Every time I try to run python manage.py createsuperuser and after giving all credentials it throws an error django.db.utils.OperationalError: database is locked I don't understand what to do I am using default database of django. -
Django template language logical issue
In this code line no. 4 if "user.number" is greater than "i", (add:'4') this will done. but if "i" is greater than "user.number", (add:'-4) this will done ...but i do not understand why ..? because if (i < users.number) is False then (i > users.number) this should not run please explain {% for i in users.paginator.page_range %} {% if users.number == i %} <li class="page-item active"><a class="page-link">{{ i }}</a></li> {% elif i < users.number|add:'4' and i > users.number|add:'-4' %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} -
Django3 : how to add an attribute from a foreign key filed
I have to migrate some code from python2.7/django1.11 to python3.7/django3.x I get an error and could not find why. The error is that i can access the foreign key value nom_ingredient. "Instance of 'ForeignKey' has no 'nom_ingredient' member". The problem is the same with mode_operatoire field class Ingredient(models.Model): id_ingredient = models.AutoField(primary_key=True) nom_ingredient = models.CharField(max_length=100) def __str__(self): return self.nom_ingredient class Meta: managed = True db_table = 'ingredient' class Recette(models.Model): id_recette = models.AutoField(primary_key=True) nom_recette = models.CharField(max_length=100, blank=True) mode_operatoire = models.CharField(max_length=1000, blank=True) class ComposerRecette(models.Model): id = models.AutoField(primary_key=True) id_ingredient = models.ForeignKey('Ingredient', db_column='id_ingredient', on_delete=models.DO_NOTHING) quantite_ing = models.FloatField() def mode_operatoire(self): return self.id_recette.mode_operatoire def __str__(self): return self.id_ingredient.nom_ingredient -
How to download a database from the postgresql in the format of zip with Filestore by using python(Django)
I am trying to implement a django project, in that project there is a postgresql database with filestore. I need to download the database along with filestore in the ZIP format and it can be restore to database as well. Thanks in advance -
Remove from cart button not appearing - django template language
So it is supposed to show remove from cart when user has that item in their cart and add to cart when they don't, I am trying to use django template language for this but remove from cart button is not appearing, home function handles the page i am talking about, It passes all the variables to home.html. home.html <h1>Here are products</h1> <h1>{{ error }}</h1> <h1>Your cart currently costs ${{ price }}</h1> {% for book in books %} <h3>{{ book.name }}</h3> <img src= "/media/{{ book.image }}" alt=""> <p>{{ book.description }}</p> {% if book in cart %} <form method="POST" action="/removefromcartforhome/"> {% csrf_token %} <button type="submit" name="removeid" value="{{ book.id }}">remove item from cart</button> </form> {% else %} <form method="POST" action="/addtocartforhome/"> {% csrf_token %} <button type="submit" name="bookid" value="{{ book.id }}">Add to cart</button> </form> {% endif %} {% endfor %} views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in … -
Exception in thread django-main-thread django
Whenever running the server the following exception is poping up. Exception in thread django-main-thread: Following are the respective Traceback. Traceback (most recent call last): File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\sarathmahe024\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\sarathmahe024\Downloads\website\venv\lib\site-packages\django\core\management\base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: web.Profile.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I had already installed the pillow but its showing error in importing ImageField. Please let me know if you have any idea regarding this. Thanking you in advance. -
Hello.. I am making project on online exam system in django. I don't understand following code inside **
I am making project on online exam system in django. I recently download one template for same form GitHub.I don't understand following code inside ** ''' def student_signup_view(request): userForm=forms.StudentUserForm() studentForm=forms.StudentForm() mydict={'userForm':userForm,'studentForm':studentForm} if request.method=='POST': userForm=forms.StudentUserForm(request.POST) studentForm=forms.StudentForm(request.POST,request.FILES) if userForm.is_valid() and studentForm.is_valid(): **user=userForm.save() user.set_password(user.password) user.save() student=studentForm.save(commit=False) student.user=user student.save() my_student_group = Group.objects.get_or_create(name='STUDENT') my_student_group[0].user_set.add(user)** return HttpResponseRedirect('studentlogin') return render(request,'student/studentsignup.html',context=mydict) ''' Thank you. -
Using a variable in xpath as "request.method.POST.get" in Python Selenium
I am trying to get data from HTML form, seems like Xpath is not able to fetch POST data. here is my HTML form <form action="pay/" onsubmit="string()" method="post"> <label for="amount">amount</label> <input type="text" formmethod="post" name="amount"><br> <input type="submit" value="Toggle" id="toggle1" /> </form> after submit it run the test. def string(request): if request.method == 'POST' ... goes well till here. then stops at: ... sleep(5) amount = request.method.POST.get("amount") j = pay.find_element_by_xpath("//strong[contains(text(),'" + amount + "']") action = ActionChains(pay) action.move_to_element(j).click().perform() Error returns with "'str' object has no attribute 'POST'". the 'amount' is in integer form which actually searches for text in xpath.`` -
I am looking to run a django server on my personal PC that can be available through WAN
I am currently working on a developmental website and I need to be able to move it to a public domain, so I went and made the purchase of a domain and now i want to make the django app i have written publically available without purchasing a web hosting service quite yet or I might plan on investing in an actually windows server, if anyone knows how to go about doing this purely for developmental use and proff of concept practice, it would be great to see a video or a step by step guide. -
Why does my clean_email and clean_username not work
Over here, I am trying to make it such that users cannot update their username and email to a username/email that is already existing. However, though no errors are shown, it does not work. Can someone advise why this is so? This worked for my register page. forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'email',) def clean_email(self): email = self.cleaned_data['email'].lower() try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_username(self): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExist: return username raise forms.ValidationError('Username "%s" is already in use.' % username) def save(self, commit=True): account = super(AccountUpdateForm, self).save(commit=False) account.username = self.cleaned_data['username'] account.email = self.cleaned_data['email'].lower() if commit: account.save() return account views.py def edit_account_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) if account.pk != request.user.pk: return HttpResponse("You cannot edit someone elses profile.") context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = AccountUpdateForm(request.POST, instance=request.user, initial={ "email": account.email, "username": account.username, } ) context['form'] = form -
Django model CharField choice clashes with itself
I was extending my Survey model with models.CharField(choices) but I cannot due to Error: surveys.Survey.status: (models.E006) The field 'status' clashes with the field 'status' from model 'surveys.survey'. My Model Code: class Survey(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) finish_date = models.DateTimeField(blank=True, null=True) uuid = models.UUIDField(unique=True, editable=False, db_index=True, default=uuid.uuid4) Finished = 'FI' OnProgress = 'OP' ReportGenerated = 'RG' STATUSES = [ (Finished, 'Finished'), (OnProgress, 'OnProgress'), (ReportGenerated, 'ReportGenerated') ] status = response = models.CharField( max_length=2, choices=STATUSES, default=OnProgress, ) Other models there I used Survey in case it may help: class SurveyCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) survey = models.ForeignKey(Survey, on_delete=models.CASCADE) class SurveyQuestion(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) response_explanation = models.TextField(blank=True, null=True) Not_Responded = 'NR' Fully_Implemented = 'FI' Partially_Implemented = 'PI' Not_Implemented = 'NI' SURVEY_RESPONSE_CHOICE = [ (Not_Responded, 'Not Responded'), (Fully_Implemented, 'Fully Implemented'), (Partially_Implemented, 'Partially Implemented'), (Not_Implemented, ' Not Implemented'), ] response = models.CharField( max_length=2, choices=SURVEY_RESPONSE_CHOICE, default=Not_Responded, ) -
How to serialize list of model objects in django model serailizer field?
Here I have a model and inside the model there is a property method and inside the method there will be a list of model objects. Now I am trying to get the products from the property method in my serializer like this but I am getting the error: TypeError: Object of type Product is not JSON serializable model class MyModel(models.Model): title = models.CharField(max_length=255) products = models.ManyToManyField(Product) categories = models.ManyToManyField(Category) @property def get_products(self): all_prods = [] products = list(self.products.all()) all_prods.extend(products) categories = self.categories.all() for category in categories: prods = [prod for prod in category.product_categories.all()] all_prods.extend(prods) return all_products serailizer class MySerializer(serializers.ModelSerializer): all_products = serializers.ReadOnlyField(source='get_products') class Meta: model = MyModel fields = ['title','all_products'] -
How to render Vue with Django
I'm working on a small application using Vue.js and Django on Digitalocean, so I have installed Django Webpack loader and the tracker also, now I have executed my Django server and my vue.js also using npm run serve and when I access to my webpage localhost:8000 I see only a blank page since everything is installed correctly, This is my HTML page ( when I inspect on chrome browser ) <html> <head> <title>Title of the document</title> </head> <body> <div id="app"></div> <script type="text/javascript" src="http://0.0.0.0:8080/js/app.js"></script> </body> </html> PS : i think the problem is in app.js ( because i follow the link and i get an error ) This site can’t be reachedThe webpage at http://0.0.0.0:8080/js/app.js might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID -
Django | changing pk view parameter breaks the view
I have a Django app I'm making where each user has a card, consisting of several text tiles. Here's my models: class Card(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner") class Tile(models.Model): card = models.ForeignKey( Card, on_delete=models.CASCADE, related_name="card") content = models.TextField() I would like to populate the same HTML template with the card/tile data based on the URL, so I am passing the primary key of the card through the URL: urlpatterns = [ path('card<int:pk>/', views.card, name='card'), ] My question is about my views. I am trying to pass only the tiles in that have a card foreign key with the primary key id that was passed through the URL. So, this works: def card(request, pk): try: card = Card.objects.get(pk=pk) if card: context = { 'title': 'Card', 'tiles': Tile.objects.filter(card=pk) } return render(request, 'cards/card.html', context) except: return HttpResponseNotFound() However, this, does not work: def card(request, card_pk): try: card = Card.objects.get(pk=card_pk) if card: context = { 'title': 'Card', 'tiles': Tile.objects.filter(card=card_pk) } return render(request, 'cards/card.html', context) except: return HttpResponseNotFound() I get the following error: card() got an unexpected keyword argument 'pk' Why is that? I was under the impression I was just renaming the parameter for my view function... -
I cant run hello world
enter image description here urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include ('portfolio.urls')), ] views.py from django.shortcuts import render from django.http import HttpResponse Create your views here. def home(request): return HttpResponse("Hello World"); please help I'm still a newbie in django -
django.db.utils.DataError: value too long for type character varying(20)
I am trying to shift my database from sqlite3 to PostgreSQL in my Django project. my models.py: from django.db import models from django.contrib.auth.models import AbstractUser class myCustomeUser(AbstractUser): #id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) def __str__(self): return self.username class Student(models.Model): user = models.OneToOneField(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=True) gmail = models.EmailField(null=True, blank=False, unique=True) def __str__(self): return self.name how after successful(first) makemigrations and migrate I run py manage.py create superuser and then enter superuser's username, email and password. then It says the following error: Traceback (most recent call last): File "G:\Python\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.StringDataRightTruncation: value too long for type character varying(20) The above exception was the direct cause of the following exception: 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 "G:\Python\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "G:\Python\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Python\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "G:\Python\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "G:\Python\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "G:\Python\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "G:\Python\lib\site-packages\django\contrib\auth\models.py", line 158, in create_superuser return self._create_user(username, email, password, … -
How to click a button to add friends and show an alert without refreshing or redirecting to another page
What I want to do is for a user to add and get an alert without refreshing the page,but I'm not that experienced with ajax,I would be thankful if you can get me a way I can pass the username of the friend to be added as a json data then send it to views.py to actually add friend on backend -
django return 2 same results when search through model?
In my django app, I have a search functionality for users to search through my model. I'm using django's SearchVector and SearchQuery because I'm using Postgresql as database. Everything works fine except it returns 2 exact same results. shell >>> results = MyModel.objects.annotate(search=SearchVector('title', 'content', 'tag__name'), ).filter(search=SearchQuery("some words")) >>> results <QuerySet [<MyModel: MyModel object (7)>, <MyModel: MyModel object (7)>]> it's been almost a day now that i'm trying to fix this problem. It worked fine in development but this problem occurs in production. Thanks you! -
Django previous MySQL raw query still running after changes the database to PostgreSQL
I am facing a problem after replacing the database connection from MySQL to PostgreSQL. Everything works fine but the MySQL raw query still running while I change it to PostgreSQL. The new raw query works fine in PostgreSQL Query tool. def home(request): if request.method == 'GET': cursor = connection.cursor() # cursor.execute('''select (select Date from datepd where dateid=Datepd_dateid) as Date, # (select QCL from productioninfo where infoid=Datepd_dateid) as QCL, # round(AVG(Gap),2) as gap FROM dailyproduction GROUP BY Datepd_dateid ORDER BY Date ASC''') cursor.execute('''select (select "Date" from public.surmafloor_datepd where dateid="Datepd_dateid") as "Date", (select "QCL" from public.surmafloor_productioninfo where infoid="Datepd_dateid") as "QCL", round(AVG("Gap"),2) as gap FROM public.surmafloor_dailyproduction GROUP BY "Datepd_dateid" ORDER BY "Date" ASC''') avrg = cursor.fetchall() The code still running the previous query. Right now I am having this error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\FKL_CIT-02\fkl\pdfloor\surmafloor\views.py", line 243, in homeChart cursor.execute('''select (select Date from datepd where dateid=Datepd_dateid) as Date, File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\FKL_CIT-02\Envs\mis\lib\site-packages\django\db\backends\utils.py", … -
Django admin. Text does not fit into manytomany field widget
Inside my django admin i have a manytomany field in which i want to fit a string.The string does not fit inside the field Is there any way to fix this? -
django intra-model field dependancy
I'm using django Oscar and trying to extend the apps included models to add some fields from the django-imagekit library to a model. The issue is that my underlying app which controls the dashboards (oscar) populates the forms for the dashboard directly from the models using from django.forms.models import inlineformset_factory. I want the fields I'm adding to be based off one of the fields already in the model, so I don't want to change any forms. Thus I need to intercept the input into the apps basic django.db.modelsImageField and use if for my new fields. example of a fork, where I subclass the model I want to extend #code from app I'm forking #link to src: https://github.com/django-oscar/django-oscar/blob/1fd9f0c3379042e1594f0d9281a5c323b5bafba2/src/oscar/apps/catalogue/abstract_models.py#L1302 class AbstractProductImage(models.Model): """ An image of a product """ product = models.ForeignKey( 'catalogue.Product', on_delete=models.CASCADE, related_name='images', verbose_name=_("Product")) original = models.ImageField( _("Original"), upload_to=get_image_upload_path, max_length=255) caption = models.CharField(_("Caption"), max_length=200, blank=True) #my fork/subclass from imagekit.models import ImageSpecField class Product(AbstractProductImage): srcset_image_1 = ImageSpecField( source=self.origional.name, processors=[ResizeToFill(100, 50)], format=self.origional.name.split('.')[-1].upper(), options={'quality': 80} ) Of course this throws an error: NameError: name 'self' is not defined Not to mention there is a serious issue of how to keep the srcset_image_1 field from containing stale data. Is there a way to manage such … -
Can anyone post a serious of steps to upload Adsense ads.txt file?
Can anyone post a serious of steps to upload Adsense ads.txt file to my root level domain (it is a django website)? -
Django Knox-Rest Authentication Receives 500 Error on Login
I'm working on setting up a Django knox-rest framework for my rest api. I'm using Postman to test the login and after executing the request, my API returns a 500 error along with a stack dump. The dump returned to Postman is showing me the following error: AttributeError at /users/api/auth/login 'LoginSerializer' object has no attribute 'validated_data' a snippet from my api.py file: class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer permission_classes = () def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.valiated_data _, token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": token }) the snippet from my serializers.py file: class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Incorrect Credentials") The server starts clean and no errors are logged to the console other than the Post request and the 500 error. I have to go to Postman to see the dump with the above error. I've tried just about everything I can think of or find to try without getting it figured out. So any help would be appreciated. -
TimeoutError [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time
I wanna sent a email to users account to reset password. But whenever I enter the send it causes an error. TimeoutError at /accounts/reset_password/ [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond I do not know why I am having a lot of issue in doing reset password. Things which I have done or try I already enable "less secure" apps in my gmail account. I was also having a issue in password_reset_email.html and for that I use email_template_name=accounts/registration/password_reset_email.html and after adding this the error was TemplateDoesNotExist. And then I make a dir in my accounts app and add a password_reset_email.html Here is code. any help please urls.py from django.urls import path, reverse_lazy from . import views from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path('register/', views.register, name='register'), path('signin/', views.signin, name='signin'), path('logout/', views.logout, name='logout'), path('user_profile/', views.edit_profile, name='edit_profile'), path('user_password/', views.change_password, name='change_password'), # Rest password section path('reset_password/', auth_views.PasswordResetView.as_view( template_name='accounts/password_reset.html', success_url=reverse_lazy('accounts:password_reset_done'), email_template_name='accounts/registration/password_reset_email.html' ), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='accounts/password_reset_sent.html', ), name='password_reset_done'), path('reset_confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='accounts/password_reset_form.html', success_url=reverse_lazy('accounts:password_reset_complete') ), name='password_reset_confirm'), path('rest_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='accounts/password_reset_done.html', ), name='password_reset_complete') ] settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = …