Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to exactly serialize and create of custom user using drf
I am not able to create a user, hitting the endpoint with the following request "http://127.0.0.1:8000/users/" with a following request body { "user": { "first_name": "test100", "last_name": "last100", "email": "user100@gmail.com", "username": "user100", "status": "active", "contact": 1234567890 }, "password": "test_pass_@100" } class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, blank=True, null=True) profile_image = models.ImageField(upload_to='image/%Y/%m/%d', blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) contact = PhoneNumberField(blank=True, null=True) is_staff = models.BooleanField(default=False, blank=True, null=True) is_active = models.BooleanField(default=True, blank=True, null=True) def find_by_username(self, name): return self.objects.filter(username=name) def find_by_id(self, id): return self.objects.filter(id=id) And this is my views.py class UserViewSet(viewsets.ViewSet): def list(self, request): try: queryset = User.objects.all() serializer = UserResponseSerializer(queryset, many=True) return HttpResponse(json.dumps(serializer.data), content_type="application/json") except: return HttpResponse(status=404) @swagger_auto_schema(request_body=UserRegistrationRequsetSerializer) def create(self, request, *args, **kwargs): try: serializer = UserRegistrationRequsetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return HttpResponse(serializer.data) else: return HttpResponse("Not valid") except: return HttpResponse(status=404) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserResponseSerializer(user) return HttpResponse(serializer.data) def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass this is my seralizer.py from rest_framework import serializers class UserResponseSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=255, required=True, allow_blank=False) last_name = serializers.CharField(required=True, allow_blank=False, max_length=255) email = serializers.EmailField(max_length=255, required=True, allow_blank=False) username = serializers.CharField(max_length=255, required=True, allow_blank=False) profile_image … -
Why can't the node js server tell i'm connected
I tried running this (https://github.com/dhvanilp/Hybrid-Cryptography) and everything works fine except the nodejs server can't even tell when I open the webpage. The instructions said to run the Nodejs with Django but the 2 cant seem to communicate. please help a noob out. var http = require('http').createServer().listen(4000); var io = require('socket.io')(http); var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // creating an instance of XMLHttpRequest var xhttp = new XMLHttpRequest(); // host of the server var host = 'localhost'; var port = '8000'; console.log('Listening'); // when a connection happens (client enters on the website) io.on('connection', function(socket) { // if the event with the name 'message' comes from the client with the argument 'msgObject', // which is an object with the format: {'user_name': < name >, 'message': < message >}, // it emits for every connected client that a message has been sent, sending the message to the event // 'getMessage' in the client side socket.on('receive', function(msgObject) { // emits the msgObject to the client io.emit('getReceive', msgObject); console.log(msgObject) // url of the view that will process var url = 'http://127.0.0.1:8000//'; // when the request finishes // prepares to send xhttp.open('POST', url, true); // sends the data to the view xhttp.send(JSON.stringify(msgObject)); }); socket.on('send', function(msgObject) { // emits … -
dropdown is not working need some insight
problem:-the problem is that dropdown is not working and i dont know why i looked at bootstrap docs also i am new to django and still learning code:- Home {% if user.is_authenticated %} <div class="collapse navbar-collapse"> <ul class="nav nav-tabs"> <li> <a class = 'navbar-brand mynav' href="{% url 'attendance:attend' %}">Add Attendance</a> <!-- this 'posts:create' posts is app_name and create is the name which we have given inside urlpattern --> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'attendance:attendlist' %}">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> <div class="dropdown-divider"></div> </div> </li> </ul> </nav>[enter image description here][1] [1]: https://i.stack.imgur.com/JU0cz.png -
When users select a category when creating a group Django doesn't post it to the database
Am trying to create a category models in my database and at that the same time i want user on my app to be able to select the categories that much their group they create. I want the categories with pictures as well but somehow i can't seem to figure it out. Below is the model class Category(models.Model): name = models.CharField(max_length=200, db_index=True) image = models.ImageField(upload_to='category/%Y/%m/%d', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class GroupEx(models.Model): categories = models.ForeignKey(Category, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='groups') admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="group_admin" ) cover = models.ImageField(upload_to='group_cover') group_name = models.CharField(max_length=200, blank=True) description = models.TextField(max_length=500, blank=True) group_members = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name="members") date_posted = models.DateTimeField(auto_now_add=True) Here is my function view for creating a group def create_group(request): context = {} user = request.user groups = GroupEx.objects.all() friend_list = FriendList.objects.get(user=request.user) friends = friend_list.friends.all() if request.method == 'POST': group_name = request.POST['group_name'] #category = request.FILES.get('category',False) cover = request.FILES.get('cover',False) group_name,created = Group.objects.get_or_create(name=group_name) user_obj = Account.objects.get(username=request.user.username) group_data = GroupEx(admin=user_obj, group_name=group_name, group=group_name, cover=cover) group_data.save() return redirect('group:groups') context['groups'] = groups Here is the HTML for creating groups, when users select the category it doesn't post it to the database. I don't want users to create their own categories … -
Django not rendering template after POST method
I'm trying to render the Django template after uploading a file (POST method). The issue is: I insert some print() inside the POST request.method and everything is working fine (terminal VSCode) but the template (HTML) is not being displayed inside the render() function. View.py: def index(request): if 'GET' == request.method: print("It didn't work it!") print(request.FILES['file']) return render(request, 'auditoria_app/index.html') else: print('It worked it!') excel_file = request.FILES["file"] wb = openpyxl.load_workbook(excel_file, data_only=True) wb.security.workbook_password = 'Rnip*2020' inputsCombo = wb['Inputs COMBO'] inputsDNCombo = wb['Inputs DN COMBO'] outputCombo = wb['OutPut COMBO'] faixas = wb['Faixas'] wb2 = openpyxl.load_workbook('media/sigma.xlsx', data_only=True) sigma = wb2['sigma'] sic = wb2['Performance'] # wb4 = openpyxl.load_workbook('media/ultimoContrato.xlsm', data_only=True) # ultimoContrato = wb4['Base'] numeroIbms = inputsCombo['F5'].value ibms = [] output = outputResults(numeroIbms, outputCombo) for i in range(8, 8 + numeroIbms): ibm = Ibm(i, inputsCombo, inputsDNCombo, outputCombo, faixas, sigma) ibms.append(ibm) print(ibm.numeroIbm) # sigmaReport(sigma, ibm) return render(request, 'auditoria_app/index.html', {'ibms': ibms, 'numeroIbms': numeroIbms, 'output': output, }) Message displayed on VSCode terminal: It worked it! Outside: SAE_R360_pagnussat.xlsm 1038108 1049885 [04/Sep/2021 21:18:36] "POST /auditoria/ HTTP/1.1" 200 5132 -
null value in column ... violates not-null constraint
Stack Overflow. I have a Django app that manages Item listings and Tags (categories). They are related with a ManyToMany field on the Item model. The following code is of the relevant code from the models I am using PostgreSQL as my database. #models.py class Tag(models.Model): title = models.CharField(max_length=300, unique=True) slug = models.SlugField(max_length=300, blank=True, null=True, unique=True) objects = TagManager() def generate_token(self): self.slug = get_random_string(length=15) return self.slug def save(self, *args, **kwargs): if self.slug is None: self.generate_token() super().save(*args, **kwargs) And the Item model class Item(models.Model): seller = models.ForeignKey(User,related_name='seller', on_delete=models.CASCADE) #the following lines are the problem lines tag = models.ManyToManyField(Tag, related_name='tag', blank=True) slug = models.SlugField(max_length=30, blank=True, null=True, unique=True) objects = ItemManager() def generate_token(self): self.slug = get_random_string(length=15) return self.slug def save(self, *args, **kwargs): if self.slug is None: self.generate_token() super().save(*args, **kwargs) This code ran fine until I tried adding an item from the Django Admin page. I filled in all of the fields, added two tags from the <select> menu and tried to save it. However, I was greeted with the following error message null value in column "tag_id" of relation "item_item" violates not-null constraint and DETAIL: Failing row contains (18, Item Name Here, This is the description, 40.00, items/pattern.png, lXBjgo70QIrI8aF, 1, null). This is … -
Easy Thumbnails - How to test a view that contains with ThumbnailerImageField in DRF
I have a model called "Post" that looks for example like this: # models.py from django.db import models from easy_thumbnails.fields import ThumbnailerImageField class Post(models.Model): name = models.CharField(max_length=255) cover = ThumbnailerImageField(upload_to='posts') Then I have a serializer for the model: # serializers.py class PostSerializer(serializers.ModelSerializer): cover = ThumbnailSerializer(alias='small') class Meta: model = Post fields = ['id', 'name', 'cover'] Finally I have a view: # views.py class PostView(generics.RetrieveAPIView): queryset = Post.objects.filter(enabled=True) serializer_class = PostSerializer Now inside my test I try creating a post and fetching the data (im using PyTest): # tests.py def test_post_endpoint(client): post = Post.objects.create( name="Post 1", cover="posts/test_image.jpg", ) response = client.get('/posts/') assert response.status_code == 200 print(response.data['cover']) # This prints: http://testserver/posts/ # Instead of: http://testserver/posts/test_image.small.jpg I also tried using: cover=SimpleUploadedFile( name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg' ) But this ended up uploading the image to S3 which I dont want since its just a test and it should not upload anything to the cloud. How can I get a proper response for the cover data? Something like this: 'http://testserver/posts/test_image.small.jpg' -
Only Show Edit Button On Owner's Posts - Django
I have a Django project with posts and the ability to edit posts. On the main index page, I am showing all posts, like a news feed. Currently anyone can edit any post, but I want to make it so that only the owner of the post can edit. I'm just not sure how to write the urls.py file since I'm using: path("", views.index, name="index"), I would probably need to pass either the post id or the username to this, but I'm not sure how to write it. I tried: path("index", views.index, name="index"), path("index/<str:pk>", views.index, name="index"), path("index/<str:username>", views.index, name="index"), But I get errors. index views.py def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() my_session = request.user other_user = User.objects.get(username=username) user1 = other_user.username # other person's profile user2 = my_session.username # myself return render(request, "network/index.html", { "list_of_posts": list_of_posts, "user1": user1, "user2": user2, }) html to show edit button. I've tried: {% if user1 == user2 %} <button class="btn-btn primary" my-id="{{i.id}}" id="ebutton- {{i.id}}" onclick="edit_form(this)" >Edit</button> <br><br><br> {% endif %} With this way I need to pass username to the url but I cannot, without getting errors. Overall I'm just looking for advice, on how to make the edit button only appear on posts that the … -
Add placeholder to dependent dropdown filter
I'm sure this is a simple solution but I cant figure out how to go about adding a placeholder to a dependent filter dropdown the closest I have gotten is this: class CarFilterForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['model'].queryset = Post.objects.none() self.fields['manufacture'].widget = forms.TextInput(attrs={'placeholder': ('test')})#HERE if 'model_manufacture_id' in self.data: try: model_manufacture_id = int(self.data.get('model_manufacture_id')) self.fields['model_id'].queryset = CarModels.objects.filter(model_manufacture_id=model_manufacture_id) except (ValueError, TypeError): pass class carFilter(django_filters.FilterSet): class Meta: model = Post fields = 'manufacture', 'model' form = CarFilterForm That gets me this but I don't understand how I would go about the TextInput as in the docs I don't see an options for drop down or something similar. -
Im having problem setting up api and front-end on same domain using nginx
I got a vm from azure and i was trying to set up a front-end in vue and back-end in django.However my problem is that under 1 domain i cant seem to make both of them work. This is my nginx config for vue : server { listen 80; server_name www.todoapi.xyz; return 301 https://www.todoapi.xyz$request_uri; } server { listen 443 ssl; server_name www.todoapi.xyz; client_max_body_size 4G; error_log /webapps/todo/enviroment_3_8_2/logs/nginx-vue-error.log; access_log /webapps/todo/enviroment_3_8_2/logs/nginx-vue-access.log; ssl_certificate /etc/letsencrypt/live/www.todoapi.xyz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.todoapi.xyz/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; charset utf-8; root /webapps/todo/todo_vue/dist; index index.html index.htm; location / { root /webapps/todo/todo_vue/dist; try_files $uri $uri/ =404; } } And nginx config for django : upstream todo_app_server { server unix:/webapps/todo/enviroment_3_8_2/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name www.todoapi.xyz; return 301 www.todoapi.xyz$request_uri; } server { listen 443 ssl; server_name www.todoapi.xyz; client_max_body_size 4G; access_log /webapps/todo/enviroment_3_8_2/logs/nginx-django-access.log; error_log /webapps/todo/enviroment_3_8_2/logs/nginx-django-error.log; ssl_certificate /etc/letsencrypt/live/www.todoapi.xyz/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.todoapi.xyz/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH'; location /static/ { alias /webapps/todo//environment_3_8_2/todo/static/; } location /media/ { alias /webapps/todo/todo_vue_api/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://todo_app_server; } } } From what i read on google it seemed possible to have them under the same domain however i am unable to do … -
Filtering objects returned by the relation (set.all) in Django
I am trying to solve the filtering of objects returned by set.all. I would like to display objects that are strictly assigned to the currently logged in user. Below is a pseudo-code that illustrates the situation. class Tags(models.Model) class Comment(models.Model): creator = models.ForeignKey(... related_name='example') tag = models.ManyToManyField(Tags) In the generic detail "tag" view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['author_objects'] = Comment.objects.filter(creator=self.request.user) return context In a detail tag template, I am using set.all to return the callback objects. However, these are all assigned objects, and I would like to filter them. {% for comment in tags.comment_set.all %} <a href="{% url 'comment-detail' comment.id %}">{{ comment.title }}</a> {% endfor %} I have tried many solutions to display user-created comments (even with 'author objects', nested loops) but I get all assigned objects or nothing. I suspect that the context is not working, but it was about visualizing the situation in the best possible way. -
how to render only recently added object of my model in my template
how to show only recently added object of my model instead of all in my template here is my views.py class home(View): def get(self, request): quote = Quote.objects.all() return render(request, 'home.html', {'qoutes':quote}) right now if render the object all the quote will shown to me but instead of all the model i want to render only recent quote which i added got render class Quote(models.Model): todays_Quote = models.CharField(max_length=500, blank=False) by = models.CharField(max_length=100, blank=False) created = models.DateTimeField(auto_now=True) def __str__(self): return self.todays_Quote -
Upload is not automatically | Dropzone & Django
I'm trying to upload an Excel file automatically with Dropzone but it's not happening. HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Auditoria - SAE</title> <link href="{% static 'css/style.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css"> </head> <body> <div class="container"> <form action="{% url 'auditoria_app:index' %}" class="dropzone"> {% csrf_token %} <div class="fallback"> <input name="file" type="file" /> </div> </form> <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script> </div> </body> </html> My view: def index(request): if 'GET' == request.method: return render(request, 'auditoria_app/index.html') else: excel_file = request.FILES["file"] wb = openpyxl.load_workbook(excel_file, data_only=True) Important: I don't want to save the file inside the Django server, so my intention is only to read the data inside the Excel. The file seems to load correctly in the web but the page is not being 'refreshed' after the file is ready to go to Django server! If I replace the Dropzone form with the standart HTML form, I can read all the Excel file without any problem. Thank you! -
Django - user should have is_active = False but it is showing active in admin
My custom signup view has the user's is_active set to False. They use an emailed authorized token to set is_active to True. However, immediately after I sign up as a new user, I log into the admin page as a superuser and I can see that my new user has active checked off. views def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() user.is_teacher = True user.is_staff = True user.is_active = False to_email = form.cleaned_data.get('email') user.username = to_email # make the username the same as the email user.save() group = Group.objects.get(name='teacher') user.groups.add(group) current_site = get_current_site(request) # use sendgrid api for email sendgrid_client = SendGridAPIClient( api_key=os.environ.get('SENDGRID_API_KEY')) from_email = From("doug@smartmark.ca") to_email = To(to_email) subject = "Activate your SmartMark Account" active_link = render_to_string('account/acc_active_email_link.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_text = f'Hello {user}<br/><p>Registration email</p><a href="{active_link}">{active_link}</a>' html_content = HtmlContent(html_text) mail = Mail(from_email, to_email, subject, html_content) response = sendgrid_client.send(message=mail) return redirect(reverse('accounts:account_activation_sent')) else: form = CustomUserCreationForm() return render(request, 'account/signup.html', {'form': form}) def account_activation_sent(request): return render(request, 'account/account_activation_sent.html') def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = CustomUser.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None # calls check_token function but user is already set to active - … -
Visual Studio Code no inicia el env de python que quiero
sería mi primer solicitud de ayuda por acá, una página que me ha ayudado tanto. Problema: con Visual Studio Code y su última versión me trajo este problema. Supuestamente estoy en el env (django2) donde tengo instalado django, pero no se activa el env al hacer el típico "conda activate django2" que incluso VSC hace automáticamente, después de hacer lo anterior hago un pip list y no aparece el django que tengo instalado, por lo tanto es como si NO estuviese dentro del env (django2). Les dejo la captura de mi VSC: env python con django no inicia Este problema comenzó desde que se instaló la última actualización de Visual Studio Code. ¡Saludos y buena vibra! -
translate one field of a model in django
i have this model: class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) date = models.DateTimeField(auto_now_add=True) text = models.TextField(max_length=400,null=True, blank=True) read = models.BooleanField(default=False) this model objects is created automatically in the views like this def payment_confirmation(request): if request.method == 'POST': form = paymentForm(request.POST) if form.is_valid(): amount= float(form.cleaned_data['amount']) form.save() notify = Notification.objects.create( user = request.user, text = f"{amount} $ is added to your wallet", ) trans = _('Recharge Completed successfully') messages.success(request,trans) return redirect('my_wallet') return HttpResponse("completed") I was able to translate messages and static pages but i couldn't find a way to translate this notification text field i looked some libraries but it seems to translate only the verbose_name of the field and not the value -
Django Create Extended User with Serializer
Im working on extend the Basic User model to additional fields i had created a Profile Model that should have a OneToOneRelation. I'm working with serializers. Now when i try to post e dummy user igot this error: TypeError: User() got an unexpected keyword argument 'street' if i send only the user it works well. i know that the 'street' argument is not part of the User but part of the Profile that should store later. I tried to solve this with 'request.POST.pop' for every value and parsed to dict but then no data will be transmitted. as well i got no success with Signals. Have any one a Idea how i gonna make this to work, as the user and profile will created at the same time, the user must save first and pass the id its generating to the Profile that is reference to it. Models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=CASCADE, null=True) street = models.CharField(name="street", max_length=100) number = models.CharField(name="number", max_length=10) plz = models.CharField(name="plz", max_length=10) city = models.CharField(name="city", max_length=100) phone = models.CharField(name="phone", max_length=20) locked = models.BooleanField(name="locked", default=False) Serializer.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['street', … -
Django Page not found (404) when filter services by categories using urls
I'm learning how to use urls in Django and I have a problem. I'm trying to get all services that belongs to a category by clicking on the category link, but when I do that, the browser returns me this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/services/None Raised by: services_app.views.service_list No Category matches the given query. And the url looks: http://localhost:8000/services/None I already have a populated data base, and it can display their content just using a djanfo for, but I need it to be displayed by categories. Can anyone help me? Here are my files: home_app/models.py from django.db import models from django.urls import reverse class Category(models.Model): name=models.CharField(primary_key=True, max_length=50) slug=models.SlugField(unique=True, blank=True, null=True) image=models.ImageField(upload_to='category_home') description=models.CharField(max_length=100) content=models.TextField(max_length=500, default="Service") created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('services_by_category', args=[self.slug]) services_app/models.py from django.db import models from home_app.models import Category class Services(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE) title=models.CharField(max_length=50) completed=models.DateField(auto_now_add=False, null=True, blank=True) content=models.CharField(max_length=50, null=True, blank=True) image=models.ImageField(upload_to='services_services') created=models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Service' verbose_name_plural = 'Services' def __str__(self): return '%s de %s' % (self.category, self.title) services_app/views.py from django.shortcuts import render, get_object_or_404 from .models import Services from home_app.models import Category def service_list(request,category_slug=None): category = None categories = Category.objects.all() services … -
Django does not increase quantity
As in title Django does not increase quantity of items which are already in the cart. I would be pleased for any advice. Why it happens and how can i solve this problem. models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.IntegerField(default=1000) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.IntegerField(default=0, help_text="100 = 1EUR") views.py def post(self, request, pk): if 'buy' in request.POST: item = get_object_or_404(Item, id=pk) item_quantity = request.POST.get('quantity') orderItem, created = OrderItem.objects.get_or_create(order_item=item) cart, created = Cart.objects.get_or_create(order_user=request.user) cart.save() if Cart.objects.filter(order_items=orderItem).exists(): orderItem.quantity += 1 cart.order_items.add(orderItem) cart.save() return HttpResponse('Items added to the database') -
Django notifications
Please can anyone tell me how to make db send notification automaticaly if anything added or changed in a db's table. For example if a user chnaged a value in a table i want him to reciev a notification to tell him. Thanks -
download multiple file FileField
I'm trying to use a form where I wan't to download multiple files at once, I don't know what's the problem al seems to work with no errors but when I check I find only on file downloaded. this is my model: class Delivery(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=_("delivery_user")) full_name_reciever = models.CharField(_("Reciever Full Name"), max_length=50) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.CharField(max_length=250) destination_city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=_("delivery_city")) destination_post_code = models.CharField(max_length=20) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) boxes_number = models.PositiveIntegerField(_("Number of Boxes"), default=1) boxes_wight = models.PositiveIntegerField(_("Boxes Wight"), default=1) boxes_volume = models.PositiveIntegerField(_("Boxes Volume"), default=0) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) billing_status = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def __str__(self): return str(self.created_at) view.py: class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" success_url = reverse_lazy("account:dashboard") def test_func(self): return self.request.user.is_customer and self.request.user.is_active def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist("decument") if form.is_valid(): for f in files: f.save() return self.form_valid(form) else: return self.form_invalid(form) … -
Check permission to download a media file in Django
In my Django project I want to make media files forbidden for viewing if no secret phrase passed. # setting.py ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # myapp/urls.py from django.conf import settings from django.conf.urls.static import static ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # myapp/models.py ... class File(models.Model): file = models.FileField(upload_to='files') I want to make the URL /media/files/afile.txt forbidden directly (with status 403) and readable by the URL /media/files/afile.txt?secret=mysecretphrase. I am unable to manage this issue in my view.py as usual. Maybe there is an elegant way to resolve it with a middleware or anything else... -
video implementation on my website doesn't work
So i tried to implement a video on my website (i am using django) it works when i use runserver on cmd and test it but when i push it to heroku and visit my url it only shows a black box with no video It doesn't work on any browser, i used google a lot but coldnt find a solution. It works when i upload the file to youtube and implement it like that, but i want to upload it directly from my computer My code looks like this. Is there something wrong with it? <video width="420" height="200" controls> <source src="{% static 'affiliate/assets/img/portfolio/c.mp4' %}" type ="video/mp4" /> <source src = "{% static 'affiliate/assets/img/portfolio/c.webm' %}" type = "video/webm"/> </video> -
Django models.TextChoices vs models.IntegerChoices
What is the difference between these two codes? Code 1: class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') Code 2: class YearInSchool(models.IntegerChoices): FRESHMAN = 1, _('Freshman') SOPHOMORE = 2, _('Sophomore') JUNIOR = 3, _('Junior') SENIOR = 4, _('Senior') GRADUATE = 5, _('Graduate') Why does everybody use models.TextChoices, although using models.IntegerChoices and models.PositiveSmallIntegerField will take less memory? Am I missing something that I am not understanding well? When to use models.TextChoices over models.IntegerChoices or vice versa? I am asking this question because at every django code I am reading, the programmer uses text choices. I am talking generally, even for django versions earlier than 3. -
How to stop user from running malicious python code in online compilers
I am developing an online compiler wherein user can run python code.My requirement is to run that python code on server side with exec. So I researched on how can I completely eliminate some user running malicious python code and most of the sites suggested this - built-ins disabled Ptrace and chroot jail Sandboxing/VM But if I store a list of blacklisted commands e.g - ["exec","os","subprocess"] and check the string code for presence of any blacklisted commands and discard it on client side as well as server side then doesn't it solve the problem?