Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"rotating" columns and unique_together
I have a django model: class ShortestRoads2(models.Model): start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True) end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True) map = models.ForeignKey('project.MapProject', null=True) def __str__(self): return str(self.start_node) + ' to ' + str(self.end_node) class Meta: unique_together =(("start_node", "end_node", "map"),) class Nodes(models.Model): number = models.IntegerField(null=True, unique=True) geom_node = models.PointField(spatial_index=True) Is it possible to create another unique_together contraint, where "start_node" and "end_node" fields are switched? Explained: obj = ShortestRoads2() obj.start_node = Nodes.objects.create(number=x1) obj.end_node = Nodes.objects.create(number=x2) obj.save() # Object created obj2 = ShortestRoads2() obj2.start_node = Nodes.objects.create(number=x1) obj2.end_node = Nodes.objects.create(number=x2) obj2.save() # Raising as expected: IntegrityError obj3 = ShortestRoads2() obj3.start_node = Nodes.objects.create(number=x2) #Notice varible change obj3.end_node = Nodes.objects.create(number=x1) #Notice variable change obj3.save() # Object created I want a exception raised when I'm saving obj3. But how to? -
HTML layout object doesn't work
I quite new with Django Crispy Form and I have tried to add a HTML object in my form but it's not working. All the other elements are rendered but not the HTML. This is my form: forms.py class MyUserRegistrationForm(forms.ModelForm): class Meta: model = MyUser fields = ['title', 'privacy_disclaimer_accepted'] def __init__(self, *args, **kwargs): super(MyUserRegistrationForm, self).__init__(*args, **kwargs) helper = FormHelper() helper.form_method = 'post' helper.form_class = 'form-horizontal' helper.label_class = 'col-sm-2' helper.field_class = 'col-sm-6' helper.form_error_title = 'Form Errors' helper.error_text_inline = True helper.help_text_inline = True helper.html5_required = True helper.form_tag = False helper.layout = Layout( Fieldset('Information', 'title'), HTML(""" <div id="iframe" class="mt-5"> <h6>Notice/Disclaimer:</h6> <div class="privacy-policy"> {% if privacy_disclaimer %} {{ privacy_disclaimer }} {% else %} {% include "registration/privacy_policy.html" %} {% endif %} </div> </div> """), Fieldset('Privacy Statement', 'privacy_disclaimer_accepted', ) ) I have a basic HTML file, where I have the normal html, header and body tags. This is the HTML registration page: register.html {% extends "base.html" %} {% block title %}Create an account{% endblock %} {% block content %} <div class="registration-page"> <h3 class="text-center">Create an account</h3> <div class="registration-page__form"> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-error"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} … -
Invalid block tag: 'else' - 'extends' inside a if statement
I'm trying to extends a template depending of the the existence of the 'custom_nav' variable: {% if 'custom_nav' %} {% extends custom_nav %} {% else %} {% extends "playexo/default_nav.html" %} {% endif %} But I get: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? It's probably a dumb error but I can't figure it out, I'm wasting my time on it for 1h now... I've searched for similar problem and it seems like an old one: Django Invalid block tag: 'else' -
The Django make ORM query
class Task(models.Model): subject = models.CharField(max_length=256) description = models.TextField(max_length=1024) reward = models.PositiveIntegerField() begin_date = models.DateField() number_of_people = models.PositiveIntegerField(default=1) class TaskDetail(models.Model): user = models.ForeignKey(User, related_name='tasks') task = models.ForeignKey(Task, related_name='tasks') This is a simple task assignment system model designed by me. and I have a question.I attempt to make a user report that include the number of task user've done.but I don't know how to make ORM query. users = User.objects.all Does anyone know how to solve this issue? Thx -
Modify django Admin forms
I have the following model form which I inherit in the majority of my models. class UserStamp(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, related_name='%(app_label)s_%(class)s_created_by', on_delete=models.CASCADE) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='%(app_label)s_%(class)s_updated_by', on_delete=models.CASCADE) class Meta: abstract = True Where I construct my own forms I use form.instance.created_by = self.request.user and everything is ok. But not in admin (expecting staff users) because he uses his own forms. What is the simplest way to make the admin forms work properly(something tha I don't need to do each of them from zero). -
Cannot get PyCharm Django project to read and display Django Templating Language Tags
I have been pulling my hair out over this, am new to using Django for web development and I have never setup a Django project in PyCharm. It is Django v2.0 and PyCharm 2017.3. I have a basic project which consists of two apps, for examples sake lets call one Test and one TestProj. Test is the core of the site where settings.py is located, and TestProj is where I wish to add templates. The Test urls.py points to the TestProj urls.py, which when requested, serves a html file to the root url of the site. This content is located in a folder again called Test which is located in a templates folder in TestProj Essentially the directory structure is as follows: Test > settings.py etc TestProj > templates > Test > index.html header.html other python files are here! The index.html file is served fine but the problem occurs when I try to use Django templating to link in another html file. This is index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <div> {% block content %} {% endblock %} </div> </body> </html> And this is header html which is located in the same templates directory: {% … -
django + uwsgi in docker
What is the best way to deploy Django apps inside a docker. I have looked into couple of blogs and it seems in most of the examples everyone is trying to put nginx + django + uwsgi in one container. But container should have one process only. so i am trying django and uswgi in one container and nginx is in another container or on host machine itself. Could some please suggest me best approach. P.S:- My django app is just providing me REST API results. and i am not using Django template for my static contents. I am also looking for enabling all these with https. Please share a blog or github link if someone already have achieved similar way of django app hosting. -
Data is not being read directly from the database instead of buffer on 2nd call
I have the following piece of code in my model that ensures that user will be not able to modify a record that was modified by someone else after he has opened it. def save(self, *args, **kwargs): on_disk = Lease.objects.get(pk=self.id) self.full_clean() if on_disk.version == self.version: error = 0 #do nothing else: raise ValidationError('Record have been modified by another user, please reopen and edit again') # self.version = self.version + 1 return super(Lease, self).save(*args, **kwargs) There is mechanism implemented(Django concurrency package) that ensures that after each save version value will be modified. However, this piece of code doesn't work it appears to me that on_disk value is not being populated with the most recent value from the disc but get it from some buffer and as result this code check is useless. Any idea how to make it work? -
Django: Get model fields in wrapper function
I want to create log data in which I want to show the previous data in the table according to primary key. After that I want to show the updated data which I am able to log. Please help in fetching the database data fields according to whatever primary key has been provided. Making another function to fetch queryset in the wrapper function is also not happening. views.py def func_detail(func): @wraps(func) def func_wrapper(*args, **kwargs): logging.basicConfig(filename='test.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logging.getLogger(__name__) print("Inside wrapper. Calling method %s now..." % (func.__name__)) changed = [field for field in (args[1].data).__dict__] print(changed) if func.__name__ == 'list': logging.info("This is all the list of objects created by you in table") elif func.__name__ == 'create': logging.info("New user added in database & table:{}".format(dict(args[1].data))) elif func.__name__ == 'update': logging.info("With pk:{}".format(list(kwargs.values()))) logging.info("previous data in model fields"??) logging.info("Updated model fields from table:{}".format(dict(args[1].data))) elif func.__name__ == 'partial_update': logging.info("In pk:{}".format(list(kwargs.values()))) print("Updated partial data from table in fields:{}".format(dict(args[1].data))) r = func(*args, **kwargs) return r return func_wrapper class UsersViewSet(viewsets.ViewSet): @func_detail def list(self, request): queryset = Mytable.objects.all() if request.GET.get('name'): queryset = queryset.filter(name=request.GET.get('name')) serializer = CheckSerializer(queryset, many=True) return Response(serializer.data) @func_detail def update(self, request, pk=None): users = get_object_or_404(Mytable, name=pk) serializer = CheckSerializer(users, data=request.data) if serializer.is_valid(): serializer.save() return … -
Typeerror: view must be callable
when i run my server i get a type error message telling me that 'my view must be callable or a list/tuple' and from what i gathered django version differs an for clarity sake,am using django latest version...anyways here's my views.py and urls.py for my project url.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^login/$', 'django.contrib.auth.views.login',name='login'), url(r'^logout/$', 'django.contrib.auth.views.logout',name='logout'), url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login',name='logout_then_login'), ] views.py from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'],password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html',{'section': 'dashboard'}) -
Django + WSGI: When is wsgi.py called?
I deployed my Django-project via Apache2 on a server. The problem I have is that I have two setting-modules: settings.py which are my local development settings and settingsprod.py which are my productive settings. I found the following line in the WSGI.py: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") Is this module only called when using WSGI? And if yes is this a good place to use my production settings like so? os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settingsprod") For local development I use the development server like so: python3 manage.py runserver Does this still defaults to settings.py then? -
How complete web application architecture work?
I am newbie in Web Development. I am Backend developer. I'm using Python-Django web framework. I understand what is Server and What is Client. Recently I have heard lot of new terms like Apache web server, Nginx, AWS, WSGI, Gunicorn. I don't understand how they fit in complete web application architecture. I write the backend code in Python (with Django framework) and called it as a server. How my server (My Python code) is different from Apache web server? How my code is using Apache or Nginx? What's the role of WSGI and Gunicorn? I didn't understand anything. I didn't understand web architecture. Can someone push me in right direction? How can I understand all terminology? Any help would be appreciated. Thanks. -
ListApiView returning only one set of object
I am trying to make an autocomplete api. Where based on one keyword, will return two separate object. But always returning one object and other one is always empty. What am i doing wrong ? My code class HotelAutoComplete(ListAPIView): serializer_class = HotelSerializer permission_classes = [] def list(self, request): city_list = [] hotel_list = [] if request.GET.get('q', None): city_list = Hotel.objects.filter( city__name__icontains=request.GET.get('q') ).values('city__name', 'city__country__name') hotel_list = Hotel.objects.filter( name__icontains=request.GET.get('q') ).values('name', 'slug') return Response({'city_list': city_list, 'hotel_list': hotel_list}, status=200) -
deploy django on tomcat
List item I am using Django 1.8 on jython in windows 10. I am beginner to Django and jython. Have created a simple Django project following the tutorial https://docs.djangoproject.com/en/1.8/intro/tutorial01. After packaging using buildwar(including jars), when I deploy the mysite.war archive in tomcat, I get error. My project name is mysite, I have referenced the jython path in web.xml. My project structure is -mysite -WEB-INF -lib -jruby-extras-fileservlet.jar -jython.jar -lib-python -django -doj -polls -application_settingspy.class -application_settings.py -eggs.pth -web.xml -wsgi Error is Traceback (most recent call last): File "D:\jython27\Lib\modjy\modjy.py", line 80, in service self.exc_handler.handle(req, resp, wsgi_environ, mx, (typ, value, tb) ) File "D:\jython27\Lib\modjy\modjy.py", line 76, in service self.dispatch_to_application(req, resp, wsgi_environ) File "D:\jython27\Lib\modjy\modjy.py", line 92, in dispatch_to_application app_callable = self.get_app_object(req, environ) File "D:\jython27\Lib\modjy\modjy_publish.py", line 68, in get_app_object return self.get_app_object_old_style(req, environ) File "D:\jython27\Lib\modjy\modjy_publish.py", line 120, in get_app_object_old_style return self.load_object(source_filename, callable_name) File "D:\jython27\Lib\modjy\modjy_publish.py", line 142, in load_object self.raise_exc(NoCallable, "Error loading jython callable '%s': %s" % (callable_name, str(x)) ) File "D:\jython27\Lib\modjy\modjy.py", line 121, in raise_exc raise exc_class(message) modjy.modjy_exceptions.NoCallable: Error loading jython callable 'application': No module named mysite I don't know what have I missed, the application_settings file shows: from mysite.settings import * CONTEXT_ROOT = "mysite" Can anyone help me on this issue and share any project structure? -
Django Allauth: Customize Forms (Label, Fields, Order)
im new to Django and even newer to Allauth. My Problem is i want to customize the Forms (Login,SignUp etc) but i'm unable to find a good Tutorial and couldn't find anything in the Documentation or in Forums that helped me. First of all i want to make a Custom SignUp Form, adding new Fields is working for me but i'm not able to Change the Labels and Placeholder or the Order. My forms.py looks like this: from django import forms class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label='Voornaam') email = forms.EmailField(max_length=30, label='Email Adresse') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.email = self.cleaned_data['email'] user.save() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['email'] = forms.EmailField(label='Label') I'm thankful for every help, and maybe some links with more infos for customizing Allauth. -
Django Creating a Custom User with the Django Rest Framework
I'm trying to create a custom user using the Django Rest Framework. I got it to the point to where I can create a regular user, but I'm unsure on how to extend it to the custom user model. models.py: from django.db import models from django.contrib.postgres.fields import ArrayField from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) languages = ArrayField(models.CharField(max_length=30, blank=True)) serializers.py: from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password') def create(self, validated_data, instance=None): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user views.py: @api_view(['POST']) @permission_classes((AllowAny,)) def create_user(request): serialized = UserSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) else: return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) How do I extend the languages field to the UserSerializer to where it can process it? Would it be better to create a signal for every time a user is created it then creates a userprofile automatically? -
Django: HttpResponseRedirect is not defined
I finally managed to POST data from a form to a database in django, however when I press the submit button on my form I get the error: Request Method: POST Request URL: http://127.0.0.1:8000/post_url/ Django Version: 1.11.2 Exception Type: NameError Exception Value: name 'HttpResponseRedirect' is not defined Exception Location: /home/xxxx/Desktop/123/src/exercises/views.py in post_treasure, line 26 Python Executable: /home/xxxx/Desktop/123/bin/python Relevant views.py: def post_treasure(request): form = TreasureForm(request.POST) if form.is_valid(): treasure = Treasure(name = form.cleaned_data['name'], value = form.cleaned_data['value'], material = form.cleaned_data['material'], location = form.cleaned_data['location'], img_url = form.cleaned_data['img_url']) treasure.save() return HttpResponseRedirect('/numbers/') Relevant urls.py: urlpatterns = [ url(r'^post_url/', post_treasure, name='post_treasure'), url(r'^admin/', admin.site.urls), url(r'^numbers/', numbers, name="numbers"), url(r'^about/', about, name="about") ] Other note: The data is successfully posted if I press the back button to view the new updated data passed from the model to the template, or if I use the admin interface to simply view the data -
How Open YouTube Video by clicking link in Django
I am trying to open my videos if user click on any given link but a am not able to do this whenever i clicked on any link then i got 404 error here i have added some screen short please tell me what should i do This is my html page -
Get Value From 'param' Of 'views.py' In Javascript Django
In views.py def website(request, pk=None): if not model_utils.check_admin_permission(request): return loginAndContinuosRequest(request) if pk: obj = get_object_or_404(Website, pk = pk) form = WebsiteForm(instance=obj) fields = obj.get_manage_payment_accounts() else: obj = None form = WebsiteForm() fields = [] if request.POST: if pk: form = WebsiteForm(request.POST, request.FILES, instance=obj) else: form = WebsiteForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("views_manage_websites")) params = { 'obj':obj , 'form':form, 'fields': fields, 'test': 'test', } return render(request, TEMPLATE_PATH + 'website.html', params) In script in template (.html), <script> $(document).ready(function() { alert({{ obj.id }}); //(1) alert({{ obj.pk }}); //(2) alert({{ obj.site_name }}); //(3) alert ({{ test }}); //(4) }); </script> The alert (1) and (2) is shown. But the alert (3) and (4) isn't shown. Can you explain for me. Thanks. -
Django one-to-many relationship in models (not about lookups)
I am trying to figure out how to define a one-to-many relationship between two models. The difficulty here is that I do not want to touch one of the models and therefore can not use the usual ForeignKey (Many-to-one). There are many question on this topic but they all either talk about how to do the lookup (reverse ForeignKey lookup) or they suggest to just add a Foreign Key to one side. Here is a similar question. I will use the same code example. This is what I am looking for: class Dude(models.Model): numbers = models.OneToManyField('PhoneNumber') class PhoneNumber(models.Model): number = models.CharField() Usually I would go ahead and just add a Foreign Key to PhoneNumber as suggested in many answers: class PhoneNumber(models.Model): dude = models.ForeignKey(Dude, related_name='numbers') But in my situation I would like to not touch the PhoneNumber model and therefore define something on the Dude model. The reason for this is that I am defining a model describing a special circumstance which is rarely used. If I used a ForeignKey on the (PhoneNumber) model I would have 99.9% of all models leave this field blank. I do not really like the idea to have a field which is always blank … -
Django + Bootstrap 4 + white-space pre-wrap/|linebreaks
I have a form with a comment as textfield where the user also uses linebreaks etc. It looks nice. Now I want to preserve these linebreaks when I call the comment in my templates. Using {{ comment|linebreaks }}does not help. Should I use white-space:pre-wrap with bootstrap and my {{ comment }} instead? Thanks in advance! -
Django forms with one-to-many relationship
I have two models in django class Project(models.Model): name = models.CharField(max_length=250) customer = models.CharField(max_length=250) class Subproject(models.Model): name = models.CharField(max_length=250) project = models.ForeignKey(Project, on_delete=models.CASCADE) I would like to create form for creating projects. The problem is that I would like to have on one form fields to create Project and dynamic number of fields to create Subproject because Project can have several Subprojects and I don't know what will be the amount of Subprojects before creating a form. At the moment my view function looks like this: def project_new(request): if request.method == "POST": form = ProjectForm(request.POST) if form.is_valid(): project = form.save(commit=False) project.save() return redirect('subproject_new') else: form = ProjectForm() return render(request, 'projects/project_edit.html', {'form': form}) And template looks like this: {% block content %} <div class="form__background"></div> <div class="box-form"> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% endblock %} I am using ModelForms: class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ('name', 'customer',) class SubprojectForm(forms.ModelForm): class Meta: model = Subproject fields = ('project', 'name',) -
Django has no attribute 'GeoManager issue
from django.db import models from django.contrib.gis.db import models location = models.PointField(srid=4326,null=True,blank=True) objects = models.GeoManager() I am hosted my Django project on AWS server. I cant able to run the project because of the error I added below, but I implemented the same project in my ubuntu system and its working fine. Unhandled exception in thread started by .wrapper at 0x7f527104b6a8> Traceback (most recent call last): File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/core/management/init.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/django_env/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/ubuntu/django_env/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and_load File "", line 958, in _find_and_load_unlocked File "", line 673, in _load_unlocked File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 10, in class BusStop(models.Model): File "/home/ubuntu/Sg_Bus/SgBusTransport/models.py", line 17, in BusStop objects = models.GeoManager() AttributeError: module 'django.contrib.gis.db.models' has no attribute 'GeoManager' -
Django 2.0 multiselect issue
I am testing 2.0 and have encountered the same error in two different places. It has to do with multi-select. I get the following error. Exception Value: not enough values to unpack (expected 2, got 0) here is the code from crispy-forms-foundation {% if not field|is_checkbox and not field|is_checkboxselectmultiple %} {% crispy_field field %} {% endif %} the other package error was from: localflavor.us.models import USStateField, PhoneNumberField, USZipCodeField What do I need to change to get these to work properly in 2.0? Cheers -
How to isolate django apps of same project with team members
We are a team of 5 members, we have one Django project with multiple apps, now we want to divide each member to different-2 apps and other members can't make any change to any other apps but they are allowed to use it, how to achieve that, please help.