Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AWS redis server config for django
I am following this tutorial and I am confused with the following code: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(<REDIS ELASTICACHE HOSTNAME>, 6379)], }, }, } here, what 'REDIS ELASTICACHE HOSTNAME' refers to? I created redis instance using AWS ElastiCache, I didn't find 'HOSTNAME' anywhere in the AWS console of redis instance. I tried to replace it with the name of the instance but after testing it in the shell, I was unable to send message over the layer. The error in testing the layers was: File "C:\Users\Nouman\AppData\Local\Programs\Python\Python37\lib\socket.py", line 748, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed Can any body help? -
unable to connect to localhost in creating a django blog
I have written the following code in my urls.py : from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/$', views.about), url(r'^$', views.homepage), ] and I created a views.py in my project folder and wrote the following code in it: from django.http import HttpResponse def homepage(request): return HttpResponse("homepage") def about(request): return HttpResponse('about') but when i use 127.0.0.1:800 for seeing my changes in browser i ocuured with unabling to connect and my internet connection does not have any problem what should I do? -
How do I use operators in Django {% if %} template tag?
so I'm trying to do simple calculation as my condition statement in {% if %}{% endif %} tag in Django. But somehow it doesn't work. Here's my code : {% for i in range %} {% if i/2 != 1 %} <!- Do something -> {% elif i/2 == 1 %} <!- Something else -> {% endif %} {% endfor %} I keep getting error that says "Could not parse the remainder: '/2' from 'i/2'" So there must be another way of using the operators in if statement, but I can't figure out what that is. I would very much appreciate your help! :) -
how to validate field already exist on form update
I add a validation on form.py to exclude the same record at the time of update so I check the username already exist or not, but self.instance.pk is getting None. I know there are also another way to do this but I want to know why self.instance.pk did not work, I will use this approach to other Forms also so I need to fix this using self.instance.pk here is my code so could you please review the code what is I am missing and why self.instance.pk not working. forms.py from django import forms from .models import CustomUser class UserForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = CustomUser fields = '__all__' exclude = ["is_admin", "is_verified", "last_login"] def clean_username(self): username = self.cleaned_data.get("username") print(self.instance.pk) user_obj = CustomUser.objects.exclude(pk=self.instance.pk).get(username=username) if user_obj: raise forms.ValidationError("username already exist") return username views.py def edit_profile(request): context = { "form": UserForm() } user_obj = request.user form = UserForm(instance=user_obj) context["form"] = form return render(request, "account/profile.html", context) -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' - ecommerce
It says that int argument must be a string, however in trying to do that i received more errors. any solutions? i was following an online tutorial which doesn't seem to have this error, so not sure where mine is wrong. views.py def update_cart(request, slug): request.session.set_expiry(120000) try: qty = request.GET.get('qty') update_qty = True except: qty = '' update_qty = False try: the_id = request.session['cart_id'] except: new_cart = Cart() new_cart.save() request.session['cart_id'] = new_cart.id the_id = new_cart.id cart = Cart.objects.get(id=the_id) try: product = Product.objects.get(slug=slug) except Product.DoesNotExist: pass except: pass cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) if created: print("yes") if int(qty)== 0 and update_qty: cart_item.delete() elif update_qty: cart_item.quantity = qty cart_item.save() else: pass #if not cart_item in cart.items.all(): # cart.items.add(cart_item) #else: # cart.items.remove(cart_item) new_total = 0.00 for item in cart.cartitem_set.all(): line_total = float(item.product.price) * item.quantity new_total += line_total request.session['items_total'] = cart.cartitem_set.count() cart.total = new_total cart.save() return HttpResponseRedirect(reverse('cart')) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, name='fuisce-subscription'), path('oneoff/', views.oneoff, name='fuisce-oneoff'), path('about/', views.about, name='fuisce-about'), path('contact/', views.contact, name='fuisce-contact'), path('cart/', cart_views.view, name='cart'), path('cart/<slug>/', cart_views.update_cart, name='update_cart'), path('cart/<int:id>', cart_views.remove_from_cart, name='remove_from_cart'), path('checkout/', order_views.checkout, name='checkout'), ] view.html {% extends "fuisce/base.html" %} … -
Is there a way I can run a web scraper on flask without blocking the server?
I have a web app written in Flask, a user will log in and input some search keywords, these keywords will be passed to a web scraper function I wrote and fetch the data, the web scraper function can take takes some minutes to return the data and render it to the user in a template, while the web scraper is running, the server is blocked, is there a way I can run the web scraper function in a separate thread or background and in some way render the data to the user without blocking the server, My code looks like this @app.route("/", methods=["GET", "POST"]) @login_required def home(): if request.method == "POST": search_phrase = request.form.get("search_term") data = run_scraper(search_phrase) for d in data: print(d) return render_template("index.html", results=data) else: return render_template("index.html") -
Django server deployment sucessful but shows some error on CMD
First I've created a Virtual environment... then I've created a Project called crm when I type python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 19, 2020 - 19:03:25 Django version 3.0.5, using settings 'crm.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. then when i go to this http://127.0.0.1:8000/ on Firefox I get the error (click the link to get the image) but the server runs well Can anyone explain me why i got this error?? -
Axios Post Request return Error 400 when that same data and url works with Postman (Django DRF ReactJS)
I am creating an application that uses Django as the backend, and ReactJS as the front end. I am using DRF for the api calls from ReactJS to Django, but am facing an issue with sending a post request. When i send a post request with the relevant data in JSON format using axios in ReactJS, it returns an error code of 400. However, when I copy that same JSON data and use it to send a post request in Postman, there was no error and the code was 201 (created). I am not too sure why there is this issue, and I have already set the neccessary settings in the Django settings.py to ensure that permission is granted (for testing purposes I just set it to 'allow all'). I managed to print out the error message behind the failed post request, but I do not really understand what the error message is talking about. If there is any other way to print out more error messages to sort of let me know where to start, please let me know, thanks! Any help is appreciated! REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for … -
How to display Foreign Key related models fields values in HTML with Django?
I passed a list from Views.py to HTML in a dictionary value. I loop through the fields. There's one column which is Foreign key to another model. Only that model realted information is not displaying in HTML. How to solve this? The following is the code. The Foreign key column "Course" is not showing but others. Screenshot attached here Views.py def Student_Main(request): objs= Students.objects.values().all() template_name = 'genius/students.html' context = {'head_title': 'Little Genius Students', 'students':objs} return render(request, template_name, context) HTML <table class="table table-hover"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">DOB</th> <th scope="col">Age</th> <th scope="col">Gender</th> <th scope="col">Grade</th> <th scope="col">School</th> <th scope="col">Course</th> <th scope="col">Address</th> </tr> </thead> <tbody> {% for i in students %} <tr> <th scope="row">{{i.id}}</th> <td><a href=''>{{i.name}}</a></td> <td>{{i.dob}}</td> <td>{{i.age}}</td> <td>{{i.gender}}</td> <td>{{i.grade}}</td> <td>{{i.attending_school}}</td> <td>{{i.course.class_name}}</td> <td>{{i.address}}</td> </tr> {% endfor %} </tbody> </table> -
how to allow svg in django 3.0 in models
I want to upload the svg images from admin models, how I can enable it? or allowed specific extensions like other .webp ,.docx and pdf etc. -
Django Testing Existence of File as URL
I am trying to figure out how to test for existence of files as URLs in Django. The version below version produces a failure: self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 Here is the code for the test. from django.test import Client from django.utils import translation class ExistenceTest(TestCase): def test_static_css_directory_exists(self): C = Client() response = C.get('/static/css/clean-blog.min.css') self.assertEqual(response.status_code, 200) Any help is appreciated. -
Django Filters - Edit queryset based on slug from url
So I have a simple model called Pages. Every Page belongs to a certain category, since this is a ForeignKey relation, a Page can only belong to a single category. Besides categories we also use tags to furthermore filter the different pages. We use a category view to display all pages belonging to a certain category, easy peasy. The thing is, we use django-filters to filter the pages by selecting different tags. The list of tags is increasing by the amount of pages. Therefore I would like to only show related tags to the category. urls.py path('<slug:category_slug>/', views.PageByCategoryView.as_view(), name='page_by_category'), views.py class PageByCategoryView(FilterView): logger.info("Category view is called") model = Page filterset_class = PageByCategoryFilter strict = False queryset = Page.published_objects.all() template_name = 'pages/page_by_category.html' filters.py class PageByCategoryFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter( queryset=Tag.objects.filter(page__category_id='2'), <-- actually works! conjoined=True, widget=forms.CheckboxSelectMultiple() ) class Meta: model = Page fields = [ 'tags__slug' ] So the tags used in the filter actually get filtered by page__category_id = 2, this is exactly what I want to achieve though I want to do this dynamically. I tried to define the qs like so; @property def qs(self): queryset = super(PageByCategoryFilter, self).qs current_category = self.request.GET.get('category_slug') if current_category: logger.info("Current category is in url") return queryset.filter(category__slug=current_category) … -
request.method == 'POST' not working properly
i have created quiz app in which i created three models ( Quiz, Question ,Answer) ,Question have Foreignkey to Quiz and Answer have Foreignkey to Question.i have provided booleanfield to correct ans. Now i created view which redirect to next question if user choose correct ans or else redirect to start But its not properly working. Here is my code Views.py def question_detail(request,question_id,quiz_id): q = Quiz.objects.get(pk = quiz_id) que = Question.objects.get(pk = question_id) count = q.question_set.count() if request.method == 'POST': selected = que.answer_set.get(pk=request.POST['choice']) if selected is True : try: come = que.rank came = come +1 later_question = q.question_set.get(rank=came) except: come = que.rank came = come later_question = q.question_set.get(rank=came) else : come = que.rank later_question = q.question_set.get(rank=come) return render(request,'app/question_detail.html',{'count':count,'que':que,'later_question':later_question}) else: return render(request,'app/result.html') -
Django ManyToMany Field in forms.CheckboxSelectMultiple: how scroll the records in the template?
I have two models with a ManyToMany Relationship and in the form, I would render this with a list of checkboxes. But I have a lot of records displayed! models.py class Categoria(models.Model): NomeCategoria = models.CharField(max_length=50,blank=True,null=True) class Prodotti(models.Model): ''' tabella Prodotti a catalogo ''' NomeProdotto = models.CharField(max_length=70,blank=True,null=True) CategoriaProdotto = models.ManyToManyField(Categoria, related_name='prodotti_categoria') ... forms.py class ProdottoModelForm(forms.ModelForm): class Meta: model = Prodotti fields = "__all__" widgets = { 'CategoriaProdotto': forms.CheckboxSelectMultiple() } HTML template ... <div class="card-body"> {{ form.CategoriaProdotto|as_crispy_field }} </div> ... A list with a lot of checkboxs Is there a way to have a list of ten checkboxes and a vertical scrollbar? I've tried with rows or size, but don't resolve the question: ... widgets = { 'CategoriaProdotto': forms.CheckboxSelectMultiple(attrs={'rows':10}) } ... Thanks -
Django: Expected view likeList to be called with a URL keyword argument named "id"
Ive been trying to create an API that would return all objects from Like model however, I received an error (Expected view likeList to be called with a URL keyword argument named "id". Fix your URL conf, or set the .lookup_field attribute on the view correctly.). Here is my model class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = models.Manager() image = models.ImageField(upload_to='post_pics') def __str__(self): return self.title @property def useremail(self): return self.author.email @property def owner(self): return self.author def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) def get_api_url(self, request=None): return api_reverse('post-detail', kwargs={'pk': self.pk}, request=request) def get_like_count(self): return self.like_set.count() class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) Serializer class likeserializers(serializers.ModelSerializer): username = serializers.SerializerMethodField(read_only=True) post_title = serializers.SerializerMethodField(read_only=True) class Meta: model = Like fields = ('id','created', 'user','username', 'post','post_title') def get_username(self, obj): return obj.user.username def get_post_title(self, obj): return obj.post.title Views class likeList(generics.RetrieveUpdateDestroyAPIView): lookup_field = 'id' serializer_class = likeserializers def get_queryset(self): return Like.objects.all() URLS urlpatterns = [ path('users/', API_views.userList.as_view(), name = 'users'), path('users/id=<int:id>/', API_views.userListbyID.as_view(), name = 'usersid'), path('posts/', API_views.postList.as_view(), name = 'post'), path('posts/id=<int:id>', API_views.postListbyID.as_view(), name = 'postid'), path('likes/', API_views.likeList.as_view(), name = 'likes'), path('likes/id=<int:id>', API_views.likeListbyID.as_view(), name = 'likesid'), path('follows/', API_views.followList.as_view(), name = 'likes'), path('follows/id=<int:id>', … -
Render The Count of filtered values through for loop in django template
I am trying to write a qyeryset that output the count of Pending and Delivered orders related to each Location throug a for loop in the Template. for example: My models are: Locations Model Class Locations(models.Model): class Meta: verbose_name_plural = "Locations" Name = models.CharField(max_length=250) Status Model class Status(models.Model): class Meta: verbose_name_plural = "Status" status = models.CharField(max_length=250) Contains three values [delivered, pending, and under process] Orders Model: class Orders(models.Model): class Meta: verbose_name_plural = "ALL Orders" Time_Registered = models.DateField(blank=False) Number = models.CharField(max_length=500) Locations = models.ForeignKey(Locations, on_delete=models.CASCADE) Status = models.ForeignKey(Status, on_delete=models.CASCADE) Remarks = models.TextField(max_length=1000, blank=True, null=True) Time_Delivered = models.DateField(blank=True, null=True) -
PythonAnywhere image not found
Before anyone deletes this due to the question being similar to others: Neither other questions nor the documentation got my site to work as intended. The goal: Load images on my site The problem: Image not found Additional info: It works locally using python manage.py runserver What I've done to try to fix it: I've tried to follow the staticfiles guide https://help.pythonanywhere.com/pages/DjangoStaticFiles but this didn't work because I'm not using the default uploaded files handling. I've tried to enter it under the PythonAnywhere > Web > static files tab but haven't been able to get that to work. Tried a bunch of different solutions from the PythonAnywhere forum and SO forum and none got my site to work. The site: http://nasablogdeployment.eu.pythonanywhere.com/ All code available here: https://github.com/MarkdenToom/NASA-blog -
How can I replace the forms with my serializer in django
Model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,default='') # user = models.OneToOneField(User, on_delete=models.CASCADE) phone_no = models.CharField(max_length=13,unique=True) registered = models.BooleanField(default=False) spam = models.BooleanField(default=False) def __str__(self): return self.user.username Serializer.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField() class Meta(): model = User fields = ('username','email','password') class UserProfileSerializer(serializers.ModelSerializer): class Meta(): model = UserProfileInfo fields = ('phone_no',) views.py def register(request): registered = False if request.method == 'POST': user_serializer = UserSerializer(data=request.POST) profile_serializer = UserProfileSerializer(data=request.POST) if user_serializer.is_valid() and profile_serializer.is_valid(): user = user_serializer.save() user.set_password(user.password) #saving hash value of password user.save() profile = profile_serializer.save(commit=False) profile.user = user profile.registered = True profile.save() registered = True else: print(user_serializer.errors) else: user_serializer = UserSerializer profile_serializer = UserProfileSerializer return Response(request,'basic_app/registration.html',{ 'user_serializer':user_serializer, 'profile_form':profile_form, 'registered':registered }) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print(username,password) user = authenticate(username=username, password=password) print(user) if user: if user.is_active: login(request,user) return render(request,'basic_app/search.html') else: return HttpResponse('Account not active!') else: # print(username,password) return HttpResponse('Login credentials not correct!') else: return render(request,'basic_app/login.html') Now I need to make changes to my views.py such that I can parallely populate the user and the profile model having one to one field. I was using the form which was working well but now I need to convert the code to rest API. Please help how I can keep the … -
django Failed at "hello world" error: No module named 'userdash.urls'
I am trying to create a simple webroot level HttpResponse and it says my module is missing when I surf to it. $ cat exchange2/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'burp' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', '192.168.42.12', '192.168.42.13'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'userdash', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'exchange2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'exchange2.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") $ cat userdash/url.py from django.urls import path from . import views urlparterns = [ path("", views.index, name="index"), ] $ cat … -
QuerySet django returns unnecessary things
I'm doing a django app which consists in an e-commerce website. I have a profile page, and inside I show all articles bought by the connected user. So for that I do a QuerySet: class ProfileView(generic.ListView): template_name = 'eduardoApp/profile.html' context_object_name = 'order_list' def get_queryset(self): return Order.objects.filter(user=self.request.user.id,ordered=True) And in my profile page I do like this: {% for order in order_list %} <div> <p> {{ order.user }} </p> <p> {{ order.articles.all}} </p> <pl> {{ order.ordered }} </p> <p> {{ order.ordered_date }} </p> </div> {% endfor %} The order.articles.all is returning the following : <QuerySet [<OrderArticle: Bottle of Wine>]> But my question is : how do I only display 'Bottle of Wine' ? Instead of diplaying QuerySet {<....> -
IntegrityError at /notes/add NOT NULL constraint failed: notes_note.created
I have a problem when I do add function in django2 cant add new post And this code enter image description here [enter image description here][2] -
Django crypto wallets and payments library
I want to build a game and betting website with Django and cryptocurrency payments with cryptocurrencies like BTC ETH XMR LTC USDT DASH ...etc like bc.game website, and I don't know how the structure it is do I need to create wallet for each user that registered on a website to handle deposits and withdrawals? or should I make a unit wallet for example blockchain wallet for the entire website? how can I make withdrawal address different and unique for each user? Do Django libraries support this? I'm a little confused about this. -
How view file in interface django admin?
I mean, when form write into the db with file upload into folder "upload". How can i see the file in interface admin? my models.py: def user_directory_path(instance, filename): ext = filename.split() filename = "%s_%s_%s_%s.%s" % (instance.last_name, instance.first_name, instance.middle_name,instance.date_birth, ext ) return os.path.join('upload', filename) class Professional(models.Model): .... upload = models.FileField('Файл', upload_to=user_directory_path) Some screenshots with error: file correctly displayed in interface erroe when i try open the file -
Pycharm Autocomplete django,emmet etc. not working in html at <body> tags
it's working pretty well in head tags in the other hand body tags ... it's same when i try to use Emmett like h1>h2 and tab working good at head tags but in the body tag it's just making spaces -
How to run django-made venv on pythonanywhere?
I am a django beginner and I have made a django app on my PC that uses MySQL Connector. I always run it by going into django's venv's scripts folder and then opening a cmd window and giving an "activate" command. Then, I go to a web browser and run my website on http://localhost:8000.... I want this same website run on Pythonanywhere and I have uploaded all the files of django folder including the venv folder --- all of them correctly placed as in my PC. When i open a "bash console" in the "scripts" folder (placed in venv folder) and type "activate", then it says "command not found". Please help me. Thank you!