Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get deleted object in Django DeleteView
I want to show an info message after deleting an object from a database. I decided to use SuccessMessageMixin for that purpose. How I can add object attributes to the success_message? class PostDeleteView(SuccessMessageMixin, DeleteView): model = Post success_url = reverse_lazy('post_list') def get_success_message(self, cleaned_data): return 'The ' + str(self.object) + ' post was deleted' I thought I can do it that way. But there is no message after the deletion. -
Turning a simple block of code into a function with object types?
I want to be able to take the following code and turn it into a function where I can pass in parameters and call the function anywhere. #views.py from .models import Pizza, Topping pizza = form.save() toppings = request.POST.getlist('toppings') for t in toppings: t = Topping.objects.get_or_create(name=t)[0] t.save() pizza.toppings.add(t) I'm sure this is fairly simple, but I for some reason can't figure out how to do it. Any help will be greatly appreciated:) -
Forms disabled/enable button django python
I have a problem i register site. I would like to make registartion panel and I would like to add When password and password confirmation are equal and not empty enable Register button After submit Form....But i really don't know how to do that. Could someone help me? Here is my code: signup.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="{% url 'sign_upsucces' %}" > {% csrf_token %} {{ form }} {{ fail }} <button type = 'submit' {{ some }}>Zarejestruj się</button> </form> </html> views.py def sign_upsucces(request): form = SignUpForm(request.POST or None) users = SignUp() people = SignUp.objects.all() fail = '' some = 'disabled' if form.is_valid(): dane = form.save(commit=False) if (len(people)>0): try: person = SignUp.objects.get(login = dane.login) except SignUp.DoesNotExist: if dane.password == dane.password_confirm: users.login = dane.login users.password = dane.password users.password_confirm = dane.password_confirm users.save() some = '<button type="submit">Zarejestruj się</button>' fail = 'Konto utworzone!' session = 'Zaloguj się' else: fail = 'Hasła się nie zgadzają' else: fail = 'Istnieje' session = 'Zaloguj się' else: if dane.password == dane.password_confirm: user = SignUp() user.login = dane.login user.password = dane.password user.password_confirm = dane.password_confirm user.save() fail = 'Konto utworzone' session = 'Zaloguj się' return render(request, 'signup.html', {'form':form, 'dane':dane, 'fail':fail, 'some':some, … -
How do I place user's input inside of a method that returns if the person exists?
So I have this code in which I need to use a method that takes the number the person inputs to check if the person exists in the database. The thing is, how do I pass the numbers the person uses to the method? The numbers are what's called "cuit" in here. The method works like this: response=get_persona("74013028") The numbers should be the ones the person types. If the person exists, it returns the name and last name like this: response["persona"]["lastname"]["name"] If the person doesn't exist, it has to print that. Where should I place this piece of code and how do I make it take the input of the user to verify if the person is in the database? This is the view: from django.shortcuts import render, HttpResponse import requests from django.views import View from .forms import MonotributoForm from app.ws_sr_padron import get_persona class Constancia(View): def get(self, request): return render(request, 'app/constancia-inscripcion.html') def post(self,request): if request: form = MonotributoForm(request.POST) if form.is_valid(): cuit = form.cleaned_data.get('cuit') email = form.cleaned_data.get('email') cuit.save() email.save() return HttpResponseRedirect('app/constancia-inscripcion.html') else: pass return render(request, 'app/constancia-inscripcion.html') -
Video.js not getting updated source in Vue
I'm trying to embed YouTube videos using Video.js. I set Vue with Django REST Framework and I'm correctly getting my embed code, but when I create Video.js player, the source is 'undefined' and it doesn't update even if it's bound. If I hardcode a YouTube address, not binding, the player loads. App.vue <template> <div id="app"> <Video :embedCode="video.embedCode" /> </div> </template> <script> import Video from "./components/Video"; import axios from 'axios'; export default { name: 'App', components: { Video }, data() { return { video: [], }; }, methods: { loadVideo: function() { axios.get('/api/video/1').then( response => { this.video = response.data; } ); }, }, created() { this.loadVideo(); }, } </script> Video.vue <template> <div> <video-player :embedCode="embedCode" /> </div> </template> <script> import VideoPlayer from "./VideoPlayer"; export default { name: "Video", props: { text:String, id:Number, title:String, category:Number, description:String, embedCode:String, views:Number, }, components: { VideoPlayer }, } </script> VideoPlayer.vue <template> <div> <video ref="videoPlayer" class="video-js"> <source :src="videoURL" type="video/youtube" /> </video> </div> </template> <script> require('videojs-youtube') import videojs from 'video.js'; export default { name: "VideoPlayer", props: { embedCode:String, }, computed: { videoURL: function() { return "https://www.youtube.com/watch?v=" + this.embedCode; } }, mounted() { this.player = videojs(this.$refs.videoPlayer) }, beforeDestroy() { if (this.player) { this.player.dispose() } }, } </script> Why does this … -
OperationalError at /1 no such column: auctions_comment.listing_id
I'm new to Django. i'm trying to display all the comments for a listing in an auction site Help me find a way to display all the comments for a listing. Mosdels.py class Listing(models.Model): title = models.CharField(max_length=64, default="") starting_bid = models.CharField(max_length=64, default="$") description = models.TextField(default="") image_url = models.CharField(max_length=200, default="") date = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="") def __str__(self): return self.title class Comment(models.Model): comment = models.TextField(default="") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="comments", default="") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments", default="") def __str__(self): return f"{self.user} - {self.listing}" views.py def listing(request, listing_id): listing = Listing.objects.get(pk=listing_id) comments = listing.comments.all() return render(request, "auctions/listing.html", { "listing":listing, "comments":comments }) -
Cant upload images into my category's on Django admin page but I can in my products
Hey Guys I'm having an issue on the Django Admin page where I cant upload images to my products but I cannot to my category's. This strange because I created the category image folder inside of my media and ran migrations yet nothing shows up on the admin page. Ill post what comes up on PowerShell below. (env) PS C:\Users\Aaron\djangoprojects\semesterproject> python manage.py makemigrations phoneshop Migrations for 'phoneshop': phoneshop\migrations\0002_remove_category_image.py - Remove field image from category (env) PS C:\Users\Aaron\djangoprojects\semesterproject> python manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, phoneshop, sessions Running migrations: Applying phoneshop.0002_remove_category_image... OK -
How to delete redis keys in optimised manner
I have millions of data in redis cache and I want to delete thousands of data out of which with specific pattern say all the keys starts with "abcd", using "abcd*" pattern. I am using django framework. Below is sample code snipet: pattern = "abcd*" from django.core.cache import cache cache.delete_pattern(pattern) It takes a long to delete all these keys from redis around 1 hour. Is there any better way to delete all the keys with specific pattern. Please suggest any optimised approach/solution. PS. There is millions of data in redis. -
Django pagination duplicates filtered objects
I'm trying to paginate filtered queryset but I keep encountering some starenge errors. The problem is that pagination duplicates objects. Let's say that we have a product model which has price and brand fields. When I filter it by brand it duplicates second object and renders it in the template two times like this: product id: 5 brand: Apple product id: 4 brand: Samsung product id: 4 brand: Samsung product id: 3 brand: Honor product id: 2 brand: Honor ... I don't know what to do, I have ben trying to fix this whole day... Ok, here is my code: #models.py class Product(models.Model): BRAND_CHOICES = [ ('Samsung', 'Apple'), ('Apple', 'Apple'), ('Honor', 'Honor'), ] brand = models.CharField(max_length=30, choices=BRAND_CHOICES, blank=False, null=True) price = models.IntegerField(validators=[MinValueValidator(0)], blank=False, null=True) #filters.py class ProductFilter(django_filters.FilterSet): price_gt = django_filters.NumberFilter(field_name='price', lookup_expr='gte') price_lt = django_filters.NumberFilter(field_name='price', lookup_expr='lte') class Meta: model = Product fields = ['brand', 'price_gt', 'price_lt'] #views.py def index(request): products = Product.objects.all().order_by('-id') myfilter = ProductFilter(request.GET, products) paginator = Paginator(myfilter.qs, 2) page = request.GET.get('page') try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context = {'products': products, 'myfilter': myfilter} return render(request, 'index.html', context=context) Also, when I delete the part of code order_by('-id'), for some reason filtering be … -
How to fetch data from Python function to JavaScript | Django
Here, I am trying to get data("Okay, we'll see.") from get_bot_response function. But every time when I call it from JavaScript, it shows 500 (Internal Server Error). Here is how I tried, Views.py def get_bot_response(request): userText = request.GET.get('msg') return "Okay, we\'ll see." urls.py urlpatterns = [ ... path('get/', views.get_bot_response, name='get'), ] In template script function botResponse(rawText) { // Bot Response $.get("/get", { msg: rawText }).done(function (data) { const msgText = data; appendMessage("", "msgText"); }); } As well as in http://127.0.0.1:8000/get/ it shows Error: 'str' object has no attribute 'get' -
'"ERROR: No .egg-info directory found" during deployment to heroku
Hello I'm deploying my first project on the heroku and I got an error: ERROR: No .egg-info directory found in /tmp/pip-pip-egg-info-wgaqr45r I have tried to update setuptools but it's not a case. Any Idea what could go wrong? My git bash commands: gg@DESKTOP-PNHHOHJ MINGW64 /c/projekty/tabele/tabenv (master) $ git push heroku master Enumerating objects: 9199, done. Counting objects: 100% (9199/9199), done. Delta compression using up to 4 threads Compressing objects: 100% (5826/5826), done. Writing objects: 100% (9199/9199), 17.71 MiB | 4.97 MiB/s, done. Total 9199 (delta 2302), reused 9182 (delta 2296), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Python app detected remote: cp: cannot stat '/tmp/build_8554d289/requirements.txt': No such file or directory remote: -----> Installing python-3.8.8 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Obtaining file:///tmp/build_8554d289 (from -r /tmp/build_8554d289/requirements.txt (line 1)) remote: ERROR: No .egg-info directory found in /tmp/pip-pip-egg-info-wgaqr45r remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 830c4b88b9a54ed95a860492a144d53bf95172c0 remote: ! remote: ! We … -
Additional Foreign Key Query in Django
I am a newbie to django and was reading about select_related. I understand that whenever a foreign key is accessed django executes an additional query. But when I checked with DEBUG log in my code, it seems django executes two queries no matter if the foreign key is accessed or not. Can someone explain this behaviour ? class Person(models.Model): # ... name = models.CharField(max_length=250) class Book(models.Model): # ... author = models.ForeignKey(Person, on_delete=models.CASCADE) As per doc # Without select_related()... b = Book.objects.get(id=4) # Executes a query. p = b.author #Executes a query. But with the get() it executes two queries b = Book.objects.get(id=4) # Executes two queries (one for books one for author). -
Django with more settings file cannot perform migrtions
In my django project i have create a settings folder where i save different settings file for local, dev, prod ecc configurations: My root directory three is like thisone: Root |_app !_settings |_base.py |_local.py |_dev.py |_manage.py ... from every settings py file except for base i at the first line import base conf from .base import * and then add different parameters (for example database parameters). When i want to run my application with specific settings configuration i do: python manage.py runserver --settings=settings.local all was done, my app start with correct settings onboard. The problem is when i want to run makemigrations and or migrate command because if i type: python manage.py makemigrations or python manage.py makemigrations --settings=settings.local i got: ModuleNotFoundError: No module named 'app.settings' How can i specify witch settings use for make my migrations? So many thanks in advance -
Django app works locally but Server error 500 when deployed
It works in local env and is pulling from the correct AWS S3 bucket. But when deployed on Heroku, Server error 500 when app opens. Fairly new to Django and scoured for similar issues with no luck. error logs: 2021-03-04T16:56:31.500209+00:00 app[api]: Release v21 created by user 2021-03-04T16:56:31.500209+00:00 app[api]: Set AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY config vars by user 2021-03-04T16:56:31.682290+00:00 heroku[web.1]: Restarting 2021-03-04T16:56:31.693489+00:00 heroku[web.1]: State changed from up to starting 2021-03-04T16:56:33.560332+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2021-03-04T16:56:33.636566+00:00 app[web.1]: [2021-03-04 16:56:33 +0000] [10] [INFO] Worker exiting (pid: 10) 2021-03-04T16:56:33.638013+00:00 app[web.1]: [2021-03-04 16:56:33 +0000] [4] [INFO] Handling signal: term 2021-03-04T16:56:33.648577+00:00 app[web.1]: [2021-03-04 16:56:33 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-03-04T16:56:34.355203+00:00 app[web.1]: [2021-03-04 16:56:34 +0000] [4] [INFO] Shutting down: Master 2021-03-04T16:56:34.503505+00:00 heroku[web.1]: Process exited with status 0 2021-03-04T16:56:37.664320+00:00 heroku[web.1]: Starting process with command `gunicorn checkdatout.wsgi` 2021-03-04T16:56:40.310198+00:00 app[web.1]: [2021-03-04 16:56:40 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-03-04T16:56:40.310974+00:00 app[web.1]: [2021-03-04 16:56:40 +0000] [4] [INFO] Listening at: http://0.0.0.0:40014 (4) 2021-03-04T16:56:40.311130+00:00 app[web.1]: [2021-03-04 16:56:40 +0000] [4] [INFO] Using worker: sync 2021-03-04T16:56:40.316318+00:00 app[web.1]: [2021-03-04 16:56:40 +0000] [9] [INFO] Booting worker with pid: 9 2021-03-04T16:56:40.405086+00:00 app[web.1]: [2021-03-04 16:56:40 +0000] [10] [INFO] Booting worker with pid: 10 2021-03-04T16:56:40.595735+00:00 heroku[web.1]: State changed from starting to up 2021-03-04T16:56:57.650175+00:00 app[api]: Set S3_BUCKET config vars by … -
Django return list of objects and list of ids from the same queryset
I'm wondering if it's possible to select different values from the same queryset. I have a queryset as follows links = Model.objects.filter(some_filters) ect. return links.values('parent_id', 'child_id', 'type', 'date') What I'd like to do is return both the list above, but also a distinct list of child_ids without having to create a new query. For example if the above returns: [(1, 2, 'child', 'some_date'), (2, 3, 'child', 'some_date')] I'd like it instead to return [2, 3], [(1, 2, 'child', 'some_date'), (2, 3, 'child', 'some_date')] Is this possible without creating a new queryset? -
Field 'id' expected a number but got.list value
I m trying to fetch session cart using key value but getting error like this: TypeError: Field 'id' expected a number but got ['3', '2', '4', '6', '8']. "GET /book/cart/ HTTP/1.1" 500 134321 What I need to change: models.py class Book(models.Model): Books_cond_choice = ( ('Old Book', 'Old'), ('New Book', 'New'), ) book_id = models.AutoField book_condition = models.CharField(max_length=10, choices=Books_cond_choice) book_name = models.CharField(max_length=200) price = models.IntegerField(default=0) book_auther = models.CharField(max_length=200) pub_date = models.DateField() category = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") pagecount = models.IntegerField(default=0) desc = models.CharField(max_length=300) image = models.ImageField(upload_to='book/images', default="") def __str__(self): return self.book_name @staticmethod def get_books_by_id(id): return int(Book.objects.filter(id__in = [id])) views.py class Cart(View): def get(self, request): ids = list(request.s`enter code here`ession.get('cart').keys()) books = Book.get_books_by_id(ids) print(books) return render(request, 'book/cart.html', {'books' : books}) -
How to notify users when other users tagged them on a post - Django
So I'm a student working on a very basic social medial app, The functionality i'd like to implement is that when a user is posting something and mentions another user using "@username", the mentioned user should be notified, I'd like to have a view that shows all of your mentions and the number of them, they should also go away once you have checked the notifications page. The main question is how to go about notifying the user in the first place, I figured I should have some Notification class implemented and also a helper function that checks for '@username' pattern after every post. I've found some similar posts but they either seem over complicated and poorly explained, to me how to mention/tag users with '@' on a django developed project or the answer is just not there How to mention users using @ in django -
Count the product in main category in django
relationship is like product->subcategory->main categories. now i want to display total product under maincategories in django. like mainCat->Men's Cloth subCat-> 1)T-shirts -> 10 products subCat-> 2)Pant -> 5 products so now I want to count the total products in Men's Cloth likewise for all maincategories -
Why my domain gives me the old website while my IP address gives me the new one I deployed?
I recently bought a domain at AWS Route 53, and routed to my EC2 Instance with its elastic IP, record type A. I made a kind of reverse proxy for manual blue-green deployment.(I don't yet know how to do that automatically) My nginx version is "nginx/1.18.0 (Ubuntu)", and I'm using Django Rest Framework as backend and React JS as frontend. The below is codes which are seemed to be related with this issue. /etc/nginx/nginx.conf ...Same as default... http { ...Same as default... sendfile off; ...Same as default... include /etc/nginx/conf.d/*.conf; # include /etc/nginx/sites-enabled/*; } ...Same as default... /etc/nginx/conf.d/default.conf upstream main { server 192.168.0.1:8080; # This IP address is the gateway of docker network } server { listen 80; listen [::]:80; listen 443 ssl; listen [::]:443 ssl; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; location / { proxy_pass http://main; add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; proxy_no_cache 1; proxy_cache_bypass 1; proxy_cache off; } } PROJECT_FOLDER/docker-compose.yml version: '3.3' services: backend-blue: build: context: ./backend args: DJANGO_ALLOWED_HOSTS: stuff DJANGO_SECRET_KEY: stuff DJANGO_CORS_ORIGIN_WHITELIST: stuff BACKEND_ADMIN: stuff RDS_HOSTNAME: stuff RDS_PORT: stuff RDS_DB_NAME: stuff RDS_USERNAME: stuff RDS_PASSWORD: stuff S3_ACCESS_KEY_ID: stuff S3_SECRET_ACCESS_KEY: stuff S3_BUCKET_NAME: stuff DEBUG: stuff EMAIL_HOST_USER: stuff EMAIL_HOST_PASSWORD: stuff environment: CHOKIDAR_USEPOLLING: "true" command: gunicorn backend.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" frontend-blue: … -
Error when using objects.create() in views.py in Django
i am trying convert audio files to image files after data processing but when I try to add it images to my object I am getting an error " 'list' object has no attribute '_committed' ". Can someone please help? here is my model.py class Image(models.Model): photo = models.FileField(null=False, blank=False) class Audio(models.Model): sound = models.FileField(null=False, blank=False) views.py def home(request): if request.method == 'POST': audios = request.FILES.getlist('audios') for s in audios: #sample_rate, sound_data = wavfile.read(s) sample_rate, sound_data = scipy.io.wavfile.read(s) data_points = sound_data[:, 0].size length = data_points / sample_rate data_shape = sound_data.shape data_type = sound_data[:, 0].dtype # fourrier transform y_fourrier = np.abs(fft(sound_data[:,0])) x_fourrier = np.linspace(0.0, sample_rate, data_points, endpoint=True) y_fourrier = y_fourrier[0:data_points // 2 + 1] x_fourrier = x_fourrier[0:data_points // 2 + 1] #transform to log scale y_fourrier_db = np.log10(y_fourrier) photo=plt.plot(x_fourrier, y_fourrier_db) image=Image.objects.create( photo=photo, ) img = Image.objects.all() return render(request, 'myapp/home.html', {'img':img}) Error Screenshot Traceback (most recent call last): File "C:\Python\Python38\lib\site-packages\django\core\handlers\exception.py ", line 47, in inner response = get_response(request) File "C:\Python\Python38\lib\site-packages\django\core\handlers\base.py ", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\AI\Misc\imageuploader\myapp\views.py ", line 71, in home image=Image.objects.create( File "C:\Python\Python38\lib\site-packages\django\db\models\manager.py ", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python\Python38\lib\site-packages\django\db\models\query.py ", line 447, in create obj.save (force_insert=True, using=self.db) File "C:\Python\Python38\lib\site-packages\django\db\models\base.py ", … -
Django rest api does not save password
I want to make a user registration form. Everything works and the user is saved, but his password is not stored. When I see the user page in admin it is in the password field -> "Invalid password format or unknown hashing algorithm.". i use default user mode. this is my code -> serializers.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', ) extra_kwargs = {'password': {'write_only': True},} def create(self, validated_data): user = User( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user views.py class CreateUser(generics.CreateAPIView): permission_classes=[AllowAny] serializer_class=RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() token, _ = Token.objects.get_or_create(user=user) return Response({ "user": RegisterSerializer(user, context=self.get_serializer_context()).data, "token": token.key }) -
What does RunPython.noop() do?
In the documentation it says, "Pass the RunPython.noop method to code or reverse_code when you want the operation not to do anything in the given direction. This is especially useful in making the operation reversible." -
How do I make my e-commerce product price have a comma?
I'm making use of React, Redux and Django to build this but I have a problem in making my products price, subtotals and everything relating to price have a comma for thousands. I have set USE_THOUSAND_SEPARATOR = TRUE and DECIMAL_SEPARATOR = TRUE but still can't get the front end to have that comma sign. -
Post data from server A to Server B with Form
I want to post a set of form data from server A to Server B. Server B will require user to fill in some data then process and post back to Server A. Server A will check and show a respond. Server B will perform a logic to check the origin & referer url compare to the white list of Url then will process the data. Way of using I am using Django Class Based view function to load the form in the template. In the HTML form, the method has set to POST and action is set to Server B url. When User click the submit button. The Server B couldt detect the origin & referer Url. As per check in Google chrome, it is Null. Is anyone can share your experience on solving this problem. -
DRF authentication classes decorator not working
I have faced a problem that authentication_classes decorator is not working. Guess, there must be some error in my code views.py @authentication_classes([authentication.BaseAuthentication]) @permission_classes([permissions.IsAuthenticated]) @api_view(['GET']) def profile(request): # some logic return Response() urls.py urlpatterns = [ path(r"profile/", profile, name='profile'), ] When I send request without any auth data on this endpoint I don't get 401 error. What's wrong?