Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set initialisation value on abstract Django mixin from concrete class
I have an abstract mixin class that adds a Django model field to any concrete class that inherits from it. At class initialisation - when makemigrations is run - I'd like the inheriting class to define whether an inherited field is required or optional via the blank= True or False property. I've tried various Meta and __new__ approaches, but can't figure out how the abstract mixin class can get the information from the inheriting class. Here's a naive attempt: from django.db import models class DescriptionMixin(models.Model): class Meta: abstract = True description = models.TetxField( # how to get value here? blank=inheriting_class.description_required ) class OptionalDescription(DescriptionMixin, SomeOtherClass): class Meta: verbose_name = 'Optional description' description_required = False class RequiredDescription(DescriptionMixin, SomeOtherClass): class Meta: verbose_name = 'Required description' description_required = True Thanks in advance for any help offered. -
Doing math with django forms and avoiding redirect
I would like to have a form in Django do some math and spit out a result that does not end up with a redirect and gives me the result on the same page (i.e without refreshing). For example: views.py: def collisionrisk(request): assert isinstance(request, HttpRequest) form_class = CRMForm result = '' if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): D = form.cleaned_data['D'] B = form.cleaned_data['B'] b = form.cleaned_data['b'] result = D*B+b return HttpResponse('') else: return render( request, 'Collision_risk.html', { 'form':form_class, 'result':result } ) forms.py: class CRMForm(forms.Form): D = forms.DecimalField(required=True) B = forms.IntegerField(required=True) b = forms.IntegerField(required=True) def __init__(self, *args, **kwargs): super(CRMForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.fields['b'].label = 'b' self.helper.layout = Layout( Div( Div('D',css_class='col-lg-offset-2 col-md-offset-2 col-lg-1 col-md-1 col-sm-12 col-xs-12'), Div('B',css_class='col-lg-1 col-md-1 col-sm-12 col-xs-12'), Div('b',css_class='col-lg-1 col-md-1 col-sm-12 col-xs-12'), css_class='row', css_style='padding-left:50px;padding-right:50px;' ) ) self.helper.add_input(Submit('submit', 'Submit', css_class='btn-primary outline',action=".")) self.helper.form_method = 'POST' Basically, in my template, I would like the user to hit "submit" and then the result of the math appear in a designated div on the same page (i.e. directly under the button without redirecting to a new page) . I can do this in Jquery easy enough, but I am interested in learning if there is a pure Django way to … -
using cycle to add padding Django
I am trying to add some padding in between my posts. currently I have the 3 column layout working nicely however when ever I try to add some padding in between the columns nothing seems to happen. index.html <h1>Recent Posts</h1> {% for entry in entries %} <div class="row__3"> <h2 class="row--gutters">{{ entry.topic }}</h2> <p class="row--gutters">{{ entry }}</p> </div> {% empty %} <li> empty </li> {% endfor %} _row.css .row { @mixin clearfix; &__3 { float: left; width: 33.33%; } &--gutters > div { padding-left: 20px; } } I've tried to use the cycle for this but it messes up my 3 column layout. can't seem to figure it out. -
Django Rest Framework and Angularjs authentification
I have a problem with Authentification throw Django REST API. The front end is seperated from the backend. the front end runs on a server port 8008 and backend on Django 8000. The problem is I added CORS settings in the setting.py and My issue is The api works fine except if I want to access data that requires authentification. This is the authentification Class View: class LoginView(APIView): permission_classes = (AllowAny,) def get(self, request, format=None): print('executed scc!!!') content = { 'status': 'request was permitted' } return Response(content) def post(self, request): print('Loging in !!!') serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] django_login(request, user) print(request.user) token, created = Token.objects.get_or_create(user=user) return Response({"token": token.key}, status=200) I think the Class view is correct. And it works fine after sending user credentials throw post request. My issue is I have another Class view that requires the user to be authenticated. so when I use postman it works fine I access request.user and it returns the logged in user. But with code I get argument must be a string, a bytes-like object or a number, not 'AnonymousUser'. Do I need to add headers to my HTTP requests ? because I've noticed postman uses cookies -
How to use characters like . in username slug in Django 2.1?
I am creating a simple web app. The user suppose to signup and can see their profile. The signup form is working fine and the user can signup perfectly. In the forms.py I have function to raise validation error when the user signup with an existing username. Here is the problem. If there is an username types for example - 'userone' , and another user types 'user.one' it saves the new user with 'user.one'. But when the user wants to go to their profile, the problem arises in the url. Because I am using username as slug, the dot(.) is not present in the url which leads to the problem. I have tried with re_path as mentioned in the django document, but still getting errors. forms.py to check unique username def clean_username(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if username and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError('This username already exists') return username views.py (signup class) class SignupView(View): form_class = SignupForm template_name = 'webapp/user_signup.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: … -
How to access to get URL address by name in Django at model file (like {{ url 'urlname' }} at template)
Need to access url by name at model, can't just hardcode it. Need it for error message for a new object creating. Any suggestions? -
Django - TypeError - save() got an unexpected keyword argument 'force_insert'
Im new in Django and I can't figure out this error. Help please. It gave TypeError - save() got an unexpected keyword argument 'force_insert'. I tested the code below and they were able to save the new user registration but now it won't save anymore... Here is part of the views.py that i think got some problem: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from . forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save(force_insert=False) messages.success(request, f'Thank you {username}! Your account has been created!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) and the models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return (self.user) def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.image.path)' -
Django and AWS elasticbeanstalk; EB CLI doesn't require to input any credentials
I didn't use elasticbeanstalk in a while and the documentation changed since the last time I used. I'm trying to deploy my app into AWS eb. And I was following the tutorial on official site. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html But EB CLI doesn't require me to input any credentials. So even though I can see the environment details on my EB CLI, I cannot see it on my AWS console. And my site link doesn't work. How can I configure the app for my AWS console? I thought in previous way, when I did eb init EB CLI requires me to input credentials but this time it requires to choose just the region. -
Django - Name Error when views call model's method
I am a newbie in Django. I have defined the models and a method from django.db import models from django.contrib.auth.models import User class Practice(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=200) phone = models.IntegerField() def __str__(self): return self.name class Doctor(models.Model): specialisation = models.CharField(max_length=50) practice = models.ForeignKey(Practice, related_name='doctor',on_delete=models.DO_NOTHING) name = models.ForeignKey(User, related_name ='doctor', on_delete=models.DO_NOTHING) selected = models.BooleanField() def __str__(self): return self.specialisation def get_list_doctors(self): all_doctors = User.objects.exclude(pk=1).filter(doctor__isnull=False) all_doctors_names = all_doctors.values_list('last_name', 'first_name') return all_doctors_names class Patient(models.Model): name = models.ForeignKey(User, related_name='patient', on_delete=models.DO_NOTHING) height = models.DecimalField(max_digits=6, decimal_places=2) weight = models.DecimalField(max_digits=6, decimal_places=2) practice = models.ForeignKey(Practice, related_name='patient',on_delete=models.DO_NOTHING) primary_doctor = models.ForeignKey(Doctor, related_name='patient',on_delete=models.DO_NOTHING) class Appointment(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() doctor = models.ForeignKey(Doctor, related_name='appointment',on_delete=models.DO_NOTHING) practice = models.ForeignKey(Practice, related_name='appointment',on_delete=models.DO_NOTHING) patient = models.ForeignKey(Patient, related_name='appointment',on_delete=models.DO_NOTHING) This is my view def login_user(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ('You Have Been Logged In!')) doctor_list = get_list_doctors() context = { 'doctor_name': doctor_list} return render(request, 'homeunimed.html', context) I am trying to use the method in the view. The reason for defining it in the model is so that I can reuse. NameError at / name 'get_list_doctors' is not defined Request Method: POST Request URL: http://localhost:8000/ Django Version: 2.1 … -
Showing entries associated with topic Django
I am trying to display the most up to date posts on the homepage. I can query the most recents topics and display them on the homepage however I am having trouble querying the entries associated with that topic. my plan is to display the first 50 or so words of the entries. Models.py class Topic(models.Model): """A topic that is associated with a certain Category""" category = models.ForeignKey(Category, on_delete=models.CASCADE) text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Topics' def __str__(self): """Return string represtation of the model.""" return self.text class Entry(models.Model): """A entry associated with a certain topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Entries' def __str__(self): """Return string represtation of the model.""" return self.text[:50] + "..." views.py index view: def index(request): """The home page for the blogging website""" topics = Topic.objects.order_by('-date_added')[:3] entries = Entry.objects.filter(id__in=topics) context = {'topics': topics, 'entries': entries} return render(request, 'blogging_logs/index.html', context) index.html {% for entry in entries %} <li> {{ entry }} </li> {% empty %} <li> empty </li> {% endfor %} {% for topic in topics %} <li> {{ topic }} </li> {% empty %} <li> empty </li> {% endfor %} Thanks for the help in … -
The best way to do multiple save() in one submit in Django
I am a newbie in Django, and actually web developing. Have been searching for a while, but haven't got the answer yet. In my project, when user submits a form request, it will search some websites and if the specific images are found, it will download the images and return the link for download. Currently I have two Models: Request It stores the information like, time, username, image name, search status (fount or not), image ID (foreign key to Model "Image") Image It stores the information like image hash(pk), image size, image source, image category, etc. Just wanted to know what is the best way to save() to the models when a request is submitted. The approaches I am thinking of are: Option A: When a request is received, save() to Request model with basic information - except "Image ID" (it is not available yet), and set status to "started" Do the searches, and download the images, and then save() to the Image model - now I have the "Image ID" Update the Request instance with the "Image ID" information, and update the status to "success" Option B: Search and download the images immediately when the request is received, and … -
Django Rest Framework: How to pass data to a nested Serializer and create an object only after custom validation
I have two models as: class Book(AppModel): title = models.CharField(max_length=255) class Link(AppModel): link = models.CharField(max_length=255) class Page(AppModel): book= models.ForeignKey("Book",related_name="pages",on_delete=models.CASCADE) link = models.ForeignKey("Link", related_name="pages", on_delete=models.CASCADE) page_no = models.IntegerField() text = models.TextField() and serializers class LinkSerializer(serializers.ModelSerializer): class Meta: model = Link fields = ['link'] class PageSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('link','text','page_no') def validate_text(self, value): #some validation is done here. def validate_link(self, value): #some validation is done here. class BookSerializer(serializers.ModelSerializer): pages = PageSerializer(many=True) class Meta: model = Book fields = ('title','pages') @transaction.atomic def create(self, validated_data): pages_data= validated_data.pop('pages') book = self.Meta.model.objects.create(**validated_data) for page_data in pages_data: Page.objects.create(book=book, **page_data) return book There is a validate_text method in PageSerializer. The create method will never call the PageSerializer and the page_data is never validated. So I tried another approach as: @transaction.atomic def create(self, validated_data): pages_data = validated_data.pop('pages') book= self.Meta.model.objects.create(**validated_data) for page_data in pages_data: page = Page(book=book) page_serializer = PageSerializer(page, data = page_data) if page_serializer.is_valid(): page_serializer.save() else: raise serializers.ValidationError(page_serializer.errors) return book Posted data: { "title": "Book Title", "pages": [{ "link":1, "text":"sometext","page_no":52}] } But the above approach throws error: { "link": [ "Incorrect type. Expected pk value, received Link." ] } -
api design concept using django rest framework
My question or say my confusion is Does api design depends on how we present in UI? I will illustrate my confusion with one of an example. Will the api design be different if i want the form to be in multiple step? I mean in the https://www.franchisebazar.com/franchisor-registration if you see the form for company registration, there are section like company information, company brand and business model which are associated with company model. The submit button is only one that means there will be only one api for posting the company data. But what if I want the UI be different(multiple steps wizard form instead of one single big form) like company info in the first step and after submitting company personal info, the next step will be brand and then business model at last. For this do i need to design an api separately? One for company personal info, one for brand and one for business model. up to now my design is following https://gist.github.com/MilanRgm/132eb6c0ba0cf66e48fa0ca4c17ef732 I will brief it in the list again 1) API design for registering company profile using one single big form 2) API design for registering company profile using multiple step way I am confused … -
Python Module 'Requests' and 'Messages Framework'
within a Django web app, I am using the aforementioned modules: Requests to handle HTTP and Messages Framework to collect and render messages Now, when I am calling the following method of the Messages Framework: messages.add_message(request, messages.INFO, 'Hello world.') it gives me an error saying it requires an HTTPRequest... however, 'Requests' does not match. Any ideas? The full error message is: add_message() argument must be an HttpRequest object, not 'module'. The preceding method call for a post is: import requests <some code...> response = requests.post(url=dest, data=self.settings, headers=headers) -
how to resolve pagination for queries, and result to "None", on Django?
I've been trying to solve this for hours, I already looked in the doc, in stackoverflow, but no way it worked so far. I have two problems. I need to put in the title "no results found" if no results are found, or if the person enters the search url directly, without providing anything to search. I need to create a paging link, but it does contain the result of the query. I've already tried href = href="search?q={{ query }}?page={{page.next_page_number}}" But the query passed by the view does not appear on the link, which results in "search? Page = 2". As for the first problem, I have tried <h1 class="title is-5"> {% if posts.paginator.count > 0 %} {{ posts.paginator.count }} Resultado{{ posts.paginator.count|pluralize }} para "{{ query|truncatechars:30 }}" {% else %} Nenhum resultado encontrado {% endif %} </h1> Remembering that I am a beginner and I do not know how to speak English, I am trying to become an online translator and google. -
Get column values from MongoDB table to Django
How should I create a model.py when I already have an existing mongoDB database. I only want to get the values from an existing Table to a the HttpResponse in Django views.py. Is there any reference material for me to go over this? -
Django - create dictionary of associated objects
I'm attempting to build a query which will return a list of all technologies and the users score associated with each. This is based on the following models: class technology(models.Model): technology = models.CharField(max_length=64) class result(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) technology = models.ForeignKey(technology, on_delete=models.CASCADE) skill_level = models.ForeignKey(skill, to_field='level', on_delete=models.CASCADE) class skill(models.Model): level = models.IntegerField(unique=True) Essentially I'd like to see somthing similar to the following: {technology: Cisco, users: {Alex: {skill_level: 1}}, {James: {skill_level: 2}} I'm not sure whether this can be acheived with a simple query or whether custom joins will need to be done? I'm also not sure whether I should be building this on the technology model or the result model? -
How to debug Django on docker while using eclipse on windows.
My objective is to debug my django application in my window's eclipse while it is running on docker (no sure if it is doable). My test here is to see if the code is on nt (windows) or not by: import os print ("your OS is: "+os.name) For this test I don't want to see "nt" (windows) but rather the docker container OS (ubuntu). What confuses me here is how does docker's container associate the code I have to the container? In other words, if I make a change in the code on eclipse, how does the container "web" knows about it? I realized that the volume is where I should define the path but didn't quite understood how to do it properly. What I did is this (and I'm a docker newbie): Under my directory of eclipse where my djangoPrj is located I have the docker-compose file such that: version: '2' volumes: postgis-data: services: web: build: context: . dockerfile: Dockerfile.debug ports: - "8000:8000" volumes: - .:/djangoPrj links: - db db: image: kartoza/postgis:10.0-2.4 volumes: - 'postgis-data:/var/lib/postgresql' environment: - POSTGRES_DB=tankers_db - POSTGRES_USER=userABC - POSTGRES_PASS=passwordABC - ALLOW_IP_RANGE=0.0.0.0/0 ports: - 5432:5432 restart: unless-stopped my Dockerfile.debug is (not sure the last line is necessary): … -
How to make the fields read only in django admin except for the superuser?
I have the following model defined: class PRegistration(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) create_date = models.DateTimeField(auto_now=False, auto_now_add=True) teamName = models.CharField(max_length=144) city = models.CharField(max_length=144) How do I make all these fields read only in the admin page for all staff accounts except the superuser? I wanna do this without specifying the fields one by one so that I can reuse the code in multiple places. -
Models with optional fields with relations
I am looking for a clean way to model data that is optional, but if included will contain a reference to other data. In example below, the cleanest relational modeling is to separate person, insurance plan, and insurance company. class InsurancePlan(models.Model): name = models.CharField(max_length=100, default="Not Indicated") insurancecompany = models.ForeignKey(InsuranceCompany, on_delete=models.CASCADE, null=True, blank=True) claims_address = models.OneToOneField(UsLocation, on_delete=models.CASCADE, blank=True, null=True) class InsuranceCompany(models.Model): name = models.CharField(max_length=50) some_important_id = models.CharField(max_length=50) class Insured(models.Model): name = models.CharField(max_length=50) plan = models.ForeignKey(InsurancePlan, on_delete=models.CASCADE) and then either add a "member_id" field to the insured model or create an Insured_Plan table that links them. However, what if the business requirements say that having InsurancePlan information is optional, because we can get by just knowing member ID and InsuranceCompany? is it ok to have: class Insured(models.Model): name=... plan = models.ForeignKey(InsurancePlan, on_delete=models.CASCADE, null=True, blank=True) insurance_summary = models.ForeignKey(InsuranceCompany, on_delete=models.CASCADE) member_id = models.CharField() Im a bit rusty on relational modeling, but I think having a fk from A to B, and another from A to C where C has a fk to B as well is not good practice. -
How to get an instance from a serializer in Django
I'm trying to get an instance from own serializer def perform_create(self, serializer): serializer.save(slug=utils.unique_slug_generator(**serializer.validated_data),user_profile=self.request.user) but didn't work because in unique_slug_generator i try to access to title of instance ModelClass = instance.__class__ qs_exists = ModelClass.objects.filter(slug=slug).exists() Error : unique_slug_generator() got an unexpected keyword argument 'title' -
Django : I am going to make the system with clients and employees via REST Framework in Custom Admin Panel
I am going to make Admin Panel based on Angular JS. And, this Admin panel will be used by certain Admin, and other users can't access this admin panel. Also, in this panel, we have to manage all users with several roles. How to configure the structure of this project? Please give me the advice. -
Printing in EPSON EPSON TM U220D Model M188D
I want to print a ticket from my printer Printing in EPSON EPSON TM U220D Model M188D but using the python-escpos library does not work for me. What is the error? def imprimir_ticket(): from escpos.printer import Usb p = Usb(0x04b8, 0x0202, 0, profile="TM-U220") p.text("Hello World") p.cut() -
Accessing last row from table C that has FK from table B, which is in one-to-one relationship with A
Let's say we have 3 models: class A(models.model): name = models.CharField(max_length=30, unique=True) class B(models.model): name = models.CharField(max_length=30, unique=True) a = models.OneToOneField(A, on_delete=models.CASCADE, primary_key=True) class C(models.model): name = models.CharField(max_length=30, unique=True) b = models.ForeingKey(B, on_delete=models.CASCADE) transaction_count = models.IntegerField(default=0) and one view: class AListView(generic.ListView): model = A In that view (template) I need to show: name of A, name of B and the last row (ordered by date) of "transactioncount" for each repository from b. In my template I iterate over items in A and show them in following way: {% for a in A %} <tr> <td>{{a.name}}</td> <td>{{a.b.name}}</td> <td>{{??? Don't know what to put here, to show the last row. I tried: a.b.c|last}}</td> </tr> {% endfor %} I tried to build custom tags and use template functions like, but that unfortunately doesn't work: {% with a.b.c_set.all|last as val %} <td>val</td> {% endwith} Among my other tries would be to build a new queryset, but then I don't know how to assign items from model A to that queryset. I tried: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'A': A.objects.all(), 'c_data': C.objects.order_by('B', '-date').distinct( 'B') }) ) What would be the best "pythonic" way to do this? Thanks -
How convert string to a datetime object to be stored and rendered correctly in Django & PostgreSQL?
I'm facing a strange behaviour when trying to convert a string which contains a date then convert it to a datetime object then store it in my PostgreSQL database to be rendered it in Django template. Let's take this example: I have a string like this one: string_date = '15/09/2018 20:30' I know the timezone of this string date which is Europe/Paris So i created a function to convert this string date into an aware datetime object: import pytz from datetime import datetime def create_aware(date): naive = datetime.strptime(date, '%d/%m/%Y %H:%M') # is_dst = True, because Paris is in DST regions # At least this what i've found while searching ... localized = pytz.timezone('Europe/Paris').localize(naive, is_dst=True) return localized Also, i know that Django stores dates within UTC timezone into PostgreSQL. So, basicaly all the dates stored will be normalized to UTC timezone. In my settings.py i use: TIME_ZONE = 'Africa/Tunis' USE_TZ = True But, the problem comes in the backend and while rendering the dates in the template. For this particular date, in the Admin panel it's rendered as: 15/09/2018 2018 20:49 which is incorrect. Because my local timezone Africa/Tunis is ahead by 1 hour from Europe/Paris timezone. And in the template: …