Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upgrade python from 2.7 to 3.4 in virtual environment
I have a virtual machine on rhel 7 that comes along with a built in package of python 2.7 , now i have a created a virtual environment for Django where few libraries are expecting the Python version to be 3.4 or version's more than that. I am not able to Upgrade python inside my Django virtual environemnt , i tried out many update commands to have it from 2.7 to 3.5 but it isn't working out. For Example: pip install Python --upgrade Requirement already up-to-date: Python in /usr/lib64/python2.7/lib-dynload (2.7.5) Please let me know how do i upgrade my Python to a higher version in Django virtual env. -
Dynamic form to represent different filter attributes
I want to make a dynamic form to filter different attributes like color, size, brand etc how can I make the following form dynamic. I want it such that if a user adds another attribute then the form should automatically display the filter for the new attribute My hardcoded form is as follows: class Att(django_filters.FilterSet): q1 = AttributeChoiceValue.objects.filter(attribute__name='color') q2 = AttributeChoiceValue.objects.filter(attribute__name='size') color = django_filters.ModelMultipleChoiceFilter( queryset=q1.values_list('name', flat=True).distinct(), widget=forms.CheckboxSelectMultiple) size = django_filters.ModelMultipleChoiceFilter( queryset=q2.values_list('name', flat=True).distinct(), widget=forms.CheckboxSelectMultiple) class Meta: model = AttributeChoiceValue fields = () my models are class ProductAttribute(models.Model): slug = models.SlugField(max_length=50, unique=True) name = models.CharField(max_length=100) op = models.CharField(max_length=20,default='in') class Meta: ordering = ('slug', ) class AttributeChoiceValue(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100) attribute = models.ForeignKey( ProductAttribute, related_name='values', on_delete=models.CASCADE) class Meta: unique_together = ('name', 'attribute') -
500 Error With Api to Server, Swift To Django
I'm trying to post to my server but, I get a 500 Error when I make the request directly from my Swift app. With cURL and Postman, I can make the request with no issues. All I should need to do is pass two pieces of information to the server: Header and Body. Here is the way I'm calling from Swift. I'm using Alamo Fire to make the request and this is how I have it set up: func requestServer(_ method: HTTPMethod,_ path: String,_ body: [String : Any]?,_ encoding: ParameterEncoding,_ headers: [String : Any]?,_ completionHandler: @escaping (JSON) -> Void){ let url = baseURL?.appendingPathComponent(path) refreshTokenIfNeed { Alamofire.request(url!, method: method, parameters: body, encoding: encoding, headers: nil).responseJSON{ (response) in switch response.result { case .success(let value): let jsonData = JSON(value) completionHandler(jsonData) break case .failure: completionHandler(nil) break } } } } In the requests, I need to pass a header with a an authorization token and the body with the order Id of the order the driver wants to pick up. Here are two functions I'm working with now: // API - Picking up a ready order func pickOrder(orderId: Int, completionHandler: @escaping (JSON) -> Void) { let path = "api/driver/order/pick/" let headers: [String: Any] = … -
string + replaced by whitespace
I'm developing an app using Django rest framework while getting query object from the request the string containing + character is replaced by whitespace. html javascript code: query = 's9+'; $.get("/api/v1/autocomplete?query=" + query, function(data, status){ str = JSON.stringify(data, null, 4); document.getElementById("response").innerHTML = str; }); Django rest framework code: def get(self, request): search_query = request.GET.get('query', None) print("search_query " + search_query) Django code print s9 instead of s9+. How to prevent Django from auto converting + in the string to whitespaces? -
Parameter 'request' value is not used in the views of django
in the first image of views request value is not used [views/student.py][1] [urls.py][2] [students/home_t.html][3] [models.py][4] [1]: https://i.stack.imgur.com/yycFG.png [2]: https://i.stack.imgur.com/1kAl7.png [3]: https://i.stack.imgur.com/vLLip.png [4]: https://i.stack.imgur.com/Bu6Ih.png -
Linking to other Foreign Model with DetailView and Formset in Django
I am new to django-formset. I have been trying to find a way to link the models at formset (Model_CustomerCart and Model_CustomerCartItem) with the other model named Model_ItemPrice. Such that with DetailView, the html page can display a list of items and also their corresponding price. Does anyone know a way to make this happens? My code is below. models.py class Model_ItemIndex(models.Model): item_name = models.CharField(max_length = 50, null = True, blank = False) class Model_ItemPrice(models.Model): item_name = models.ForeignKey(Model_ItemIndex, null = True, blank = False) item_price = models.FloatField(null = True, blank = False) class Model_CustomerCart(models.Model): customer_name = models.CharField(max_length = 50, null = True, blank = False) class Model_CustomerCartItem(models.Model): customer_name = models.ForeignKey(Model_CustomerCart) item_name = models.ForeignKey(Model_ItemIndex) forms.py class Form_ItemIndex(forms.ModelForm): class Meta: model = Model_ItemIndex fields = [ "item_name", ] class Form_ItemName(forms.ModelForm): class Meta: model = Model_ItemName fields = [ "item_name", "item_price", ] class Form_CustomerCart(forms.ModelForm): class Meta: model = Model_CustomerCart fields = [ "customer_name", ] class Form_CustomerCartItem(forms.ModelForm): class Meta: model = Model_CustomerCartItem fields = [ "customer_name", "item_name", ] Formset_customercartitem = forms.inlineformset_factory( Model_CustomerCart, Model_CustomerCartItem, form = Form_CustomerCartItem, extra = 3 ) views.py class View_CustomerCart_DV(DetailView): queryset = Model_CustomerCart.objects.all() html {% for cartitem_ in object.model_customercartitem_set.all %} {{ cartitem_.item_name }} {{ cartitem_.item_name.item_price }} <------ How can I get … -
Django- How to view Generic views of a child class
Basically what I am trying to do is view all the comments accompanied with a certain post This is my views.py from django.views import generic from .models import comment, article class IndexView(generic.ListView): template_name = 'newspaper/newspaper.html' context_object_name = 'articles' def get_queryset(self): return article.objects.order_by('-date') class ArticleDetailsView(generic.DetailView): template_name='newspaper/details.html' context_object_name = 'articles' def get_queryset(self): return article.objects.order_by('-date') class CommentsDetailsView(generic.DetailView): template_name='newspaper/details.html' context_object_name = 'comments' def get_queryset(self): return comment.objects.all() models.py from django.db import models from datetime import datetime class article(models.Model): title= models.CharField(max_length=150) body= models.TextField() date= models.DateField() author= models.CharField(max_length=150, default='') def __str__(self): return self.title + ' - ' + str(self.author) class comment(models.Model): main_article=models.ForeignKey('article',on_delete=models.CASCADE) text=models.TextField(default='Empty reply') date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.text urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)$',views.ArticleDetailsView.as_view(),name='articledetails'), url(r'^(?P<main_article_id>[0-9]+)$',views.CommentsDetailsView.as_view(),name='commentdetails'), ] and finally my html file {% extends "header.html" %} {% block title %} Article Details {% endblock %} {% block content %} {% if articles %} <div class="panel panel-primary"> <div class="panel-heading"> <h2>{{ articles.title}} </h2> </div> <div class="panel-body"> <h4>{{ articles.body}} </h4> </div> <div class="panel-footer"> <h5><i> Posted on: {{ articles.date}} </i> </h5> <h6 class="text-right"><i>By: {{articles.author}}</i></h6> </div> </div> <br> <button class="btn btn-primary" type="button" > Replies <span class="badge">{{ comments.count }}</span> </button> {% for y in comments %} <div class="well"> <h5>{{ y.text}} … -
Prevent reloading after submit button in django
i have code written completly in django using get/post method.Now after submitting the button it reloads the page.how can i stop reloading the page whenever we are submitting a form.Any leads will pls -
How can my Model primary key start with a specific number?
I have a User model, I want its id start from 10000, then its id should auto-increment like: 10001, 10002, 10003, 10004... My User class: class User(AbstractUser): username = models.CharField(max_length=64) ... Is it possible to make it come true? -
Django: trying to implement case insensitve username but not working
I wanted to have case insensitive username for my project. So i tried the following solution from https://simpleisbetterthancomplex.com/tutorial/2017/02/06/how-to-implement-case-insensitive-username.html from django.contrib.auth.models import AbstractUser, UserManager class CustomUserManager(UserManager): def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) class CustomUser(AbstractUser): objects = CustomUserManager() I have a signup form to create a user. I have created a username called "test". It was saved properly in the database. Then i tried to create another user name called "Test" I found that form.save() has saved "Test" also into database. But i wanted that is should show some error that username already exists. Then how is the solution which i am following is helping me. -
How can I put link into translation label in django
My issue is, how can I translate label, where is link, inside the label. I am trying but I get only translate for msgid not for msgid. site.html <label for="id_data_protection" class="checkbox"> {% blocktrans %}Lorem <a href="/en/policy" target="_blank">Lorem ipsum</a> lorem ipsum test test {% endblocktrans %} </label> django.po file #: templates/pages/templates/contact.html:72 msgid "" "Text <a href=\"/de/datenschutz\" target=\"_blank\">Text</a> " "TextTextTextTextText" msgstr "" "Text <a href=\"/en/policy\" target=\"_blank\">Text Text</a> Text " "TextTextText TextText" -
File upload security in Django-2.x
The documentation on secure file upload (https://docs.djangoproject.com/en/2.0/ref/models/fields/#file-upload-security) doesn't quite answer my concerns. Consider the following use case : a (potentially malicious) user can use a form to upload a file. I want to implement the following controls (returning an error message and not accepting the file if it doesn't comply) : the file must be less than 50MiB the file name must be of format ^[a-zA-Z0-9_ ]{1,250}.csv$ the filemust be ANSI encoded only a whitelist of ANSI characters inside the file will be allowed (for example [a-zA-Z1-9;]) securing metadata to prevent code injection through malicious metadata What would be the best way to implement this ? Also did I forget important controls for this use case ? -
Django MySql : foreign key queries
I'm starting Django since 2 weeks and i'm actually trying to get information from the 'Salaire' table with a selected 'matriculeemp' pk from 'Employe' table which is the foreignkey of 'Salaire', I haven't been able to find the answer by searching on the other stackoverflow post. I have this models : enter image description here The view with the query : Thanks for helping :)) -
Django routing using optional URL parameter
I am trying to implement a route in Django that captures all requests to /results/, such that the optional url parameters /results/1/ and /results/2/ are translated to specific result pages (as replacement to ?page={i}). However, this doesn't work as expected. When using the path /results/{i}, where i represents the page number, the routing works fine. However, when leaving the i out, such that the path is /results/, then an error is produced. The error that I get is: Page not found. What I want to do is to process /results/ as /results/1/, but without making different url patterns. Any suggestions? My setup: urls.py urlpatters = [ path('results/<int:page>/', SearchListView.as_view(), name='list'), ] views.py class SearchListView(ListView): model = Search paginate_by = 5 -
Conditional sign up for internal Django site
I'm using Django (with python-social-auth) to authenticate users for an internal student information system. We currently have an external SQL table, that keeps track of whether a user is: an admin, staff member, or student, based on their Google Apps email address. Current post_save function @receiver(post_save, sender=User) def create_student_or_staff(sender, instance, created, **kwargs): if created: try: state = UserState.objects.get( email=instance.email ) except UserState.DoesNotExist: # if exception is raised here, user is not created but site crashes # if no exception is raised, a user is created but no admin, staff or student instance pass if state.staff: if state.is_admin: Admin.objects.create( user=instance ) else: Staff.objects.create( user=instance ) else: class_instance = None if state.year and state.band and state.set: class_model = apps.get_model('class_groups.ClassGroup') class_instance = class_model.objects.get( year=state.year, band=state.band, set=state.set ) Student.objects.create( user=instance, class_group=class_instance ) When a user first attempts to login, I want to be able to check against that database to see if they meet any of the criteria. Currently, using the post_save signal for the user (I've also tried to use pre_save but no dice) to somehow halt the creation of a Django user object if they are not on the UserState table. Is this possible at all? The only way I can halt … -
Serialize model fields into nested object/dict
Imagine the following model: class Person(models.Model): name = models.CharField() address_streetname = models.CharField() address_housenumber = models.CharField() address_zip = models.CharField() I have a django rest framework ModelSerializer that exposes all the fields. But I would like to be able to serialize the address fields into a dict. So when serialized to json output would be: { name: 'Some name', address: { streetname: 'This is a test', housenumber: '23', zip: '1337', } } I tried creating creating a AddressSerializer class AddressSerializer(serializers.Serializer): streetname = serializers.CharField() housenumber = serializers.CharField() zip = serializers.CharField() and then set the PersonSerializer.address to use the AddressSerializer class PersonSerializer(serializers.ModelSerializer): ... address = AddressSerializer() This results in my schema being correct. I generate swagger docs by using drf-yasg. It looks at the serializers to generate the correct model definitions. So the serializers needs to represent the schema. So this is where I am at, at the moment. Obviously now it fails because there is no address property in the Person model. How would you go about solving this? -
Deploying multiple Python applications on the same Compute Engine server / Docker
I am a PHP developer(10 years) currently learning Python(2 months). I currently have a server on Compute Engine with about 10 domains hosted with 10 different websites/applications. Each application has requirements such as SSL, caching, database connectivity etc. I am building a few Python (Django and Flask) applications and I stuck on deploying them. When I run the Django application using python manage.py runserver 0.0.0.0:80 the terminal is occupied and I cannot launch another application on a different port. The same issue for Gunicorn. Each Python application will have a database connection, SSL, Cache etc. With my PHP application, I use Nginx to point to the folder, LetsEncrypt to add SSL to the site and I can deploy the applications on the same server using different folders for each application. I can also re-start the server from the Compute Engine admin(which I need to do) and once the server starts, all websites are available to the end users. I would like to understand how to do the same with Python. As these projects are not being paid for/bringing in revenue I cannot host them on their own servers due to cost. I use Docker containers for development on my computer … -
Why does React fetch retrieve blank object?
I have a working Django REST API which returns this: { "id": 1, "brand": "peugeot", "model": "3008", "variant": "allure" } I am using the following code to fetch the above data: render() { const { brand, model, variant } = this.props; let url = `http://127.0.0.1:8000/api/car/${brand}/${model}/${variant}/`; console.log(url) <== url is correct when checked in console fetch(url) .then(response => response.json()) .then(data => data.length === 0 ? this.setState({ data : data }) : null ) <== I have used a condition for setState to stop fetching infintely const { data } = this.state; console.log(data) <== This is a blank object with no data in console console.log(data.id) <== This is undefined in console return ( <div> {data.id} <== No data is shown on webpage Car Details </div> ); } No error is shown when I try to fetch the data on my webpage. What am I doing wrong? P.S. Data can be fetched from the same API server when I have an array of objects, and I use map to loop over the data. Over here I am trying to fetch a single item so there is no array, just an object. Am I doing something wrong with the syntax? -
Django tutorial part5 error
I'm learning Django programming I am playing with part5 I'll leave the address below https://docs.djangoproject.com/en/2.0/intro/tutorial05/ I added the contents of the test file but I did the test, but there was a problem with the test file I tried to find a typo but I can not find it What is the problem? this is Traceback Traceback (most recent call last): File "/home/choco/python3/django/mysite/polls/tests.py", line 96, in test_two_past_questions create_question(question_text="Past question 1.", days=-30) NameError: name 'create_question' is not defined ---------------------------------------------------------------------- Ran 8 tests in 0.103s FAILED (errors=5) Destroying test database for alias 'default'... This is tests.py import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_old_question(self): """ was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self): """ was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def test_was_published_recently_wiht_future_question(self): """ test_was_published_recently() returns False for questions whose pub_date is in the test_was_published_recently_wiht_future_question """ time = timezone.now() +datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def create_question(question_text, days): """ Create a question … -
ManytoMany related to django Rest
modes.py class Product(models.Model): product_name = models.CharField(max_length=32) quantity = models.IntegerField() remarks = models.TextField(blank=True) class Vendor(models.Model): vendor_name = models.CharField(max_length=50) address = models.CharField(max_length=100) bill_no = models.CharField(max_length=8) product = models.ManyToManyField(Product) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class VendorSerializer(serializers.ModelSerializer): product = ProductSerializer(many=True, read_only=False) class Meta: model = Vendor fields = '__all__' def create(self, validate_data): product_data = validate_data.pop('product') vendor = Vendor.objects.create(**validate_data) for product_data in product_data: Product.objects.create(vendor=vendor, **product_data) return Vendor views.py class VendorViewset(viewsets.ModelViewset): serializer_class = VendorSerializer queryset = Vendor.objects.all() How should I write product view such that It can be demonstrated that products of certain vendor can only be viewed with url routing? -
Why iframe to not exist file create empty file?
I need some help or advise. In the template of django application I have iframe widget where user select date and load xls file by url address which I set in js. If file with selected date is not exist I want to show message about it. For some reason in that case iframe create empty xls file. How to fix it? JS: var downloadSideBarFiles = { main_url: "https://example.com", file_types: { 2: "/shares/rpfile/", 1: "/shares/waprfile/" }, init: function() { var e = $(".regulations__download"); this.clickMethod(this, e) }, clickMethod: function(e, a) { a.find(".regulation__download-link").click(function(t) { t.preventDefault(); var r = a.find("input[type=radio]:checked"), o = a.find("input[type=text]"); 0 == r.length ? e.errorMethod("No file type selected") : 0 == o.val().length ? e.errorMethod("No date selected") : (type = e.file_types[r.val()], date = o.val().split("/").join("."), uri = e.main_url + type + date, e.downLoadMethod(e, uri)) }) }, errorMethod: function(e) { alert(e) }, downLoadMethod: function(e, a) { $.fileDownload(a).fail(function() { e.errorMethod("File is not exist") }) } }; views.py: def warpfile_date(request, date): if urllib.urlopen(filepath+ 'wapr' + str(date) + '.xls').code == 200: file = urllib.urlopen(filepath) response = HttpResponse(file, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=' + 'wapr' + '.xls' else: response = HttpResponse(status=404) return response -
dynamic range filter not working properly
for the following code when i am choosing the range between 1-5 the output contains the range between 6-10 also. please help qu=dict(request.GET) # result=Package.objects.all() for key,value in qu.items(): qu[key]={'attri':value} dict3={n:{**qu[n],**d[n]} for n in qu } print(dict3) result=Package.objects.all() print() print(result) print() for key, value in dict3.items(): vls = value['attri'] if value['op'] == 'range': vls = [ literal_eval(vl) for vl in vls ] # print(vls) # print() cond_name = 'attributes__{}__{}'.format(key, value['op']) conditions = reduce(or_, [Q(**{cond_name: vl}) for vl in vls], Q()) -
How to get the latest value of one filed(Django Model.objects.filter())
I have models as below: class ProjectRecord(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True,related_name='user_projects') project = models.ForeignKey(Project,on_delete=models.CASCADE, null=True, blank=True, related_name='user_projects') project_type = models.CharField(max_length=30, choices=(("project_a","A"),("project_b","B")),null=True) version = models.FloatField(null=True, blank=True) I want to filter the latest value of version with this: project = list(ProjectRecord.objects.filter(user=self.request.user, project_type='project_a')) , but I don't know how to achieve it.the data in database is similar as below: id project_id version project_type 1 5 1.0 project_a 2 5 2.0 project_a 3 5 3.0 project_a 4 5 3.0 project_b 5 4 1.0 project_a 6 4 1.0 project_b For example, I want to get the lates value of project_id=5 to exact match other data, the queryset should be display as below id project_id version project_type 1 5 3.0 project_a 2 5 3.0 project_b Thanks so much for any advice and assistance. -
PUT method makes Invalid password format or unknown hashing algorithm DRF
POST request for creating user is working fine, but when I preform PUT method on a user and change the password I'm getting Invalid password format or unknown hashing algorithm, so I'm a bit confused why is this happening, so can someone please help me overcome this. MyUserSerializer from rest_framework import serializers from business_accounts.models.my_user import MyUser class MyUserSerializer(serializers.ModelSerializer): """ TODO: MyUser model Serializers :return: TODO """ password = serializers.CharField(min_length=8, write_only=True) class Meta: model = MyUser fields = '__all__' def create(self, validated_data): user = super(MyUserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user User Detailed APIView from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from ..serializers.my_user_serializers import MyUserSerializer from business_accounts.models.my_user import MyUser class UserDetailView(APIView): """ User detail api view """ def get_object(self, pk): try: return MyUser.objects.get(pk=pk) except MyUser.DoesNotExist: raise Http404 def get(self, request, pk): user = self.get_object(pk) serializer = MyUserSerializer(user) return Response(serializer.data) def put(self, request, pk): user = self.get_object(pk) serializer = MyUserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): user = self.get_object(pk) user.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
Handle error : "CSRF verification failed. Request aborted"
In django 1.11, Handle error : "CSRF verification failed. Request aborted". If verification failed reload page.