Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to design a data model/form for a betting web app in Django?
While deploying my Django app to heroku, but colletstatic method seems to throw lots of errors. I've tried several solutions posted online but none worked. By the way, I'm using whitenoise for serving my static files. Counting objects: 77, done. Delta compression using up to 12 threads. Compressing objects: 100% (74/74), done. Writing objects: 100% (77/77), 351.57 KiB | 0 bytes/s, done. Total 77 (delta 27), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.1 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting Django==1.11.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 1)) remote: Downloading Django-1.11.1-py2.py3-none-any.whl (6.9MB) remote: Collecting gunicorn==19.7.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 2)) remote: Downloading gunicorn-19.7.1-py2.py3-none-any.whl (111kB) remote: Collecting whitenoise==3.3.0 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 3)) remote: Downloading whitenoise-3.3.0-py2.py3-none-any.whl remote: Collecting psycopg2==2.7.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 4)) remote: Downloading psycopg2-2.7.1-cp36-cp36m-manylinux1_x86_64.whl (2.7MB) remote: Collecting pytz (from Django==1.11.1->-r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 1)) remote: Downloading pytz-2017.2-py2.py3-none-any.whl (484kB) remote: Installing collected packages: pytz, Django, gunicorn, whitenoise, psycopg2 remote: Successfully installed Django-1.11.1 gunicorn-19.7.1 psycopg2-2.7.1 pytz-2017.2 whitenoise-3.3.0 remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", … -
Django - link to url from different app in same project
I am making a Django project with multiple apps and therefore multiple urls.py files. I am trying to an app for user accounts into a project with apps for the shop, cart, and orders. Specifically, I want to link the account/ pages back to the shop Main urls.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('account.urls')), url(r'^cart/', include('cart.urls', namespace='cart')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^', include('shop.urls', namespace='shop')), ] Urls.py for account/: 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'), url(r'^register/$', views.register, name='register'), url(r'^$', views.dashboard, name='dashboard'), ] Here is the template I am using for the account page {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Rachel's Stuff</span> {% if request.user.is_authenticated %} <ul class="menu"> <li {% if section == "dashboard" %}class="selected"{% endif %}> <a href="{% url "dashboard" %}">My dashboard</a> </li> <li {% if section == "images" %}class="selected"{% endif %}> <a href="{% url 'shop' %}">Home</a> </li> <li {% if section == "people" %}class="selected"{% endif %}> <a href="#">People</a> </li> </ul> {% endif %} <span class="user"> {% if request.user.is_authenticated %} Hello {{ request.user.first_name }}, <a href="{% url "logout" %}">Logout</a> {% else %} <a href="{% url "login" %}">Log-in</a> … -
Django how to save custom inline form
I have following setup Model.py class Day(models.Model): date = models.DateField(auto_now=False, auto_now_add=False) price = models.FloatField() payment_method = models.CharField(max_length = 200, blank=True) payment_date = models.CharField(max_length=200, blank=True) room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE) def __unicode__(self): string = str(self.date) + ' ' + str(self.price) return string class Reservation(models.Model): reserved_days = models.ManyToManyField(Day, blank=False) admin.py class DaysInline(admin.StackedInline): model = Reservation.reserved_days.through form = DayForm extra = 1 class ReservationAdmin(admin.ModelAdmin): inlines = (DaysInline,) exclude = ('reserved_days',) forms.py class DayForm(forms.ModelForm): class Meta: model = Day fields = ('date', 'price','payment_method', 'payment_date',) date = forms.DateField(widget = AdminDateWidget) price = forms.CharField(label=("Цена"), widget=forms.TextInput, required=True) payment_method = forms.CharField(label=("Метод оплаты"), widget=forms.TextInput, required=True) payment_date = forms.CharField(label=("Дата оплаты"), widget=forms.TextInput, required=True) def __init__(self, *args, **kwargs): super(DayForm, self).__init__(*args, **kwargs) try: instance = kwargs['instance'] day = Day.objects.get(id=instance.day_id) self.fields['price'].initial = day.price self.fields['date'].initial = day.date self.fields['payment_method'].initial = day.payment_method self.fields['payment_date'].initial = day.payment_date print(day) except (KeyError, AttributeError): pass def save(self, commit=True): m = super(DayForm, self).save(commit=True) if commit: m.save() return m When I try to save, I get error NOT NULL constraint failed: core_reservation_reserved_days.day_id What am I doing wrong ? -
Unnamed title appears blank
I have a form that I can save the title as blank in this case the function transform the blank as unnamed + primary key. But in my case the saving as blank remains blank . I don't know what is the problem. The template : <div class="page-header"> <h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %}</div> <div id="tab1" class="tab" > <form action="{% url "backtest" %}" method='POST' role='form' id='form'> {% csrf_token %} <input type="hidden" name="tabs" value="first" id="toggle-tab1" checked="checked" /> {% include 'tags/parameters_form.html' %} <br /> {% include 'tags/parameters_backtest_form.html' %} <br /> {% if user.is_authenticated %} <input type='submit' id='run' value='Run' class='btn btn-default'> {% if user.profile.is_active %} Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'> {% else %} <p> Expired account! you need to reactivate in order to save parameters. </p> {% endif %} {% else %} Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting! </br> Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs). {% endif %} The models.py : title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to … -
How to change username authentication to email authentication in already buit project?
I initially used to login using username and password but now want to change it to email address authentication in the same site without having to delete the existing users and content. I made the following changes in my files but get an error 'UNIQUE constraint failed: auth_user.username' forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password'] views.py class UserFormView(View): form_class = UserForm template_name = 'main/registration_form.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) # cleaned (normalized) data email = form.cleaned_data['email'] password = form.cleaned_data['password'] user.set_password(password) user.save() # return user objects if credentials are correct user = authenticate(email=email, password=password) if user is not None: if user.is_active: login(request, user) # request.user.username display their username return redirect('main:register2') return render(request, self.template_name, {'form': form}) class LoginForm(View): form_class = UserForm template_name = 'main/login_form.html' def get(self, request): form = self.form_class(None) if error: return render(request, self.template_name, {'form': form}, {'error': error}) else: return render(request, self.template_name, {'form': form}) def post(self, request): email = request.POST.get('email', '') password = request.POST.get('password', '') user = auth.authenticate(email=email, password=password) if user is not None and user.is_active: … -
unittest django login from auth
I want to write simple test for login: view.py: def login(request): username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: auth.login(request, user) else: pass test.py: class TestSuite(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='jacob', email='jacob@…', password='top_secret') def test_user_can_login(self): r = self.factory.post("/login", {"username": "jacob", "password": "top_secret"}) login(r) When I run test (by manage.py test) I recive: System check identified 1 issue (0 silenced). E ====================================================================== ERROR: test_user_can_login (Users.tests.TestSuite) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\bbb\auto\Contract\Users\tests.py", line 16, in test_user_c an_login login(r) File "C:\Users\bbb\auto\Contract\Users\views.py", line 13, in login auth.login(request, user) File "C:\Users\bbb\AppData\Local\Programs\Python\Python36-32\lib\site-pac kages\django\contrib\auth\__init__.py", line 126, in login if SESSION_KEY in request.session: AttributeError: 'WSGIRequest' object has no attribute 'session' ---------------------------------------------------------------------- Ran 1 test in 0.080s FAILED (errors=1) Destroying test database for alias 'default'... What should I do to enable session in test or what is better way to write this test? -
nested Many-to many relationship django
I have these two models: class Item(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) rarity = models.CharField(max_length=3) craftable = models.BooleanField() and class Recipe(models.Model): id = models.IntegerField(primary_key=True) items = models.ManyToManyField(Item) Some Items have a Recipe because they are craftables, others don't because they are base Items. Some Items needed to craft another item need to be created following a Recipe (they are nested, many times!) Example: Item: Construction Material Recipe: [Steel, Chalk, Reinforced Concrete] Item: Reinforced Concrete Recipe: [Sand, Concrete, Bricks] Item: Bricks Recipe: [Resistant Stone, Concrete, Resin] <- All base Objects How can i make a view that displays all the tree of the Items that allows me to make a certain Item? Result: Construction Material Steel Chalk Reinforced Concrete Sand Concrete Bricks Resistant Stone Concrete Resin I can't find a method to go as deep as i need into the relationships... -
Issue creating instance of model object - Arg must be a string or a no. not a model
I am having an issue creating an instance of a model I have. I am trying to create instance of the model modelMedicationResult and I get the error: int() argument must be a string or a number, not 'modelManagmentResult' I have spent over a couple of hours on this and would appreciate any suggestions regarding this: Following are my two models class modelManagmentResult(models.Model): name = models.CharField(max_length=250, default="") modelPatient = models.ForeignKey(modelPatient, default=None) class modelMedicationResult(models.Model): item = models.CharField(max_length=250, default="") result = models.ForeignKey(modelManagmentResult,default=None,on_delete=models.CASCADE) This is how I am using them (3rd statement gives the exception) patient = modelPatient.objects.get(patient_temp_id=temp_pat_id) mgtResult = modelManagmentResult.objects.get_or_create(modelPatient=patient) medResult = modelMedicationResult.objects.get_or_create(item = "Medication Result",result=mgtResult) #------>Error This is the error I am getting here int() argument must be a string or a number, not 'modelManagmentResult' Any idea what I might be doing wrong? -
How to make user list readable for admin users only in Django REST?
I'm trying to make it so that anyone can create a user, but only admin users can view a list of all users and their information. This is my Right now I get this error whether I'm posting or getting from an admin account: TypeError at /accounts/ 'method' object is not iterable Here is my view: from django.contrib.auth.models import User from rest_framework.permissions import IsAuthenticated, AllowAny, IsAdminUser from accounts.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status class UserViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny) def get_permissions(self): if self.action in ('create'): self.permission_classes = [AllowAny, ] return super(self.__class__, self).get_permissions def create(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.create(serializer.validated_data) return Response('success', status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I tried changing the third line to permission_classes = (AllowAny), which I think should allow anyone to get or post anything, I still get the same error. The only way I can get rid of the error is to comment out the permissions_classes and the get_permissions assignment, so that I just have this: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def create(self, request, *args, **kwargs): … -
django transaction management with class based view
I have a class based view and that has method post as follows class Comment(View): def dispatch(self, request, *args, **kwargs): super(Comment, self).dispatch(request, *args, **kwargs) @method_decorator(transaction.non_atomic_requests) def post(self, request, *args, **kwargs): <Some code> In above example transaction.non_atomic_requests does not make post method non atomic, but if I use same decorator for dispatch method then it works? Why? I am using django 1.9 -
poloniex authentication using secret keys in database
I am working on a webapp that should serve analytics about information found on poloniex (a cryptocurrency exchange). The problem is, they need to submit their public key and their secret key in order for me to obtain the information that I need. Is there a way for me to get that information from the user and plug it into my model without the user compromising their security? -
ValueError at /admin/zinnia/entry/add/ in Zinnia?
When adding an entry usin the admin site in Zinnia I get the following error? ValueError at /admin/zinnia/entry/add/ too many values to unpack (expected 2) Does anybody know how to solve this? -
how to redefine something in DecimalField to get rid of extra zeros after coma
I have next field: proba_weihgt = models.DecimalField(max_digits=8, decimal_places=4,default=0) and when user print into the form field for example 1,22 then in the model would be saved 1,2200 how I can redefine something in main class DecimalField to get rid of extra zeros? -
Wagtail API - show image URL on json output
Fairly new to Wagtail - I'm currently creating a Wagtail API for my React app. Have installed successfully and am getting a json output, but not getting a url for images that are uploaded in the Wagtail admin panel. I have searched online, but not having much joy. This is the basic home page model I have created class BarsHomePage(Previewable, Themable, Page): bars_site_homepage_test = models.CharField(max_length=255, blank=True) feed_image = models.ForeignKey( 'DemoImage', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) api_fields = ['bars_site_homepage_test','feed_image'] Any help or pointers would be much appreciated. -
(Django/Python/Javascript) Accessing a list of tuples in Javascript?
In my views.py file, I am able to return two lists of tuples that contain a book title as the first element, and the book type as a second element. I am able to access these in html interchangably by creating for loops like "for each in booklist_latin" then use curly braces for the expressions {{ each.0 }} or {{ each.1 }} so yes, now I got my goal there. But there's some filtering options that I need to take place based on the type of each book. So I need to be able to access the second element of each tuple within my lists of tuples, perhaps put it through a conditional of some sort. I do not know the syntax for doing that. I'm still learning Javascript and I still have a ways to go, let alone the fact I'm learning Django. It's pretty efficient to be able to write {{ each.0 }} and get the first element the tuples I made in my views.py file. But how can I do that in Javascript? Will I have to jsonify anything? And if so could you provide an explanation or useful documentation on what that does in this context … -
detect image errors django template
I pull in image links from several sources so I have a mix images that render and then have problems rendering. I have many images that return with http error 400, 403 etc. Am I able to detect this in the django template so that I can render something more suitable than a broken image? Something like: {% if ia.image.url %} <img src="{{media_url}}{{ia.image.url}}" alt="#" class="trimimg1" /> {% else %} <img src="{% static 'common/app/images/news-default.jpg' %}" alt="#" class="trimimg1" /> {% endif %} -
Print as it is input from form django
I have a model : class somemodel(models.Model): message=models.TextField() def __str__(self): return self.message now i have make a form for this model and took input from user . say user is giving input like bellow: Hi i am a djago developer and i am developing a website . Bellow are my contact details: Address: xyz mobile:123456 pin:1234 But when i print out the out put this is coming like bellow. Hi i am a djago developer and i am developing a website . Bellow are my contact details: Address: xyz mobile:123456 pin:1234 Is it possible to print the input given by the user as it is it have typed .Kindly suggest . -
Django Performance, Slow TTFB Without Any Queries
I have a simple view which renders an HTML template. No variables whatsoever and no database queries. However, my TTFB is still 665ms. Here is code for the view: def test_page(request): return render(request, 'home/test_page.html') The template home/test_page.html is a 12.5 KB file. I'm using an Amazon EC2 instance (t2.medium) deployed with Elastic Beanstalk. Django version 1.8 using python 3.4. Since I'm using Elastic-Beanstalk, The configuration of the server is done by AWS. An interesting observation is that a smaller file such as a 4.1 KB file gives me a TTFB of 145ms. -
Django REST: Limit query of nested view (depth=1) in serializer?
I use UserSerializer to add a lot of different models onto my user object. This allows me to easily access properties in the client. The problem is - I cannot figure out a way to limit the query on the related objects. For example, my user serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'first_name', 'last_name', 'email', 'messages', 'calendar', 'profile', 'relationship', 'notifications', 'last_login', 'date_joined') read_only_fields = ('last_login', 'date_joined', 'username', 'id') depth = 1 I want to limit the results of messages to 10, so in my MessageSerializer and MessageView set I have the following: def get_queryset(self): queryset = Message.objects.filter(user=self.request.user.id).order_by("-create_time")[:10] return queryset However - this does not limit the number of results on User.messages. As it returns a list of all messages for the user. Is there a way to limit messages when it's attached to the User serializer/view and the depth is equal to one? -
How to make sure a filtered update view is safe?
I've made a list view of users that are part of a group named Manager. I've made a link to edit those users. The link looks like: http://localhost:8000/en/manager/edit/12 So this is about "editing the User number 12". If you manually change 12 to 1, it works... so what is the way to properly make sure the User you're editing belongs to the group Manager? I've tried to override get_object and return None if the User doesn't belong to the Manager group but it doesn't make sense: def get_object(self, queryset=None): group = Group.objects.get(name="Manager") try: return User.objects\ .filter(groups__in=[group])\ .get(pk=self.kwargs.get('pk')) except User.DoesNotExist: return None What is the correct way to do this? -
ImportError: No module named rest_framework_extensions.cache.mixins
Trying to set up RDMO on a apache server, but when running "python manage.py runserver" this error accures. Before that many other import Error accurred which I solved by pip install missing package, but i am not able to find requred package to solve this error. And it would also be very helpful if someone can provide name to the whole package/bundle required for RDMO server run. -
Adding rows breaks datatable in Django
I have a datatable in Django that functions fine when hardcoded, but when I add my Django template tags it breaks. The inspect on the page says: Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined in jquery.datatables.min.js This only happens when I have more than one user in the table, or try to add a column in the table with django. Since I will be using multiple datatables in my project, I need to figure out what I'm doing wrong. The datatable JS code I'm using comes from a template, and I'm not sure if the error is in the template code or in my Django template code. So please excuse the long code blocks. employees.html (django template): <div class="card-body collapse in"> <div class="card-block card-dashboard"> <button id="addRow" class="btn btn-primary mb-2 js-create-employee"><i class="ft-plus"></i>&nbsp; Add New Employee</button> <table class="table table-striped table-bordered zero-configuration"> <thead> <tr> <th>Name</th> <th>Username</th> <th>Roles</th> <th>Email</th> <th>Mobile Contact</th> <th>Actions</th> </tr> </thead> <tbody> {% for profile in user_profile_list %} <tr> {% if not profile.user.is_superuser %} <td><a href="{% url 'dispatch:profile_detail' pk=profile.user_id %}">{{ profile.user.get_full_name }}</a></td> <td>{{ profile.user.username }}</td> <td> {% for g in profile.user.groups.all %} <div class="tag tag-default">{{ g.name|split:'_'|title }}</div> {% endfor %} </td> <td>{{ profile.user.email }}</td> <td>{{ profile.mobile_phone }}</td> <td><a href="#" alt="Edit"><i … -
Django: How to migrate dynamic models made at runtime
In my Django app, a specific user input will result in the creation of a new model. Here is the code I am using to create the model and register it. model = type(model_name, (ExistingModel,), attrs) admin.site.register(model, admin_options) from django.core.urlresolvers import clear_url_caches from django.utils.module_loading import import_module reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() This successfully creates the new model, however, when I click on the model to see the table on the admin page, I get the following error: relation "ExistingModel_NewModel" does not exist This usually means that the new model changes have not been migrated. How can I migrate dynamically created models in Django to see their corresponding data tables? -
Dynamic choices in admin inline for CharField
I have a model with a Charfield in which no choices are set. Now in the admin panel, in the inline admin in which I display this model, I want to present a dropdown with possibilities to fill in (where the choices need to be fetched dynamically and the display is different from the value that I want to fill in the field). How would I make this happen without changing the model? This is what I tried (not dynamically yet): class MyModelInline(TabularInline): model = Mapping def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'status': kwargs['choices'] = ( ('accepted', 'Accepted'), ('denied', 'Denied'), ) return super(MyModelInline, self).formfield_for_choice_field(db_field, **kwargs) return super(MyModelInline, self).formfield_for_dbfield(db_field, **kwargs) However, when I open my model, I get an error __init__() got an unexpected keyword argument 'choices'. I looked at the stack trace and found that this is the __init__ it is talking about: <path>/django/forms/fields.py in __init__ 214 super(CharField, self).__init__(*args, **kwargs) What should I change to make this work? I am using Python 3.5 and Django 1.8.14. -
Python-django: Cannot edit, create, view, delete and print item
I'm programming language for 3 months, but I'm totally blue and I don't know a lot of them. I ask to you because i was searching solutions for this problem: While in compilation doesn't show any error but when I'd like to edit, view, delete or print that item then comes to main site it doesn't do (for example delete or view). This project is made of... 27 files. So i will send to you most of important codes and maybe they help: models.py class Games(models.Model): title = models.CharField(max_length=50) type = models.ForeignKey("Types") date_of_production = models.DateField() producer = models.ForeignKey("Producers") availability = models.BooleanField() account = models.IntegerField() language = models.ForeignKey("Languages", default='') price = models.CharField(max_length=10) abbr = models.CharField(max_length=5) def __str__(self): return self.title class Languages(models.Model): language = models.CharField(max_length=15) def __str__(self): return self.language forms.py from django import forms class GamesForm(forms.Form): title = forms.CharField(label= "Nazwa gry", max_length=50) type = forms.CharField(label= "Typ gry", max_length=10) date_of_production = forms.DateField(label= "Data produkcji") producer = forms.CharField(label= "Nazwa producenta", max_length= 10) availability = forms.BooleanField(label= "Czy jest dostępne?") account = forms.IntegerField(label= "Ilość dostępnych sztuk") language = forms.CharField(label= "Języki", max_length=50) price = forms.CharField(label= "Cena", max_length=10) abbr = forms.CharField(label= "Skrót waluty", max_length=5) class LanguagesForm(forms.Form): language = forms.CharField(label= "Języki", max_length=15) urls.py """ from django.conf.urls import url from …