Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any tool to automatically create template for model in django
I am new in django and I have some experience in Jsf within Netbeans. In netbeans, when we have entity classes, it can automatically create jsf page from entity classes for list, create and view. Is there any tool to automatically create template for model in django? -
django rest serializer: ordering fields appearance
Is it possible to specify in which order fields will appear in a serialised model? To make sure there is no confusion, while searching answers for this I have found lots of suggestions for ordering objects in a list view but this is not what I am looking for. I really mean for a given model, I'd like their fields, once serialized to appear in a specific order. I have a fairly complex serialized object containing a lot of nested serializers, which appear first. I'd prefer instead key identifying fields such as name and slug to show up first, for readability. Apologies in advance if this question is a duplicate, but I didn't find any relevant responses. -
django form is not working properly. getting error at form.is_valid()
I am getting error "init() got an unexpected keyword argument 'sub_category'" in form.py on line super(LeadForm, self).init(*args, **kwargs) and in views.py on line form.is_valid(). Please help. I am sharing github link for the project, just look into 'leads' app. check on create_lead function in views.py and Leadform in forms.py and Lead model in models.py https://github.com/admill1519/django-crm -
How to log in and check, if user is staff, can access to url or use a views class?
At my question, my problem is How to log in and check, if user is staff, can access to url or use a views class ? I want to user login on website (Not admin-console) and user is staff (in admin-console) can post. And someone just have a account create on web (they dont have permission staff) thay just can login. Thank you so much ! class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Show all languages in form using django-translations
I am using django-translations for translating some fields of my model. Using the Django Admin I can enter the translations and the form in the frontend shows the matching language values. But I want to show one field for each language "similar" to the Django Admin, except I don't want to manually add the fields for non translated languages. So if I have the languages en (default) and de I want to output title or title_en and title_de as fields. I tried to add the translation fields myself e.g. title_de to the model, layout and meta class, but it didn't work. How can I show all the fields for different languages simultaneously? Model class Category(Translatable, MPTTModel): title = models.CharField(max_length=200) slug = models.SlugField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Meta: # enforcing that there can not be two categories under a parent with same slug unique_together = ('slug', 'parent',) class MPTTMeta: order_insertion_by = ['title'] class TranslatableMeta: fields = ['title', 'slug'] Form class CategoryForm(forms.ModelForm): use_required_attribute = False title = forms.CharField(max_length=200) slug = forms.SlugField(help_text=_('Will be generated automatically from the title')) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.form_class = 'form-horizontal form-bordered' self.helper.label_class = 'col-lg-3' self.helper.field_class … -
Unable to paginate django-tables2-column-shifter
I have a table will 1000+ user records, I am unable to paginate it or add filters to it. tables.py from django_tables2_column_shifter.tables import ColumnShiftTable from .models import UserAdminTB import django_tables2 as tables class AdminData(ColumnShiftTable,tables.Table): def get_column_default_show(self): self.column_default_show = ['associate_nbr', 'first_name','last_name','last_hire_date','function','client','lob'] return super(AdminData, self).get_column_default_show() class Meta: model = UserAdminTB views.py class AdminView(SingleTableView): template_name = 'admin.html' def get(self,request,*args,**kwargs): queryset = UserDetails.objects.all() table = AdminData(queryset) return render(request,self.template_name, {'table': table}) -
Convert text file to tiff file in python
I am converting text file to tiff by using the following code but it is not working when text file content starts with special characters. I don't know why it is not working. Could you please anyone help me to do this task def main(): image = text_image('/Users/administrator/Desktop/367062657_1.text') image.show() image.save('contentok.tiff') def text_image(text_path, font_path=None): grayscale = 'L' # parse the file into lines with open(text_path) as text_file: lines = tuple(l.rstrip() for l in text_file.readlines()) large_font = 20 font_path = font_path or 'cour.ttf' try: font = PIL.ImageFont.truetype(font_path, size=large_font) except IOError: font = PIL.ImageFont.load_default() print('Could not use chosen font. Using default.') pt2px = lambda pt: int(round(pt * 96.0 / 72)) max_width_line = max(lines, key=lambda s: font.getsize(s)[0]) test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' max_height = pt2px(font.getsize(test_string)[1]) max_width = pt2px(font.getsize(max_width_line)[0]) height = max_height * len(lines) # perfect or a little oversized width = int(round(max_width + 5)) # a little oversized image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF) draw = PIL.ImageDraw.Draw(image) vertical_position = 5 horizontal_position = 5 line_spacing = int(round(max_height * 1.0)) for line in lines: draw.text((horizontal_position, vertical_position), line, fill=PIXEL_ON, font=font) vertical_position += line_spacing c_box = PIL.ImageOps.invert(image).getbbox() image = image.crop(c_box)`enter code here` return image -
How to ignore a specific migration?
I have a migration like this: class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20191023_2245'), ] operations = [ migrations.AddField( model_name='agenda', name='theme', field=models.PositiveIntegerField(default=1), ), ] But it raises an error: django.db.utils.ProgrammingError: column "theme" of relation "app_agenda" already exists Not a problem, I've wrapped this error like this: from django.db import migrations, models, ProgrammingError def add_field_theme_to_agenda(apps, schema_editor): try: migrations.AddField( model_name='agenda', name='theme', field=models.PositiveIntegerField(default=1), ), except ProgrammingError as e: # sometimes it can exist if "already exists" not in str(e): raise class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20191023_2245'), ] operations = [ migrations.RunPython(add_field_theme_to_agenda), ] This works like a charm and all the following migrations are done. My problem is that each time I run a "makemigrations" Django adds again the migration (= the one on the top of my question). I guess it's because it doesn't see it in the migrations, because my code obfuscate it. How to circumvent this using migrations (dont say answers like "this problem is on your database, correct your database")? -
How to fix Django admin encoding error when I update the user?
When I update user data through the admin panel I get the following error: IntegrityError at /admin/registration/testuser/11/change/ ������������: INSERT ������ UPDATE �� �������������� "django_admin_log" ���������������� ���������������������� ���������������� ���������� "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: �������� (user_id)=(11) ���������������������� �� �������������� "auth_user". How I can fix this? P.S. I saw an old similar question, but the custom backend from there, knocked me all the authorization. -
How to start task at 0815 and run it every 15 minutes in django
I am trying to schedule a celery task on django, which would start at 0815 in the morning and run every 15 minutes. @periodic_task(run_every=crontab(minute='*/15', hour='8-23',), queue='xenia_celery_priority_queue_1', options={'queue': 'xenia_celery_periodic_queue_1'}) As I understand, I would need to set minutes=15, so the task starts at 0815, bu I am using minutes, to run the task every 15 minutes already. Is there a simple way to start the task at 0815 and run it every 15 minutes? -
Conditional Statement If-else in Jinja2
I'm building my first application in Django and I am having trouble with the conditional loop. I want to create a form where users would input their name, family size and income and it would calculate where they land on the sliding scale (A, B, C or Overqualify) based on their income. I'm expecting it to output one scale (A,B,C, or Overqualify) but it keeps looping - so what I am getting is: What I am getting If anyone can help me or point me to any resources because I just started learning python and django so I'm quite stuck. Thank you! models.py from django.db import models # Create your models here. class SlidingScale(models.Model): scale = models.CharField(max_length=1) family_size = models.IntegerField() min_annual = models.IntegerField(default = 0) max_annual = models.IntegerField() def __str__(self): return self.scale forms.py from django import forms class SlidingForm(forms.Form): name = forms.CharField(max_length = 100) household = forms.IntegerField() income = forms.IntegerField() views.py from django.shortcuts import render from django.template.response import TemplateResponse from .models import SlidingScale from .forms import SlidingForm # Create your views here. def index(request): return render(request, 'index.html', {}) def calculator(request): if request.method == "POST": #Get the posted form form = SlidingForm(request.POST) data = SlidingScale.objects.all() if form.is_valid(): name = form.cleaned_data['name'] household … -
How to use Outer for loop value in inner for loop in Django template
I'm doing Django Project. Here I am trying to use Outer for loop data in inner for loop in Django Template. Help me in that i did mistake in inner for loop i don't know how to solve this. views.py def test_view(request): if 'username' in request.session: if request.method == 'GET': offers_objs = offers.objects.all().values() data = Signup.objects.all().values() return render(request, 'index.html',{'offers_objs':offers_objs, 'data': data}) index.html {% for i in offers_objs %} <div class="divi" style="height: 410px"> <img src="{{ i.image.url }}" alt="Images" width="300px" height="auto"/> <p>Offer Des: {{ i.description }}</p> <p>Address: {{ i.address }}</p> <p>Offer id: {{ i.offer_id }}</p> </div> {% for {{ i.username }} in data %} <p>{{ name }}</p> {% endfor %} {% endfor %} -
Reverse relation of foreign keys in django
I have two tables connected via foreign keys. Models.py class Foo(models.Model): A = models.DateField(default=datetime.now) B = models.IntegerField(default=0) C = models.IntegerField(default=0) class Bar(models.Model): X = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='foo_a') Y = models.CharField(default=0) Z = models.CharField(default=0) Views.py def foo_details(request): query = Foo.objects.all() return render(request, 'foodetails.html', {'query': inward}) HTML <thead> <tr> <th>A</th> <th>B</th> <th>C</th> <th>Y</th> <th>Z</th> </tr> </thead> <tbody> {% for i in query %} <tr> <td class="align-middle">{{ i.A }}</td> <td class="align-middle">{{ i.B }}</td> <td class="align-middle">{{ i.C }}</td> <td class="align-middle">{{ i.?? }}</td> <td class="align-middle">{{ i.?? }}</td> </tr> How can I show the related field of Bar model in my template? If the query in my views was Bar.objects.all() then in my templates I could easily do <td class="align-middle">{{ i.X.A }}</td> But how can I use the reverse relation? -
I am always getting none from request.POST.get in django
html -customer_view //nam and mob field are userinput fields which i am using for user input and later i am using them for filtering ----- {% block content %} {% csrf_token %} {{ customer.sponsor }} {% for i in sponsor %} {{ i.mobile|add:' - '|add:i.name }} {% endfor %} Please select a valid Existing Customer. Search Urls.py ---- path('customer_view',views.customer_view,name='customer_view') Views.py ---------- def customer_view(request): print(request.method ) name1 = str(request.POST.get('nam')) print(name1) mobile1 = str(request.POST.get('mob')) print(mobile1) customers_list = customer.objects.filter( mobile=mobile1) & customer.objects.filter(name=name1) sponsors = customer.objects.all().distinct('mobile') ctx = { 'customer': customers_list, 'sponsor': sponsors } return render(request, 'pages/customer_view.html', ctx) -
Is it rational to cache result of a filter query?
I want to arrange architecture for my new project. Beside caching result of intensive calculations, I have coded a new model that has caching mechanism as below and when I want to have caching on a model in new model I inherit this model. Is it a rational way to cache result of filter queries or not? Thanks in advance. class CacheQuerySet(models.QuerySet): def get(self, *args, **kwargs): if "pk" in kwargs and len(kwargs) == 1: key = "{cache_key}_PK_{pk}".format(cache_key=self.model.cache_key(), pk=kwargs["pk"]) cached_obj = cache.get(key) if cached_obj is None: db_obj = super(CacheQuerySet, self).get(*args, **kwargs) cache.set(key, db_obj, self.model.CACHE_TIMEOUT) return db_obj return cached_obj return super(CacheQuerySet, self).get(*args, **kwargs) def update(self, **kwargs): super(CacheQuerySet, self).update(**kwargs) keys = cache.keys("%s_*" % self.model.cache_key()) cache.delete_many(keys) def cached_data(self, *args, **kwargs): query_hash = md5(str(self.query).encode()).hexdigest() key = "%s_FILTER_%s" % (self.model.cache_key(), query_hash) cached_objects = cache.get(key) if cached_objects is None: db_objects = list(self.all()) cache.set(key, db_objects, self.model.CACHE_TIMEOUT) return db_objects return cached_objects class CachedModel(models.Model): CACHE_TIMEOUT = 10 * 60 @classmethod def cache_key(cls): return cls.__name__.upper() @property def my_key(self): return "{cache_key}_PK_{pk}".format(cache_key=self.cache_key(), pk=self.pk) objects = CacheQuerySet().as_manager() def save(self, *args, **kwargs): super(CachedModel, self).save(*args, **kwargs) filter_keys = cache.keys("%s_FILTER_*" % self.cache_key()) cache.delete_many(filter_keys) cache.set(self.my_key, self, self.CACHE_TIMEOUT) def delete(self): cache.delete(self.my_key) filter_keys = cache.keys("%s_FILTER_*" % self.cache_key()) cache.delete_many(filter_keys) super(CachedModel, self).delete() class Meta: abstract = True -
google login with Django rest api (android and ios)
I am writing backend for Google Login for both android and ios. For android we can use web application client id and client secret but for ios google only provides client id and no secret key. So I am not able to perform google login from ios. Since ios and android require two different client credentials, how can i include two client ids in one single project (one for android and one for ios)? This is the Back End code i have used: serializers.py `class SocialSerializer(serializers.Serializer): """ Serializer which accepts an OAuth2 access token and provider. """ provider = serializers.CharField(max_length=255, required=True) access_token = serializers.CharField(max_length=4096, required=True, trim_whitespace=True) views.py class SocialLoginView(generics.GenericAPIView): """ Log in using facebook or Google """ serializer_class = serializers.SocialSerializer permission_classes = [permissions.AllowAny] def get_tokens_for_user(self, user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } def post(self, request): """Authenticate user through the provider and access_token""" serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) provider = serializer.data.get('provider', None) strategy = load_strategy(request) try: backend = load_backend(strategy=strategy, name=provider, redirect_uri=None) except MissingBackend: return Response({'error': 'Please provide a valid provider'}, status=status.HTTP_400_BAD_REQUEST) try: if isinstance(backend, BaseOAuth2): access_token = serializer.data.get('access_token') user = backend.do_auth(access_token) except: return Response({ "error": "Invalid Credentials", }, status=status.HTTP_400_BAD_REQUEST) try: authenticated_user = backend.do_auth(access_token, user=user) except: return Response({ "error": … -
How request works in Flask if not parameterized in view
I have just started with Flask I know django. We take a request parameter in a simple django view from django.http import HttpResponse def view(request): #request is the local paramter for view return HttpResponse('Welcome to Django') Now this view is request aware because of parameter passed. But now in Flask from flask import Flask, request app = Flask(__name__) @app.route('/', methods=['GET','POST']) def view(): if request.method == 'GET': return "Hello from Flask" request is not local to function view how it is aware of the request it should be like request is not defined. Where it is coming from? How it works here? -
Many small requests vs few large requests - Angular to Django REST API - No DB involved
I know there are related questions on SO, but I am not sure if the conditions I am asked to work on causes any changes to the answer, so I am asking it here. I am creating a simple webapp in Angular that imports spreadsheet data from the user and sends the data to Django backend that does data analysis on it. The data results are returned to frontend and Angular creates a dashboard of the results. There is a chart displayed for every column of the spreadsheet. I am faced with two options: a) Keeping the spreadsheet in the browser memory and sending each column of data separately to the Django server that makes analysis of the data and returns the results. Pros: Simple architecture. No caching required. Cons: If there are 150 columns in the sheet, it will result in 150 calls to the API for that user. b) Sending the entire sheet of data and let python handle everything. It will return a big chunk of data in return which will have to be unpacked by Angular. Pros: Only one request per file. Cons: For subsequent calls for the same file, I might need caching? If the … -
OSError: [WinError 123] (file name error) but project previously worked
I have written an authentification application with Django and it used to work now, when I try to use it in another project, I have an error: OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect '' error seems to deal with a pathlib.py file I did not change: File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\pathlib.py", line 1168, in stat return self._accessor.stat(self) I try to go back with my original code that was working by cloning my project on gitlab but I have the same error what happen? -
Converting curl command to request.post
I have following curl command: curl.exe -u sys_dcmsys:sys_******1 -d "grant_type=client_credentials&scope=Token_WindowsAuth" -H "Content-type: application/x-www-form-urlencoded" https://abcd-i.company.com/token -k -i And i am trying to do the same over python using requests: payload = { 'grant_type': 'client_credentials', 'scope': 'Token_WindowsAuth' } header = {'Content-Type': 'application/x-www-form-urlencoded'} result = requests.post( https://abcd-i.company.com/token, auth=HTTPBasicAuth('sys_dcmsys', 'sys_******1'), data=payload, headers=header, verify=False) i am able to get the result from command line. but when i tried with request.post its failing. it says : File "/home/vcap/deps/1/python/lib/python3.5/json/decoder.py", line 357, in raw_decode [APP/PROC/WEB/0] ERR raise JSONDecodeError("Expecting value", s, err.value) from None 2019-10-23T11:48:28.60+0530 [APP/PROC/WEB/0] ERR json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) can any one suggest me why my python post request is failing -
Django user rights management through the admin panel
I have a user to whom I have added permissions. How to do this through the admin panel so that with one click I can assign the permissions I need (one at a time or all at once)? class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) class Meta: db_table = '"fyzzys"."users"' permissions = ( ("payments", "can_see_payments"), ("analytics", "can_see_analytics"), ) -
In Tabbing page how to come back to same tab if i have gone in children of each tab
In my Django page, I have two tabs.Tab1 and Tab2 right. And Each Tab has a number of children. If I navigate to Tab1's children, the Same as if I navigate to Tab2's children. If I came back to the parent(Tab1 or Tab2) it will always go to Tab1. If I navigate through Tab1 than it will come back to Tab1 and if I navigate through Tab2 than it will come back to Tab2. How to do this in Django? -
Django (or something else) for utilising stored procedures
I need a web framework that can handle SQL Server store procedures as a main way of recieving and sending data. This data wold also need to be editable and sent be able to be sent back with stored procedures. (This is unavoidable). I was thinking of using Django as it can be run on Linux and I enjoy developing with that platform, but resources on how to utilise stored procedures in Django are scarce. I'd love some suggestions! -
Error encountered checking Geometry returned from GEOS C function "GEOSGeom_createLinearRing_r"
Trying to generate a polygon field for my region and cities for geotagging. Idea is to save the coordinates separately from Gmaps. Then use them to generate a region polygon. For regions like NCR in India, you have multiple cities like Delhi, Noida. Gurgaon etc. So these cities form the subset of the polygon. So you create a polygon and save with every city, then make a multipolygon to save at a regional level. Encountered this error. Please help from Geography.models import Region,City from django.contrib.gis.geos import Polygon,MultiPolygon coordinates={ 'JAL':{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "Name": "jalandhar", "Description": "" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 75.510571, 31.384717, 0.0 ], [ 75.515237, 31.270770, 0.0 ], [ 75.683574,31.264225, 0.0 ], [ 75.672656,31.390200, 0.0 ] ] ] } } ] } } def add_polygons(): r = Region.objects.last() city_coordinates = coordinates[r.name]['features'] polygon=None for cx in city_coordinates: coo_list_ = cx['geometry']['coordinates'][0] coo_list =[[item[0],item[1]] for item in coo_list_] name = cx['properties']['Name'] city=City.objects.filter(name__iexact=name).first() p = Polygon(coo_list) if city: city.poly=p city.save() if polygon: polygon=polygon.union(p) else: polygon=MultiPolygon(p) r.poly=Polygon(polygon.shell) r.save() add_polygons() This is the error I get. Something about create linear ring function. I tried to go through the library itself but to no avail. … -
mutiValueDictKeyError in django
I am a novice in django app development. I was trying to develop a simple app where it adds two numbers. I am getting MulitValuedDictKeyError. I referred to few questions of same type previously asked and tried some solutions, but none worked.Kindly help me fix it. views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request,'home.html',{'name':'pavan sunder'}) def add(request): val1 = request.GET["num1"] val2 = request.GET["num2"] res = val1 + val2 return render(request, 'result.html',{'result':res}) home.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} <h1>hello {{name}}</h1> <form action="add"> Enter 1st number:<input type="text",name="num1"><br> Enter 2nd number:<input type="text",name="num2"><br> <input type="Submit"> </form> {% endblock %} </body> </html> result.html <!DOCTYPE html> <html lang="en"> <body> {% extends 'base.html' %} {% block content %} Result:{{result}} {% endblock %} </body> </html> error msg: MultiValueDictKeyError at /add 'num1' Request Method: GET Request URL: http://127.0.0.1:8000/add Django Version: 2.2.6 Exception Type: MultiValueDictKeyError Exception Value: 'num1' Exception Location: C:\Users\PAVANM~1\django\lib\site-packages\django\utils\datastructures.py in __getitem__, line 80 Python Executable: C:\Users\PAVANM~1\django\Scripts\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\pavan m sunder\\projects\\django\\tst', 'C:\\Users\\PAVANM~1\\django\\Scripts\\python37.zip', 'C:\\Users\\PAVANM~1\\django\\DLLs', 'C:\\Users\\PAVANM~1\\django\\lib', 'C:\\Users\\PAVANM~1\\django\\Scripts', 'c:\\users\\pavan m ' 'sunder\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\pavan m ' 'sunder\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\PAVANM~1\\django', 'C:\\Users\\PAVANM~1\\django\\lib\\site-packages'] Server time: Wed, 23 Oct 2019 05:32:02 +0000