Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django multi-table inheritance: upgrade a "place" to a "restaurant"
The same question was already asked on SO in 2010 here, with the most recent answer being from 2014. I would like to know if this got simpler with the current django 2.0. I couldn't find anything about it in the docs. In the django docs for model inheritance, the example lists a Place and Restaurant model as such from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) Say I already have an object in Place, how can it be promoted to a Restaurant? -
Specify a select widget for a field in a formset
I am building a form which has a nested model formset for holding multiple addresses for a subscriber. I want to specify dropdown for region and city fields. So I added widgets property to the formset definition. AddressFormSet = modelformset_factory( Address, fields=('country', 'region', 'city', 'locality'), widgets={'region': Select(), 'city': Select()}, extra=0) This is working fine and am able to select the value in the dropdown and save it to the database. When I come to the subscriber_edit page again, I see that the fields region and city are empty. This is the Address model. class Address(models.Model): subscriber = models.ForeignKey(SubscriberProfile, on_delete=models.CASCADE, related_name='address') locality = models.CharField(max_length=100, blank=True, verbose_name="Locality") city = models.CharField(max_length=40, verbose_name="City") region = models.CharField(max_length=40, verbose_name="State") country = models.CharField(max_length=200, verbose_name="Country") This is the subscriber_edit view. def subscriber_edit(request, slug): _subscriber = get_object_or_404(SubscriberProfile, slug=slug) _address = Address.objects.filter(subscriber=_subscriber).all() if request.method == 'POST': subscriber_form = SubscriberForm(data=request.POST, instance=_subscriber, prefix='s') addr_fmset = AddressFormSet(data=request.POST, prefix='addr') if all([subscriber_form.is_valid(), addr_fmset.is_valid()]): subscriber_form.save() for form in addr_fmset: addr = form.save(commit=False) addr.subscriber = sub addr.save() return redirect('subscriber_preview', slug=_subscriber.slug) else: subscriber_form = SubscriberForm(instance=_subscriber, prefix='s') addr_fmset = AddressFormSet(prefix='addr', queryset=_address) return render(request, 'main/subscriber_edit.html', { 'sub_fm': subscriber_form, 'addr_fmset': addr_fmset }) When I print(addr_fmset) in the view, I see that the values for region and city are empty. <input type="hidden" … -
Autopopulate Django modelform placeholder with current project model name
I wan't to autopopulate the ProjectForm fields with the current value of the field, i.e.: class ProjectForm(forms.ModelForm): project_name = forms.CharField(label='Project Name', widget=forms.TextInput(attrs={'placeholder': 'fixed_value'})) However instead of a fixed value I would like to prepopulate the field with the current project name (if appropriate). -
Select an option ofrom SeparatedValueSet()
I'm using Django and `mysql'. This is my Question table: class Question(mixins.OrdMixin, mixins.EqMixin, models.Model): section = models.ForeignKey('Section', on_delete=models.CASCADE, related_name='owner') text = models.TextField() options = SeparatedValuesField(blank=True, null=True) options_score = SeparatedValuesField(blank=True, null=True) objects = models.Manager() The field options contains Never, occasionally, often and the field options_score the corresponding scores like 0,1,2,3. My CompletedQuestion table is: class CompletedQuestion(models.Model): updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='responder') question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='question_source') answer = models.CharField(max_length=256) where the field answer contains a value contained in Question.options. Based on the CompletedQuestion.question_id I want to get the score that corresponds to CompletedQuestion.answer. My current query is the following which is not correct. It just get the CompetedQuestion.answer value. selected_quest_option = CompletedQuestion.objects.filter(question_id__exact=question_id).values("answer") -
Distribute ssh connections made by Django App (multi-threaded python function) among n number of Kubernetes Replicas
My Django App makes SSH connections to n number of machines (using a multithreaded python function). When replica=n is set in kubernetes deployment.yaml file then I want my app to distribute the connections among the n replicas. I mean 1 replica should connect to k number machines, another to next k number of machines and so on. When all the replicas are done then it should take the connections in cyclic fashion i.e. next k connections to first machine and another next k to other machine. I tried with 2 replicas but all the connections are getting established by both the pods(replicas). I want those connections to be distributed among the pods. How can I achieve this ? -
To run the Flask and Django application
I don't understand why if I want to run Flask application I need (venv) $ export FLASK_APP=microblog.py (venv) $ flask run But if I want to run Django application I only (venv) $ python manage.py runserver without export DJANGO_APP=microblog.py Why? Why I need the export app in the first case, but in the second case I don't need? -
python getting many to many from model mixin returning None
I have a model: class Employee(models.Model, MyMixin): full_name = models.CharField(max_length=255) items = models.ManyToManyField(Item, blank=True) and a mixin class: class MyMixin(object): def my_m2m(self, field): field_value = getattr(self, field) print(field_value) // do something with many to many field emp = Employee() emp.my_m2m("items") It gives me the result like employee.Item.None while printing emp.my_m2m("items") on console. Why is it not giving the list of item associated with it ? Am I missing anything ? -
Create and use a custom username validator for a registration form
currently I'm attempting to create a custom validator to validate usernames. Django only provides two validators: ASCIIUsernameValidator and UnicodeUsernameValidator. But both of them accept special characters like @, but I want to accept only alphanumeric characters (A-Za-z0-9) and underscores. I did read the validator documentation and I believe that something like this should work: # project_name/validators.py from django.core import validators from django.utils.deconstruct import deconstructible from django.utils.translation import gettext_lazy as _ @deconstructible class AlphanumericUsernameValidator(validators.RegexValidator): regex = r'^[\w]+$' message = _( 'Enter a valid username. This value may contain only English letters, ' 'numbers and underscores.' ) flags = re.ASCII But how would I actually use it? I checked and AbstractUser contains this line: username_validator = UnicodeUsernameValidator(). Would I have to create an AbstractUser like below (not sure if I even can make one because I already have some users registered)? from django.db import models from django.contrib.auth.models import AbstractUser from project_name.validators import AlphaNumericUsernameValidator class User(AbstractUser): username_validator = AlphaNumericUsernameValidator() Would I have to create a custom AbstractUser? Or is there some other simpler way that doesn't require the creation of one just to change a single validator? -
Joined selection from two tables
I'm using Django with a mysql database. I have the table Question that contains the fields: id, text, section_id and I have the table CompletedQuestion that has the fields: id, question_id where the field question_id is foreign key to Question.id. My models.py contains: class Question(mixins.OrdMixin, mixins.EqMixin, models.Model): section = models.ForeignKey('Section', on_delete=models.CASCADE, related_name='owner') text = models.TextField() class CompletedQuestion(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, related_name='question_source') I want to check whether there are completed questions in CompletedQuestion where belong to a specific section_id from Question. My current query is the following but it's not the proper one: quest_id = Question.objects.filter(section_id = section_id) -
Django / Postgres Group By Aggregate
I've have an issue regarding queries with a group by clause. Lets assume I have the following Django-Model: class SomeModel(models.Model): date = models.DateField() value = models.FloatField() relation = models.ForeignKey('OtherModel') If I want to do a query where I group SomeModel instances by OtherModel and annotate the latest date: SomeModel.objects.values('relation').annotate(Max('date')) This is all great, but as soon as I want to add a filter on the already annotated queryset I am getting nowhere: SomeModel.objects.values('relation').annotate(Max('date')).filter(value__gt=0) This would indeed filter out all the value != 0, however I only want it after the annotations took place. If the latest date of a relation has the value 0, I want it to be filtered out! -
403 Forbidden on curls calls to my website
Im using an notification API that makes curl calls to a specific url on my website to send me values and receive a response from the server and everything is working fine when i make calls using AJAX or when i use curl setting CURLOPT_USERAGENT to mimic a browser. My problem is that the api which sends me the notification don`t use this option so i have to allow this call to be made without this option being set. I run a python/django website -
OperationalError when converting from sqlite3 to postgresql
I tried changing my db from sqlite3 to postgresql using this tutorial: https://tutorial-extensions.djangogirls.org/en/optional_postgresql_installation/ but when i try to migrate i get the following error Traceback (most recent call last): File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", line 213, in ensure_connection self.connect() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\postgresql\base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\core\management\commands\migrate.py", line 83, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\migrations\executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\migrations\loader.py", line 52, in __init__ self.build_graph() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\migrations\loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\migrations\recorder.py", line 65, in applied_migrations self.ensure_schema() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\migrations\recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_name s(self.connection.cursor()): File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", line 254, in cursor return self._cursor() File "c:\Users\gudat\Documents\Arbeit\Szenario\Python\venv1\lib\site-packages\ django\db\backends\base\base.py", … -
Custom Django field for converting values but on the db side
I have a model class MyModel(models.Model): my_field = TextField(...) Now I want to convert it to something like class MyModel(models.Model): my_field = MyCustomField(...) where MyCustomField is similiar to TextField except that whenever I read data from the db I want it to be wrapped in a custom database function, e.g. SELECT foo(my_field) FROM my_models; Note the return type of foo is text as well, if that matters. It doesn't seem that overwriting def from_db_value on TextField works since this converts data after receving it from the database which obviously is too late. The requirement is that the database function foo is called on the db side and this cannot be moved to the Python's side. I also don't want to write raw queries everywhere, that's why I'm trying to figure out how to write a custom field for that. Is that possible with Django? If the answer is database dependent then I'm fine with Postgresql only. -
how to get client side ip address using django application?
I have tried using this: ip_address=str(request.META.get('HTTP_X_FORWARDED_FOR')) But it always return None. Also I have tried this: ip_address=request.META.get('CF-Connecting-IP', request.META.get('REMOTE_ADDR')) But it always return 127.0.0.1 I need client side ip address, not the remote ip address. Any help would be appreciated. -
Python / Django - Issue with parsing JSON on server
I have a Django server API which is hosted on PythonAnywhere, and a client.py file that is hosted locally on my computer. The theory of the program is that it will check stock of a particular item, of which the database is accessed via the API. The client.py file is run and asks for the user input for the product (E.g. "Apple"). This should then be sent in a JSON payload to the server using a "requests.get" request. The server should then load this payload, and parse the information from it, before using the value to query the database. Once it is retrieved as a JSON using the GET function in the client.py, the JSON should be displayed. However, my issue is that I cannot seem to get my server working. I always get the following issue: TypeError at api/checkstock: string indices must be integers I have read up on this, and tried applying various answers to try and fix it, but none seem to work. Here is the body of my code: client.py (stored locally) import json import requests def main(): item_input = input("Enter Item Name:") params = {'item': item} r = requests.get('http://XXXXX.pythonanywhere.com/api/checkstock/', json=params) # blocked out exact link … -
modelformset_factory in SessionWizardView
I'm working with Django 1.11. I use django-formtools to do a multiple steps form. In my SessionWizardView I would like to apply modelformset_factory only for the first step of my form. I don't really know how to do it. Views.py : FORMS = [ ("step1", FormStep1), ("step2", FormStep2) ] TEMPLATES = { "step1" : "app/step1.html", "step2" : "app/step2.html" } class TestFormWizard(SessionWizardView): instance = None myModelFormSet = modelformset_factory(HotelRegistration, form=FormStep1) def done(self, form_list, form_dict, **kwargs): new_list = [] for form in form_list: new_list.append(form.cleaned_data) print(form, file=sys.stderr) form.save() return render(self.request, 'done.html', { 'form_data': new_list, }) def get_form_instance(self, step): if self.instance is None: self.instance = Hotel() return self.instance def get_template_names(self): return [TEMPLATES[self.steps.current]] FormStep1 When I return new_list, only the last instance of FormStep1 is saved : done.html but I want all instances, not only the last one. -
app doesn't work with otree 1.4.4
I have an otree app that works perfectly on my computer, with otree 1.3.1. In this app, I specify several settings variables. One of those is called "sure", which can take values 0 or 1, and I refer to it in models.py and views.py as self.settings.config['sure']. In my html page, I have several conditions as "{% if sure == 1 %}" or {% if sure == 0 %}. When trying to run it on the computer of the lab (which has the new version of otree, 1.4.4 ), I have the following problem: The file models.py reads it fine, so when I ask to print "sure" on the terminal, it prints the right value of the variable. The file views.py cannot read it, so in the html page it makes a mess: some things it shows as if "sure" == 0, others as if "sure" == 1, and when I ask to show it in the html page, using {{sure}}, it shows nothing. It doesn't show any error messages. The problem is only with the settings variable "sure", and only with the version 1.4.4 of otree. By now, the only solution I can think of is to re-write the app … -
Django/Python - dynamically creating HTML pages for SEO
I have a catalog of information for which I want to create several thousand open web pages for the purposes of SEO. My web application for which I want traffic is created with Django and I'm wondering the best way to do something like this would be. Would using a Jinja template to serve the different content be the most optimal way or would serving pre-made HTML/CSS pages with Nginx be a better way? I'm a beginner with SEO and this is my first project of the type so any pointers are hugely appreciated. -
admin view error id column
I have a database (postgresql). I recreate the model with python manage.py inspectdb. Here the model : class Groupe(models.Model): corg = models.CharField(max_length=2) cagence = models.CharField(max_length=2) cgroupe = models.IntegerField() class Meta: unique_together = ("corg", "cagence","cgroupe") managed = False db_table = 'groupe' I just add the unique_together (pk in the original table) when I try to acces to the admin page of groupe i have an error : ERREUR: the columne groupe.id doesn't existe LINE 1: SELECT "groupe"."id", "groupe"."corg", "groupe"."cagence", "... any idee ? -
Django: Self Join on table
I wanted to write a query something like this: SELECT b.consumerservicerequestid, b.statusDate, a.statusdate, timediff(a.statusDate, b.statusdate) FROM consumer_servicerequest_log a, consumer_servicerequest_log b WHERE a.consumerservicerequestid=b.consumerservicerequestid AND a.status="Parts received" AND b.status in ("Parts pending","Parts request accepted"); Is there a way to do it in Django ORM? -
Add placeholder field to basic UserCreation Django sign up form
I am fairly new to Django and I have set up a sign up form with some additional fields. In my forms.py file I have the following code: class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) In my views.py I have the following code: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('index') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) Then in my signup.html view I am rendering the following: <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button class="btn-contact" type="submit">Let's Go!</button> </form> Essentially what I want to do is add placeholder text in each field but this is not appearing the way I have set it up. To do this I need more control over the forms fields but I don't know how to do … -
Creating model in django and overriring django-redux
I want to create a model in django(1.11). I am using django-redux for registration. After user log in, it will ask some details about the user and that will be saved inside database. Below is my code but nothing is there inside db. It should be a seperate model: from django.db import models # Create your models here. class UserProfile(models.Model): name = models.ForeignKey('auth.User') email = models.EmailField('auth.User.email') mob_number = models.IntegerField() address = models.TextField() def __init__(self): return self.name -
DRF change url to absolute url
i uploaded some file to server you can see the adress: "file": "/upload/user_1/backup.zip", can you please tell me how can i change it to absolute url like: localhost:8000/upload/user_1/backup.zip", we had some function linke get absolute url in django i dont about drf its my serializer class: class ProductSerializer(ModelSerializer): product_ratings = ProductRatingsSerializer(many=True, read_only=True) product_video = ProductVideoSerializer(many=True, read_only=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name + ' ' + obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'title', 'mini_description', 'you_learn', 'you_need', 'full_description', 'price', 'video_level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_video' ] read_only_fields = ['product_id', 'created_date', 'updated_date', 'author', 'product_ratings'] def validate_title(self, value): if self.context['request']._request.method == 'POST': qs = Product.objects.filter(title__iexact=value) if self.instance: qs.exclude(pk=self.instance.pk) if qs.exists(): raise serializers.ValidationError("this title is already used") return value -
set data in html django
I learning django rest. And now i wont output some json data in html. My json: {'Resul': {'Period Start': '2017-01-01', 'Period End': '2017-12-12'}} then i send it json to html: context = {'Resul': json_data['date']} content = render_to_string('balance.html', context) json_data['date'] - {'Period Start': '2017-01-01', 'Period End': '2017-12-12'} in html i write this code Period: {{ Resul['Period Start'] }} - {{ Resul['Period End'] }} but have error: Could not parse the remainder: '['Period Start']' from 'Resul['Period Start']' -
Adding new ManyToMany object in UpdateView
I have searched but can't find an answer to my query. I would like a similar functionality in front-end as is possible when adding an object in the Admin site (where you get a little green "add" button next to the select box for a ManyToMany relationship). This is my (simplified) Client model: class Client(models.Model): name = models.CharField(max_length=60) competitors = models.ManyToManyField(Competitor) def __str__(self): return self.name This is my UpdateView view within views.py: class ClientUpdate(UpdateView): model = Client fields = [ 'name', 'competitors', ] And this is my template: <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> Can I change those aspects to be able to add a Competitor at the point of adding or updating a Client?