Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, can I have one model field whose value is the highest value in a one-to-many relationship?
I have two models. One represents several groups, and the other represents people in those groups with a ranking. I would like to have a field in the groups model that represents the highest ranked person inside that group. Is this possible? For example: Groups: id name highest 1 alpha gold 2 bravo diamond People: name group rank Dave 1 silver bob 1 gold dilan 1 silver arthur 2 gold mark 2 diamond -
Sending email from another SMTP with Django
I am using Django to send emails. I have everything setup to send emails using the normal method of filling out the variables in settings.py DEFAULT_FROM_EMAIL = 'xxxx' SERVER_EMAIL = 'xxxx' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = SERVER_EMAIL EMAIL_HOST_PASSWORD = 'xxxx' I setup a contact form that I want to use another SMTP server for. I am doing this by using this code: with get_connection( host='smtp.gmail.com', port=587, username='myemail@gmail.com', password='mypassword', use_tls=True ) as connection: EmailMessage('subject1', 'body1asdfasdf', 'bob@yahoo.com', ['myemail@yahoo.com'], connection=connection).send() Now from my understanding when I get this email it should show as from 'bob@yahoo.com'. But when I am getting it, it is still showing it is from 'myemail@gmail.com' I have even tried adding reply_to='bob@yahoo.com' in the EmailMessage but that did not work either. -
Django Rest - Update not saving
I have two Model, Partner and PartnerAddress, Partner hasOne PartnerAddress. I trying to update this Related field, However the field is not save after update. My ModelViewset class PartnerViewset(viewsets.ModelViewSet): queryset = Partner.objects.all() serializer_class = PartnerSerialzer filter_backends = (filters.DjangoFilterBackend,) def update(self, request, *args, **kwargs): # instance = self.queryset.get(pk=kwargs.get('pk')) # instance.name partner_address = request.data.get('partner_address') try: instance = Partner.objects.get( partner_address=partner_address['id']) except Partner.DoesNotExist: instance = None serializer = PartnerSerialzer( instance, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) Sorry I'm still new to Django. Any help will be appreciate of all ur help. Thanks :) -
Should Django-specific Python packages require Django?
I was looking at the setup.py file for django-mailbox and noticed that Django is not listed in install_requires. Django is imported in many different places in the package, so the django-mailbox package definitely requires Django. Is Django not listed so the desired version of Django can be chosen beforehand? More specifically, is it a best practice to not require Django when developing a Django-specific package? ... or is this just a bug in django-mailbox? -
When I change the language of the website, the slug is not translated causing a 404 error
I'm new programming with Django. I'm currently using version 2.2 for my first project. So far it's going well, my website consists of a landing page with a product catalog which has to work in two languages: English and Spanish. My problem is that when I try to change a URL from English to Spanish or from Spanish to English, I get a 404 error because the product slug does not get translated. Let me explain. For a product, I have a URL structure in English: mywebsite.com/products_en/item-name_en In Spanish, it would be: mywebsite.com/products_es/item-name_es Both links work well, as long as the corresponding language is active. The problem is that, for example, if I am on the English product page and try to switch to the Spanish page, it tries to take me to mywebsite.com/products_es/item-name_en I know this question has been already asked here on Stack Overflow but the answers didn't get me to the solution How can I avoid this? Thank you in advance. -
QuerySet Nested Within Other Querysets
I have multiple models: class Student(models.Model): unit_packages = models.ManyToManyField(UnitPackage, related_name='student') class UnitPackage(models.Model): individual_units = models.ManyToManyField(Unit, related_name='individual_unit') class Unit(models.Model): [...] class StudentUnitData(models.Model): student = models.ForeignKey(Student) unit = models.ForeignKey(Unit) package = models.ForeignKey(UnitPackage) I have a student and I am able to get their packages and the units for each package: user_packages = UnitPackage.objects.filter(student=user.student).prefetch_related('individual_units') And output them like this: {% for package in user_packages.all %} [...] {% for unit in package.individual_units.all %} [...] #? -> {% display 'unit_data' of this 'student' of this 'package' for this 'unit' %} [...] Now I am trying to get the unit_data for each unit in each package the student has (in my view). I have tried chaining a select_related onto the end of my queryset above but have had no luck. Thank you. -
Getting 403 on post despite no database calls in view and csrf_exempt tag in place
I want to do something very simple, that does not require CSRF, but a post request is required. I stripped my function to everything but the following, and I still get a 403 (forbidden) error when calling the endpoint. I even commented out the CSRF middleware, and still was getting the 403. Any advice would be very appreciated! the function: @csrf_exempt @api_view(['POST', 'GET']) def dummy_test(request): logger.error(request) return Response({'this worked!': "correct format"}, status=status.HTTP_201_CREATED) -
django filter function not responding
I'm creating a filter function for my order list by following this tutorial https://www.youtube.com/watch?v=G-Rct7Na0UQiews.py from youtube , but my filter functions seems to be not responding. When I click on submit It doesn't give me any kind of error on the template and on terminal I get this request " [14/Jul/2020 02:23:28] "GET /orderlist/?status=Received HTTP/1.1" 200 10477". def order_list(request): if request.user.is_superuser: order_list = Order.objects.all() paginator = Paginator(order_list, 5) myFilter = OrderFilter(request.GET, queryset=order_list) order_list = myFilter.qs else: order_list = Order.objects.filter(user=request.user) paginator = Paginator(order_list, 10) page = request.GET.get('page') try: order = paginator.page(page) except PageNotAnInteger: order = paginator.page(1) except EmptyPage: order = paginator.page(paginator.num_pages) context = { 'object_list':order, 'order': order, 'myFilter': myFilter, } return render(request, "order_list.html", context) filters.py import django_filters from .models import Order class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = ['status', 'date_created', 'manu_date'] order_list.html <form method="GET"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <table id="table_id"> <body> <div> <thead class="bg-secondary"> <tr> <th scope="col">Order ID</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Phone</th> <th scope="col">Shipping method</th> <th scope="col">Language</th> <th scope="col">No. of Box</th> <th scope="col">Print Name</th> <th scope="col">Date Created</th> <th scope="col"> Status </th> <th scope="col">Manufacturing Date</th> <th></th> <th></th> <th></th> <th scope="col"><button type="button" class="btn btn-dark js-create-order" data-url="{% url 'accounts:create-order' %}"> <span class="glyphicon glyphicon-plus"></span> Create </button></th> </tr> </thead> {% … -
Django Mezzanine model creating two objects
I am using the Mezzanine CMS for Django to create a blog, and I wanted a separate page for a list of my personal projects. What I did was pretty much copy the BlogPost model from Mezzanine and called it Projects. Everything I needed was in the BlogPost model, so I decided against creating my own. I assumed copying over the code for BlogPost would work, and it kind of did. My issue lies when I go to the admin page to create a new project in the projects panel. When I create the new project, it is successfully created. So, I see it in the projects panel. When I go to my blog posts panel, I also see the project I just created. Every time I make a blog post, it does not show up in the projects panel. I need to create a project and have it not show up in the blog posts panel. Did I mess up by basically inheriting the BlogPost model for my Projects model? How can I create a project without it creating a blog post? Here is my app/models.py: from django.db import models from mezzanine.blog.models import BlogPost, BlogCategory # Create your models … -
How to create save a wav file in Django from UnityWebRequest
Now,I'm having a trouble to save the waveform audio file using Django model from unity webrequest.This is my attempts On Unity IEnumerator UploadAudioSource(byte[] input) { List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("inputAudioClip", input, "byte[]")); UnityWebRequest www = UnityWebRequest.Post(downloadURL, formData); www.chunkedTransfer = false; yield return www.SendWebRequest(); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log("Form upload complete!" + www.downloadHandler.text); } } On Django views.py def onRecieve(request): if request.method == "POST": existingFiles = speechToText.objects.all() for existingfile in existingFiles: existingfile.incomingSpeech.delete(save = True) existingfile.delete() event = speechToText() datas = request.POST.get('inputAudioClip') data_byte = datas.encode('UTF-8') content = ContentFile(data_byte) event.incomingSpeech.save("input.wav", content, save=True) event.outputText = "output texts" event.save() Somehow, I believe that when using doing POST request, bytes will convert to string. So, the problems is when I'm using this code the wav audio file will be corrupted. Do anyone of you have a solutions to this? -
Passing data from React form to Django
I am running a Django server with the frontend based on Reactjs (Ant Design specifically). However, I faced a problem when I was trying to pass the data from a React form to the Django backend: the data never made it through. Please assume that all the {whatever_url} in this file is already defined. The headers are also ignored as there are no import errors. auth_login.js function getCookie(name) { // As there are no permission errors so far, the contents in // this function is ignored. Please ask for it if anyone // needs it for any purpose. } class NormalLoginForm extends React.Component { constructor(props) { super(props); this.state = {username: '', password: ''}; this.handleUsernameChange = this.handleUsernameChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleUsernameChange(event) { this.setState({username: event.target.value}); } handlePasswordChange(event) { this.setState({password: event.target.value}); } handleSubmit(event) { console.log(this.state.username); // Output see below (1) console.log(this.state.password); let csrftoken = getCookie('csrftoken'); fetch('/account/login', { credentials: 'include', method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body: { "username": this.state.username, "password": this.state.password } }) .then((response) => {console.log('message: ', response);}) // Output see below (2) .catch((error) => {console.error('Error:', error);}); } render () { return ( // I am able to successfully retrieve the data (see output below) from … -
Change admin form field with a custom one
I got a Category model class Category(models.Model): name = models.CharField(max_length=120,default='', verbose_name=_('name')) color = ColorField(default='#FF0000') and a Product model class Product(models.Model): name = models.CharField(max_length=120) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None) ... In the Product admin page, I want to make the category drop-down to show the name with the category's color. With help from this question: Django form field choices, adding an attribute I manage to make a colored category field in my admin page: This is the code (added to product/admin.py): class SelectWOA(Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option_dict = super(SelectWOA, self).create_option(name, value, label, selected, index, subindex=subindex, attrs=attrs) #Category.objects. try: option_dict['attrs']['style'] = 'color: ' + Category.objects.get(name=label).color + ';' except: pass return option_dict from django.forms import ChoiceField, ModelChoiceField from category.models import Category class ProductAdminForm(ModelForm): test_field = ModelChoiceField(queryset=Category.objects.all(), widget=SelectWOA()) class Meta: model = Product exclude = ['category'] fields = ('name', 'image', 'image2', 'category', 'test_field',) from django.db import models class ProductCastumAdmin(admin.ModelAdmin): form = ProductAdminForm but the test_field does not know I want it to "connect" to the category field and replace it. So when I save the form, the data I put inside test field is not saved as the category. My question is after I excluded the category field, … -
gunicorn_start failing No module Found
Hi guys Im having some trouble deploying in Ubuntu VPS. I have in / directory a dir called webapps and inside my folder "EntornoCursoDjango" that is my virtual environment. Inside this folder I have my dir project "ProyectoEmpleados". When running gunicorn_start file I have this error: This is my gunicorn_start file: -
Django Elastic Beanstalk Secret Variables
I want to secure my secret variables for my django project, which is deployed on AWS Elastic Beanstalk. I've seen others use environment variables and am wondering if this is secure. Or, is it more secure to use KMS? Thanks! -
NoReverseMatch at /polls/2/
Django version: 3.0.8 Python version: 3.8.0 I'm doing a Django tutorial and I ran into this error below "detail.html" below {% extends 'polls/base.html' %} {% block main_content %} <h1>{{question.question_text}}</h1> {% if error_message %}<p><strong>{{error_message}}</strong></p>{% endif %} <form action ="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name = "choice" id="choice{{forloop.counter}}" value="{{choice.id}}"/> <label for="choice{{forloop.counter}}">{{choice.choice_text}}</label><br> {% endfor %} <input type="submit" value="vote"/> </form> {% endblock %} "base.html" below <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Base</title> </head> <body> <hr> <p> Header </p> <hr> {% block main_content %} {% endblock %} {% include "polls/footer.html" %} </body> </html> If anyone can help with this, I would appreciate it. -
Using Django's prefetch_related on complex queries
I have the following basic query in my APIView: categories = UserCategorizationType.objects.all() In the serializer, I have setup eager loading for all foreign keys and one-to-many relationships as well. However, now I need to setup eager lading for a field that is added by the serializer of UserCategorizationType. Basically, for each result in categories, I want to append a field called "possibleValues". I do this in my serializer like so: class UserCategorizationTypeWithApprovedValuesSerialiser(BaseSerializer): possibleValues = serializers.SerializerMethodField() def get_possibleValues(self, categorizationType_): #-- get all approved values and user's own values values = UserCategorizationValue.objects.filter( Q(categorizationType=categorizationType_) & ( Q(categorizations__in=UserCategorization.objects.filter(author=self.__userProfile)) | Q(state="APPROVED") ) ).distinct() serializer = UserCategorizationValueSerializerValueOnly(values, many=True) return serializer.data My question is how do I use prefetch_related for this sort of query? I want this query to ideally stay in the serializer because there are multiple views that obtain categories and I want to encapsulate the way possibleValues are added into a category. -
On Heroku, redirect doesn't work even though it works on localhost
I developed Django web service and deploy to Heroku. However, redirect doesn't work only on Heroku.The code is following(for people who came for the first time): def index(request): if not ('user_id' in request.COOKIES): return redirect('main:getting_started') This should redirects https://remind-archives.herokuapp.com/main/ to https://remind-archives.herokuapp.com/main/getting_started but 404 error happens. What could be the cause? -
Django: the command 'py manage.py runserver' isn't showing any output
the command py manage.py runserver isn't showing any output and as far as I could tell isn't opening a server either. I couldn't even get passed the first tutorial in the official django docs. C:\Users\sruls\OneDrive\Desktop\the big fat coding folder\django\django_learn> py manage.py runserver C:\Users\sruls\OneDrive\Desktop\the big fat coding folder\django\django_learn> I have tried reinstalling Django and it didn't help -
Restricting/limiting number of times a model.foreignkey choice can be chosen in python django (fantasy sports website)
I am in the process of making a fantasy sports website. The django out-of-the-box User equals a team owner. On my blog/models.py file, I created a class of Player (aka an NBA player) with a foreignkey field of player_owner pointing back to User: # blog/models.py class Player(models.Model): player_full = models.CharField(max_length=50) player_owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) image = models.ImageField(default='default_player.jpg', upload_to='player_pics') player_unit_value = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(1)]) As you can see, I also have a field on the Player class called player_unit_value set permanently to 1. This, i think, will come into play with my question. I have a lot of the website set up: Free Agents Page, Team Dashboard, Player Profile, financials etc all built out with form validation to ensure players are "signed" and "dropped" by the authorized signed-in User (aka team owner). # blog/views.py class PlayersUpdateView(LoginRequiredMixin, UpdateView, Player): model = Player fields = [] template_name = 'blog/player_form.html' # <app>/<model>_<viewtype>.html context_object_name = 'guys' def form_valid(self, form): form.instance.player_owner = self.request.user return super().form_valid(form) Thus, when you click "add player" on my site, that player's player_owner field is updated from "None" to the User. and the "Drop Player" button does the reverse. So here is my question: How can I create a logic … -
Django modeltranslation for AJAX request
I have installed the Django modeltranslation package and almost everything works fine... The only thing that doesn't are the AJAX requests, whose JsonResponses are still coming back in the original language. I couldn't find in the docs how to fix it. I'm using the 'django.middleware.locale.LocaleMiddleware' middleware, so the LANGUAGE_CODE selection should be based on data from the request (i.e. the user's browser settings). Apparently, AJAX requests are not getting the memo. Is there a way to let the server knows the LANGUAGE_CODE incoming from an AJAX request (other than hard coding it in the URL)? -
pass ajax data to django model with many to many relationship
I've been working on this for a while and Im stumped. I've been reading through the docs... https://www.django-rest-framework.org/api-guide/relations/#nested-relationships and still cant make sense of how this is supposed to work. If someone could help me solve this error or explain how this is supposed to work I would be very happy to get some help. Thanks What I want: send ajax to django rest framework api endpoint have django / DRF save many-to-many related data in postgreSQL db What I've got: TypeError: Session() got an unexpected keyword argument 'pose_list' models.py class Pose(models.Model): name = models.CharField(max_length=100, blank=False, default='') def __str__(self): return self.name class SeshPoseList(models.Model): order = models.PositiveIntegerField() pose_fk = models.ForeignKey(Pose, on_delete=models.CASCADE) class Session(models.Model): session_name = models.CharField(max_length=100, blank=False, default='') def __str__(self): return self.name serializers.py class PoseSerializer(serializers.ModelSerializer): class Meta: model = Pose fields = ('id', 'name') class SeshPoseListSerializer(serializers.ModelSerializer): def create(self, validated_data): return Session.objects.create(**validated_data) class Meta: model = SeshPoseList fields = ['order', 'pose_fk'] class SessionSerializer(serializers.ModelSerializer): pose_list = SeshPoseListSerializer(many=True) def create(self, validated_data): return Session.objects.create(**validated_data) class Meta: model = Session fields = ('id', 'session_name', 'pose_list') views.py @api_view(['GET', 'POST', 'PUT', 'DELETE']) def session_list(request): if request.method == 'POST': seshSerializer = SessionSerializer(data=request.data) if seshSerializer.is_valid(): seshSerializer.create(seshSerializer.validated_data) return Response(seshSerializer.data, status=status.HTTP_201_CREATED) print("sesh errors ---> ", seshSerializer.errors) return Response(seshSerializer.errors, status=status.HTTP_400_BAD_REQUEST) -
dumpdata/loaddata BInaryField results in Incorrect Padding error ondeserialization
As the subject says, I have a legacy database that stored binary blobs within the database. I'm working to do a data migration, running dumpdata without any issues, but when I try to loaddata it always fails with a django.core.serializers.base.DeserializationError: Problem installing fixture 'data.json': Incorrect padding: error. As best I can tell this is related to Django b64 encoding the binary field and then trying to restore it. I've tested it by b64 encoding the field myself and there is no issue with the field contents, any thoughts if the problem is with dumpdata or loaddata and how it might be solved? Thanks -
how to filter by pk_set in m2m_changed
i want to to update field whenever an instance been created i tried signals but it seems complicate to ManyToManyField def update_m2m(sender,instance,*args,**kwargs): if kwargs.get("pk_set"): pk = kwargs.get("pk_set") Imei.objects.filter(pk=pk).update(active=False) #and also tried this but still not work #Imei.objects.filter(pk=instance.id).update(active=False) m2m_changed.connect(update_m2m,sender=SelectMobile.imei.through) not updated , and print nothing this models.py class SelectMobile(models.Model): #others imei = models.ManyToManyField(Imei) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i want to update active field in Imei model when SelectMobile created !? is there something i've missed ?thanks for helping -
Getting "|as_crispy_field got passed an invalid or inexistent field" with a field that exists
I'm using django-crispy-forms, and have run across an issue where one of my form fields won't render. The error I'm getting is telling me that the form field is either inexistent or invalid, but it definitely exists, and it's pretty much copied from other form fields that work properly on other pages. So I don't really see how it is either of those. Here's the relevant code: forms.py class AddSkillsForm: all_skills = forms.CharField( label="Skills ", widget=forms.HiddenInput(), required=False ) view.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}{{ course.name }}{% endblock %} {% block content %} {% include 'course/partial/nav.html' with course=course active_breadcrumb=None %} <div class="card"> <div class="card-header"> {% include 'course/partial/menu.html' with course=course %} </div> <div class="card-body"> <dl class="row"> <dt class="col-sm-3">Name:</dt> <dd class="col-sm-9">{{ course.name }}</dd> <dt class="col-sm-3">Number of Students:</dt> <dd class="col-sm-9">{{ total_students }}</dd> <dt class="col-sm-3">Sections:</dt> <dd class="col-sm-9"> {% for section in sections %} <p>{{ section.name }}</p> {% endfor %} </dd> </dl> </div> <div class="card-body"> <p>First, you'll need to import any existing students and groups from Canvas</p> <a class="btn btn-primary" href="{% url 'import_students_and_groups' course.id%}"> Import Students and Groups from Canvas </a> <div id="skill_box"> <p>If you would like to use self-reported student skills to form teams, you can define the … -
data not showing in data base django postgresql
i have to add data in database ,but after i click on sign up button i see my data in the python shell .but the data is not added in the database. i am using postgresql. this is my code for register def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] user = User.objects.create_user(username=username,email=email,password=password1) user.save() return redirect('login.html') else: return render(request,'login.html') my python shell shows this-> [14/Jul/2020 03:31:58] "GET /register?csrfmiddlewaretoken=znOO3WMBIwzO1Q8DhqgsX4Xj8pGNrBkY0p27uYSefVyGi6QaNaMjdmsBD2R5jVbt&userame=hello&email=hello%40hello.com&password1=hello&password2=hello HTTP/1.1" 200 1173 my imports in views.py -> from django.shortcuts import render,redirect from .models import profile from django.contrib.auth.models import User,auth