Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Declare another template path for CreateView
I have 2 Apps in my django project , 1. HotelApp , 2. ManageHotels The hotel details are shown to the user using the model in the HotelApp. However I have set up a CreateView form in the ManageHotels app for owners to add Hotels. The problem is , CreateView attempts to find the form template inside HotelApp/templates/HotelApp/hotels_forms.html I would rather put hotels_forms.html in the ManageHotels/templates/ManageHotels/hotels_forms.html How do I change the template path ? Thanks! -
django, init inherited model from super model
I want to save the history of what happens to objects stored in a particular model in my Django application. To that end I want to create a model that inherits from my "observed" model and adds two additional fields, history_id to override what is the primary key of the initial model, and when to save the time when a particular modification happened. Then I want to use the @receiver(pre_save, MyModel) to save that new model to DB. However, the difficulty I ran into is that I cannot easily instantiate the inherited model from the super model, for example, like this: inherited = InheritedModel(super_model_instance). For now it seems that I will have to write a serialiser to serialise the super model and to init the inherited model from it, but is there an easier way to do it? -
Django Select Widgets has string options values instead of integer
I have used a modelForm with a limited integer choice field: n = models.IntegerField(choices=[(1,1), (2,2), (3,3)]) The corresponding widget is naturally a Select Widget. The problem is the corresponding value to each option is formatted has a string instead of an integer. <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> When I post the selected value and clean my form, I get the following error: n must be an integer. FYI: I am working with Django 1.10. -
Django app generator
I made generator for django web application. I made my generator project in one file, and when I start generator, it makes django web app in new file. But I have one issue, I don't know hot to integrate generated code with hand written code. I make changes in generated django web app, but when I start my generator again, it override all hand written code. Can anyone help me with this problem? -
Decorator to cache expensive non-field django model attributes
I have some models, lets say it's something like this: class book(models.Model): name = models.CharField(max_length=256) ... class vote(models.Model): book = models.ForeignKey( book ) is_up = models.BooleanField( default = False ) ... class comment(models.Model): ... And I would like to have a decorator, ModelCacheAttr so that I can cache some expensive methods the first time they're used or calculated elsewhere. Like the total number of upvotes, downvotes and the overall percentage. Also, It's important to note that models should be cached based on their model_id rather than their python object id. And, It should be possible to removed a cache, in-case it has been expired, likely in a related vote's post_save signal. So lets extend the book class so that it covers all that I said: class book(models.Model): name = models.CharField(max_length=256) ... def _update_votes(self): U,D = 0,0 for v in vote.objects.filter( book_id = self.id ): if v.is_up: U+=1 else: V+=1 self.percentage.set_cache( U / (U + D) if U + D > 0 else 50 ) self.up_votes.set_cache( U ) self.down_votes.set_cache( D ) @ModelCacheAttr def percentage(self): self._update_votes() return self.percentage() @ModelCacheAttr def up_votes(self): self._update_votes() return self.up_votes() @ModelCacheAttr def down_votes(self): self._update_votes() return self.down_votes() @ModelCacheAttr def total_comments(self): return comments.objects.filter( book_id = self.id ).count() So far, this … -
what is 'mpoly' : 'MULTIPOLYGON' in Geodjango , what should be its default value if its blank
I am working on example from [https://docs.djangoproject.com/en/1.11/ref/contribt/gis/tutorial/][1] using mysql as database, followed most of the steps given and while trying to load data using load.run() as in the doc, seems like # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField() is blank, and needs a default value, what should be the default value of this field. Is it ok to keep it blank. The data needed is : world_mapping = { 'fips' : 'FIPS', 'iso2' : 'ISO2', 'iso3' : 'ISO3', 'un' : 'UN', 'name' : 'NAME', 'area' : 'AREA', 'pop2005' : 'POP2005', 'region' : 'REGION', 'subregion' : 'SUBREGION', 'lon' : 'LON', 'lat' : 'LAT', 'mpoly' : 'MULTIPOLYGON', } while command line shows this data, which does not have 'mpoly' field {'pop2005': 83039, 'region': 19, 'fips': 'AC', 'lat': 17.078, 'subregion': 29, 'name': 'Antigua and Barbuda', 'un': 28, 'iso3': 'ATG', 'iso2': 'AG', 'area': 44, 'lon': -61.783} -
LEFT OUTER JOIN in Django
I have two models class Topic(models.Model): name = models.CharField(max_length=200,verbose_name="Topic name") description = models.TextField(default="") class Comment(models.Model): message = models.TextField(default="") user = models.ForeignKey(to=User,related_name="user_comments",on_delete=models.CASCADE) topic = models.ForeignKey(to=Topic, related_name="comments",on_delete=models.CASCADE) How can i do a LEFT outer join of Topic Model on Comments for a particular "user" made "comment". The equivalent Sqlite query is like SELECT * FROM topic_topic a LEFT OUTER JOIN topic_comment b ON b.topic_id=a.id AND b.user_id=1 Is there a good way of doing this in django queryset? Please let me know -
django: Better implementation of LEFT JOIN
I have two models, class Post(models.Model): id = models.IntegerField(primary_key=True) post_title = models.CharField() post_type = models.CharField() class Comments(models.Model): id = models.IntegerField(primary_key=True) post = models.ForeignKey(Post, related_name="post_comments") comment = models.CharField() user_id = models.IntegerField() I want to get "all" posts with post_type "blog" along with comments of a specific user. If am doing it with raw query, the query will be like this, SELECT p.id as post_id, p.post_title, pc.comment FROM Post p LEFT JOIN Comments pc ON (p.id=pc.post AND pc.user_id=20) WHERE p.post_type='blog' The above query will return all posts with post_type as "blog" along with comments by user_id 20. How can I implement this in django? I tried the bellow method, But it didnt work. queryset = Post.objects.filter(post_type='blog', post_comments__user_id=20).all() I googled a lot but I couldnt find a good solution for this. -
Django: python manage.py migrate does nothing at all
I just started learning django, and as i try to apply my migrations the first problem occurs. I start the server up, type python manage.py migrate and nothing happens. No error, no crash, just no response. Performing system checks... System check identified no issues (0 silenced). You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 01, 2017 - 11:36:27 Django version 1.11, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. python manage.py migrate And that's the end of my terminal feed. I thought maybe it just looks like nothing happens, but no. The changes weren't applied and I can't proceed any further. Any ideas on what's going on? -
Smallest unused id from mysql table with django
suppose i have a table A(id, x, y). I've inserted where id = 1 to 35 but 15, 18 etc. is there a way to find the smallest unused id in django. what should i do to insert with smallest available id available whenever i add an item. there are some similar questions i found on stackoverflow that explains how to do it in mysql(links below). but as i am very new to django i am not getting how to do that in django. mysql find smallest + unique id available -
DRF and HStoreField?
I have a model with HStoreField: When I try view in browser I get: AttributeError at /test/ 'str' object has no attribute 'items' I set the breakpoint on to_representaion method in DictField and I see: def to_representation(self, value): self: CharMappingField() value: ' "key"=>"value" ' """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) if val is not None else None for key, val in value.items() } value is string, but must be dict. It is a model and serializer: class Test(models.Model): field = HStoreField() class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = '__all__' Same I can not add a new value: ProgrammingError at /test/ can't adapt type 'dict' Django version (1.11), Rest Framefork (3.6.2) Thanks for any help! -
How to connect a microsoft azure SQL server to django webapp
I am working on a Django webapp, and for this app I would like to have an online database. It just so happens my faculty grants access to using some Microsoft Azure services, including SQL databases. Now, I would like to connect an Azure SQL database to my Django project, however I cannot get this to work. I can connect to the database through PyCharm's data source view, however using the same parameters in settings.py yields this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03846270> Traceback (most recent call last): File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\kairy\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File … -
Convert nested dict/json to a django ORM model, without hard coding the data structure
I want to import data from json files into my django db. The json contains nested objects. Current steps are: Set up my django models to match the json schema (done - see below) Import json file into python dict using mydict = json.loads(file.read()) (done) Convert dict to django models (done - but solution is not pretty) Is there a way I can convert my nested dict into django models without hard-coding the data structure? Bonus points for automatically generating the django models (i.e. the models.py file). Thanks in advance! How I'm currently doing it Step 3 is easy if the dict does not contain any nested dicts - just construct a new object from the dict i.e. MyModel.objects.create(**mydict) or use django fixtures. However, because my json/dict contains nested objects, I'm currently doing step 3 like this: # read the json file into a python dict d = json.loads(myfile.read()) # construct top-level object using the top-level dict # (excluding nested lists of dicts called 'judges' and 'contestants') c = Contest.objects.create(**{k:v for k,v in d.items() if k not in ('judges', 'contestants')}) # construct nested objects using the nested dicts for judge in d['judges']: c.judge_set.create(**judge) for contestant in d['contestants']: ct = c.contestant_set.create(**{k:v … -
Error adding new models to database Django
models.py class Genre(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name Genres.py from MyVideoGames.models import Genre from ClientIGDB import ClientIGDB genres = ClientIGDB.api_call("genres", ["name"], 50) for genre in genres: g = Genre.objects.create(name=genre["name"]) g.save() When I'm trying to add some models to sqlite db i'm not able to do this import: from myproj.models import Genre. I don't know why... When I do it this error is shown: % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. If someone can help me I'll be really gratefull -
How to Additional attribute to object
Im new to Django and Python which I'm using to create a Hotel Booking website. Im trying to fetch all the rooms associated with a hotel With the returned object Im trying to add an extra attribute onto each room returned. This attribute will equal a variable . Example: rooms = Room.object.filter(hotel=thehotel) // for each room in rooms Roomsavailable = Room.totalrooms Roomsleft = RoomsAvailable - RoomsBooked //attach roomsleft onto each room object room.spaceleft = Roomsleft Any help would be appreciated , hope i've explained it ok. -
How to serve an image with a different random name each time with Django?
I'm implementing some sort of image captcha for a client, and my client requested the images be served with a different URL on each challenge attempt. My web server is Django and I currently serve the images using nginx locally but I plan to host the images on S3. What's the best approach to do this? I could: Use Django to declare a python view that would download the image from where it is originally hosted and serve it under the random name;(the name saved under the challenge attempt instance). Use Django to call on the file system or to call Amazon API to copy the file to a random name, when the challenge is initialised, and then delete that file later when triggered by the solving of a challenge relating to that image. The reason I'm asking is because Django isn't efficient in serving static data. Any other ideas? -
Django app to have this sequence: One add -> Video call with screen sharing -> Rate the call and donation. Any tips on how to implement this pipeline?
In your answers I would love if you included a reasoning behind your tip. Any programming language is welcome, though I would prefer Java, Python, C, and/or C++. The add should be something like the ones in youtube videos, in which you can't skip it as it is short (so money is guaranteed). Maybe use AdSense? Thank you -
Django runserver gives me syntax error
python manage.py runserver Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import(name) File "C:\Users\Kaidi\Desktop\CM2\CM\CM\urls.py", line 18, in from mysite import views File "C:\Users\Kaidi\Desktop\CM2\CM\mysite\views.py", line 2, in from rest_framework import viewsets, permissions, status File "C:\Python27\lib\site-packages\rest_framework\viewsets.py", line 26, in from rest_framework import generics, mixins, views File "C:\Python27\lib\site-packages\rest_framework\generics.py", line 10, in from rest_framework import mixins, views File "C:\Python27\lib\site-packages\rest_framework\views.py", line 98, in class APIView(View): File "C:\Python27\lib\site-packages\rest_framework\views.py", line 103, in APIView authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES File "C:\Python27\lib\site-packages\rest_framework\settings.py", line 220, in getattr val = perform_import(val, attr) File "C:\Python27\lib\site-packages\rest_framework\settings.py", line … -
How to use MultipleChoiceField in django-widget-tweaks?
I have form with MultipleChoiceField field which has dynamic list for choices. With the help of this form users can select data and add them to database. Sometimes dynamic list can be empty []. So I want to show message in template when its empty but next code didnt show me message. I use django-widget_tweaks application in my template. Where is my mistake? forms.py: class RequirementForm(forms.ModelForm): symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) class Meta: model = Requirement fields = ('symbol',) requirement_add.html: {% load widget_tweaks %} <form method="post" action="{% url 'project:requirement_add' project_code=project.code %}"> {% for field in form %} {% render_field field class="form-control" %} {% empty %} <p>Form is empty!</p> {% endfor %} </form> -
ALLOWED_HOSTS error in Django app on Digital Ocean. Setting the variable does not resolve the error
I followed this guide to set up a Django app on DO: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 However, I'm unable to get past the common ALLOWED_HOSTS error, where everyone typically forgets to put anything in the list and its a simple fix. Even with the correct values entered, or with the catch-all "*", the error persists. I've never had this happen before, so I'll put my configuration files here to get some more eyes on it. Any ideas as to what could be causing this? contents of /etc/uwsgi/sites/myapp.ini: [uwsgi] project = myapp uid = myuser base = /home/%(uid) chdir = %(base)/%(project) home = %(base)/%(project)/venv module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true contents of /etc/systemd/system/uwsgi.service: [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown myuser:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target contents of /etc/nginx/sites-available/myapp: server { listen 80; server_name mydomain.com www.mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myuser/myapp_static; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/myapp.sock; } } -
How Connect angular 2 to Django?
I have a problem to connecting angular 2 to django. I want to send some data from http post request and in django use this data that sent from http request(Save to model,show,etc). I tried some code but that doesn't worked. Can anyone help me to fix my problem??? Thanks a lot. -
I couldn't store the values in database from the custom form in HTML page. Using Django
This is my views.py file. from django.shortcuts import render, redirect from .forms import RegistrationForm def index(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() else: form = RegistrationForm() args = {'form': form} return render(request, 'Login/index.html', args) This is my models.py file from django.db import models class Customer(models.Model): fname = models.CharField(max_length=25) company = models.CharField(max_length=15) email = models.CharField(max_length=15) password1 = models.CharField(max_length=15) password2 = models.CharField(max_length=15) def __str__(self): return self.company + ' - ' + self.fname Following is my forms.py file from django import forms from django.forms import ModelForm from .models import Customer class RegistrationForm(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = Customer fields = ( 'fname', 'company', 'email', ) def save(self, commit=True): user= super(RegistrationForm, self).save(commit=False) user.UserName= self.cleaned_data.get['name'] user.CName = self.cleaned_data.get['cname'] user.Email = self.cleaned_data.get['email'] if commit: user.save() return user And HTML file is: <!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="favicon.ico"/> <title>Customer Desk</title> {% load static %} <link href="{% static 'css/Styles.css' %}" rel="stylesheet" type="text/css" /> </head> <body class="login"> <!-- header starts here --> <div id="desk-Bar"> <div id="desk-Frame"> <div id="logo"> <a href="http://127.0.0.1:8000/Home/">Virtual Agent </a></div> <div id="header-main-right"> <div id="header-main-right-nav"> <form method="post" action="" id="login_form" name="login_form"> <table border="0" style="border:none"> <tr> <td ><input type="text" tabindex="1" id="mail" placeholder="Email or Phone" name="email" class="inputtext radius1" value=""> </td> <td ><input type="password" … -
Django Rest framework, POST FOREIGN KEY
I'm trying to post a nested object, and im getting the following error: Column person_id cannot be null Here's my serializer,model and my view. Model.py class Person(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) curp = models.CharField(max_length=50) rfc = models.CharField(max_length=12) gender = models.CharField(max_length=20) class Employee(models.Model): id = models.IntegerField(primary_key=True) joining_date = models.DateField() salary = models.DecimalField(18, decimal_places=2, max_digits=50) status = models.IntegerField() person = models.ForeignKey(Person, related_name='persons', on_delete=models.CASCADE) user = models.ForeignKey(User) branch = models.ForeignKey(Branch) Serializers.py class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('__all__') class EmployeeSerializer(serializers.ModelSerializer): persona = PersonSerializer(read_only=False) usuario = UserSerializer(read_only=False) sucursal = Serializer(read_only=False) class Meta: model = Employee depth = 1 fields = ('__all__') def create(self, validated_data): person_data = validated_data.pop('person') user_data = validated_data.pop('user') branch_data = validated_data.pop('branch') employee = Empployee.objects.create(**validated_data) for person_data in person_data: Person.objects.create(employee=employee, **person_data) #### Code for user and branch #### return empleado Views.py class ListCreateEmployee(generics.ListCreateAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer I've added the method create as i've read it in the django rest website but i didnt understand how to call that method. -
Django - Generic detail_view doesn't accept an object_list
I have the following in urls.py: url(r'frameworkslist/(?P<pk>\d+)$', DetailView.as_view(queryset=Category.objects.all().order_by("id"), template_name='home/subcategory.html')) And in my html template: {% extends "Layout.html" %} {% block content %} {{ subcategory.Name }} {% for item in object_list %} <h5> <a href="/search/{{ item.id }}">{{ item.Name }}</a> </h5> {% endfor %} <a href = "/frameworkslist/">Back to framework list</a> {% endblock %} I was wondering why object_list was empty but when I changed my urls to the following, it worked. (returned the ListView template instead of DetailView): url(r'frameworkslist/(?P<pk>\d+)$', ListView.as_view(queryset=Subcategory.objects.all().order_by("id"), template_name='home/subcategory.html')) Also to note, it seems like passing the variable "model=Subcategory" to the DetailView would return the first record (or what should be a single model) of the Subcategory table and pass that to the Template. So my question is two-part, the second being: How do you a collection of objects to DetailView Template? -
How to use django-notifications to inform a user when somebody sends a new request to them
I have been developing in Django for some time now, and have developed a neat website having functionality such as sending requests to a user and accepting of the request. However, there is still one thing that is missing and i.e. creating a notification for users. What I want to do is to inform users in their profiles, whenever somebody sends a new request to them, or if they somebody accept the request.