Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Radio buttons are rendering on top of rest of form
I'm using vanilla bootstrap with Python on Django. I've configured a form with radio buttons, however the buttons render on top of the fields as shown in the screenshot below. I've notice that Django puts the radio buttons into a list and I thought that could be the cause, so I tried using CSS to disable the tag but the radio buttons still float on top just without the list bullets. Forms.py class MerchantGroupForm(forms.Form): DO_WHAT_CHOICES=[('merge','Merge'), ('update','Update')] #do_what = forms.ChoiceField(choices=DO_WHAT_CHOICES, widget=forms.RadioSelect(attrs={'class': "custom-radio-list"})) do_what = forms.ChoiceField(choices=DO_WHAT_CHOICES, widget=forms.RadioSelect) merge_merchantgroup = forms.ModelChoiceField(required=False, queryset=MerchantGroup.objects.all().order_by('name'), empty_label="Merge with") name = forms.CharField(required=False) default_ledger = GroupedModelChoiceField(required=False, queryset=Ledger.objects.all().order_by('coa_sub_group__name','name'), choices_groupby = 'coa_sub_group') disable_AI = forms.BooleanField(required=False, label='Disable AI') <form action="/monzo/merchantgroups/update/799/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="ZWtsz3JDsnUtu1mj6NO3SDlBuyJyEpDgbZUDC6elfTPK2DCwWevD2BpirSZJOhiM"> <div class="form-group"> <label for="id_do_what_0">Do what:</label> <ul id="id_do_what" class="custom-radio-list form-control"> <li><label for="id_do_what_0"><input type="radio" name="do_what" value="merge" class="custom-radio-list form-control" required id="id_do_what_0"> Merge</label> </li> <li><label for="id_do_what_1"><input type="radio" name="do_what" value="update" class="custom-radio-list form-control" required id="id_do_what_1"> Update</label> </li> </ul> </div> <div class="form-group"> <label for="id_merge_merchantgroup">Merge merchantgroup:</label> <select name="merge_merchantgroup" class="form-control" id="id_merge_merchantgroup"> <option value="" selected>Merge with</option> <option value="203">ATM</option> <option value="799">Amazon</option> <option value="200">Post Office</option> <option value="201">Virgin Media</option> <option value="202">www.modelsport.co.uk</option> </select> </div> <div class="form-group"> <label for="id_name">Name:</label> <input type="text" name="name" value="Amazon" class="form-control" id="id_name"> </div> <div class="form-group"> <label for="id_default_ledger">Default ledger:</label> <select name="default_ledger" class="form-control" id="id_default_ledger"> <option value="">---------</option> <optgroup label="Accounts"> <option value="20">Jacks Account</option> … -
Is Mongodb better than Cassandra to be used as a database for my Django and react native project
Being new to Django and learning about it to work on my project along with react native I wanted to know if mongodb is better for working with db than apache Cassandra because I recently did some research on mongo db and found out about djongo but still wanted to know that is there a better database out there to work with in Django and react native . -
django.core.exceptions.FieldError: Unknown field(s) ( message) specified for Message in django error
form.py ( consider all imports ) can anyone point out error that we i am getting message is unknown field class emailForm(forms.ModelForm): class Meta: model = Message fields = ['receiver','subject' ,' message'] labels ={'receiver':'receiver','subject':'subject' , 'message' : ' message'} widgets = {'receiver':forms.TextInput(attrs={"class":'form-control'}),'subject':forms.TextInput(attrs={"class":'form-control'}),'message':forms.Textarea(attrs={"class":'form-control'}),} models.py ( considering all imports ) class Message(models.Model): sender = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='receiver') subject = models.CharField(max_length=1200) message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.message views.py ( importing all ) def home(request): form = emailForm(request.POST) if request.method == 'POST' or 'GET': if form.is_valid(): email= request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') user = Message(receiver=email , subject=subject ,message = message ) user.save() form =emailForm() return redirect('inbox') # return redirect('addpost.html') else: form =emailForm() return render(request,"home.html",{'message':form}) -
Datatable save and load table state with Django
Has anyone used Datatable.net library - https://datatables.net/ I want to save the state of the table in the database like column visibility and order. With stateSaveCallback I get all these in a JSON. I wrote an API that saves this data in a SQL table. And on reloading, I want to render the table with the saved state changes. var tableSumm = $('#summary_table').DataTable({ stateSave: true, stateSaveCallback: function (settings, data) { console.log(this.attr("id")) console.log('SAVE', data); var URL = window.location.origin + '/api/state/' + this.attr("id") + '/' fetch(URL, { method: 'POST', dataType: 'json', headers:{ 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() 'X-CSRFToken': csrftoken }, body:JSON.stringify(data), success: function () {} }) }, stateLoadCallback: function (settings, callback) { console.log('Load', data); var URL = window.location.origin + '/api/state/' + this.attr("id") + '/' fetch(URL, { headers:{ 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', //Necessary to work with request.is_ajax() } }) .then(response => { return response.json() //Convert response to JSON }) },} There are 2 callback methods available to achieve this, stateSaveCallback and stateLoadCallback. I have tried implementing them in my project but was not been able to successfully achieve it. I want the state to be saved in SQL server. I wrote an API that uses saveStateCallback and … -
How to allow user to toggle between color themes in a Django
So I'm working on a Django website and want visitors to the site to click the theme they want. I was able to do it with pure Html/css and Javascipt but now that im moving everything in Django it's not working. I think maybe its my path set up. Fisrt the code in my index.html <h5 style="text-align: center;line-height: 0;">Personalize Theme</h5> {% load static %} <script type="text/javascript" src="../../static/pythonicThinking/script.js"></script> <div id="theme-options-wrapper"> <div data-mode="light" id="light-mode" class="theme-dot" ></div> <div data-mode="blue" id="blue-mode" class="theme-dot"></div> <div data-mode="green" id="green-mode" class="theme-dot"></div> <div data-mode="purple" id="purple-mode" class="theme-dot"></div> </div> <p id="settings-note">*Theme settings will be saved for<br>your next visit</p> </div> the javacript file console.log('Its working') let theme = localStorage.getItem('theme') if(theme == null){ setTheme('light') }else{ setTheme(theme) } let themeDots = document.getElementsByClassName('theme-dot') for (var i=0; themeDots.length > i; i++){ themeDots[i].addEventListener('click', function(){ let mode = this.dataset.mode console.log('Option clicked:', mode) setTheme(mode) }) } function setTheme(mode){ if(mode == 'light'){ document.getElementById('theme-style').href = 'default.css' } if(mode == 'blue'){ document.getElementById('theme-style').href = 'blue.css' } if(mode == 'green'){ document.getElementById('theme-style').href = 'green.css' } if(mode == 'purple'){ document.getElementById('theme-style').href = 'purple.css' } localStorage.setItem('theme', mode) } the setting.py file # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) the urls.py file from django.views.generic import … -
My order is not being saved. forms in django
Here you can see my models.py. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) imya = models.CharField(max_length=200, null=False) familiya = models.CharField(max_length=200, null=False) tel = models.CharField(max_length=200, null=False) address = models.CharField(max_length=200, null=False) city = models.CharField(max_length=200, null=False) state = models.CharField(max_length=200, null=False) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) Here you can see my forms.py. Here I just created forms, but, the data should be got from template inputs. from django import forms from django.forms import ModelForm from .models import * class OrderForm(forms.ModelForm): class Meta: model = Order fields = '__all__' views.py def checkout(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] form = OrderForm() if request.method == 'POST': name = request.POST.get('name') surname = request.POST.get('surname') email = request.POST.get('email') number = request.POST.get('number') address = request.POST.get('address') city = request.POST.get('city') state = request.POST.get('state') form = OrderForm(request.POST) if form.is_valid(): Order.object.create( imya=name, familiya=surname, tel=number, adres=address, city=city, state=state, ) form.save() return HttpResponse('Заказ отправлен', safe=False) context = {'items':items, 'order':order, 'cartItems':cartItems, 'form':form} return render(request, 'store/checkout.html', context) In my views, I want to create an object for my order model. I tried this code, It's not giving any errors, but it's not working. PLease, help with saving the order. -
learning django and i getting this, TemplateSyntaxError, message
16 {% if request.user.is_authenticated %} 17 <ul class="menu"> 18 <li {% if section=="dashboard" %}class="selected" {% endif %}> 19 <a href="{% url 'dashboard'%}">My dashboard</a> 20 </li> 21 28 {% endif %} this is the code thats giving me the error i don't know what am i doing wrong error message: Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' -
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 …