Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do ...ON DUPLICATE KEY UPDATE... in django
Is there a way to do the following in django's ORM? INSERT INTO mytable VALUES (1,2,3) ON DUPLICATE KEY UPDATE field=4 I'm familiar with get_or_create, which takes default values, but that doesn't update the record if there are differences in the defaults. Usually I use the following approach, but it takes two queries instead of one: item = Item(id=1) item.update(**fields) item.save() Is there another way to do this? -
Loop inside a Raw Queryset
I have 2 Models: Item(models.Model): name = models.CharField(max_length=255) Image(models.Model): item = models.ForeignKey(Item, related_name='item_images', on_delete=models.CASCADE) ... In Django to do a reverse FK query(from Product to Image) a prefetch_related. is usually use. Because I have a more complex query with multiple conditions and a Lateral Join in a case I preferred to do a RAW Queryset. The most simplistic case: SELECT *, i.image, FROM item AS t INNER JOIN image AS i on t.id = i.item_id Taking in consideration, that and item can have one or multiple images how can I retrieve the images for each item. In prefetch case, I can loop over item.item_images , but in this case ? -
django uploads via POST to directory but still doesn't see http://localhost:8000/media/picture.jpg
Im trying to configure my static files in django. I've set STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") STATIC_ROOT = os.path.join(BASE_DIR, "static/") and when I upload a photo via admin panel it appears in the folder I want ("src/media") but I cant access it via URL that is Page not found (404) Request Method: GET Request URL: http://web/media/picture.jpg Im not sure if it's not a fault of wrong URL because it's on localhost -
How to create unique URLs in django?
My project is type of a blog. In this blog I need to post news. I can just add news with Django admin page and display all the news in one url. Now I want each news to have a unique URL. My models.py: from django.db import models class Newsform(models.Model): headline = models.CharField(max_length=50) description = models.CharField(max_length=100, default='') content = models.CharField(max_length=100, default='') image = models.ImageField(upload_to='news_image', blank=True) views.py: from django.shortcuts import render from blog.models import Newsform def show_content_from_database(request): headline_news=Newsform.objects.all() context = { 'headline_news': headline_news } return render(request, 'blog/index.html', context) Here is urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.show_content_from_database, name='show_content_from_database'), ] And for the last, the part of index.html, where I display the titles of every news: {% for headline in headline_news %} <h1>{{ headline.headline }}</h1> {% endfor %} At best, I'd like to post a unique link to the news here: <h1>{{ headline.headline }}</h1>, and that unique page has to extend some base.html. I've searched the solution of my problem in the internet, but didn't find. This task may be big enough, so I'd like to see a link to some example in the internet (youtube, or stackoverflow, or github, etc). -
Is it possible to use the admin form for a proxy model in Django with a ManyToMany relationship?
I'm modelling a quiz and the associated questions as follows: # models class Question(models.Model): title = models.TextField() category = models.TextField() class Quiz(models.Model): questions = models.ManyToManyField(Question, through='OrderedQuestion') class OrderedQuestion(models.Model): # A through table to allow ordering of questions question = models.ForeignKey(Question, ...) quiz = models.ForeignKey(Quiz, ...) order = models.PositiveIntegerField(default=0) I have two types of questions that are handled by proxy models: # proxy models to handle specific question categories class BoatQuestion(Question): objects = BoatQuestionManager() # handles setting category class Meta: proxy = True and a similar one for CarQuestion. I have inlines for both BoatQuestions and CarQuestions to allow them to be edited independently on the Quiz admin page. The admin setup is: class QuestionAdmin(admin.ModelAdmin): model = Question class BoatQuestionAdmin(admin.ModelAdmin): model = BoatQuestion class CarQuestionAdmin(admin.ModelAdmin): model = CarQuestion class BoatQuestionInline(admin.TabularInline): model = BoatQuestion.quiz.through def get_queryset(self, *args, **kwargs): return OrderedQuestion.objects.filter(question__category='boat') def formfield_for_foreignkey(self, *args, **kwargs): if db_field.name == 'question': kwargs['queryset'] = BoatQuestion.objects.all() return super().formfield_for_foreignkey(db_field, request, **kwargs) class CarQuestionInline(admin.TabularInline): # similar to above class QuizAdmin(admin.ModelAdmin): model = Quiz inlines = (BoatQuestionInline, CarQuestionInline) The add and edit buttons for BoatQuestions and CarQuestions use the generic admin form for Question. Is there a way to ensure the BoatQuestionAdmin form is used when editing BoatQuestions inline? -
Django Login via e-mail And Csrf failed with @csrf_protect decorator
I'm fighting with relatively easy task - Login with email instead of builded in username Login system. So the problem that I met is exacly as "CSRF verification failed. Request aborted" Probably I have all the components needed in this action but let me show all the code to handle my mistake. The main intresting thing is that I've placed csrf token in login and in views. The models are migrated with mysql db. Of course emailAuthBackend is added to settigns.py. I am newbie in Django so I've tried to avoid more advanced technics. Do you have any ideas what might be wrong with my code ? Thank u class EmailAuthBackend(): def authenticate(request,username=None,password=None,**kwargs): try: user = Users.objects.get(email=username) success = user.check_password(password) if success: return user except Users.DoesNotExist: try: user = Users.objects.get(username=username) if user.check_password(password): return user except Users.DoesNotExist: return None def get_user(self,user_id): try: user= Users.objects.get(pk=user_id) if user.is_actve: return user return None except Users.DoesNotExist: return None models() class Users(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. username = models.CharField(max_length=100) password = models.TextField() email = models.CharField(max_length=50) USERNAME_FIELD = 'email' forms() and Urls class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(render_value=False),max_length=100) path('login/',views.login_view,name='login_view'), login view() @csrf_protect def login_view(request): def errorHandle(error): form = LoginForm() return … -
Migration error. TypeError: expected string or bytes-like object django
I have a problem, this gives me an error and I don't know why. I have tried everything including deleting the date fields even if I change it to a datetime field, i always get the same error. This is django 1.11. This happens everytime I migrate. 1.This is the traceback of the error. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, profiles, sessions Running migrations: Applying profiles.0031_auto_20181107_1420...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/claudia/Documents/kiboko/Aramati-Safaris/virtual/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/claudia/Documents/kiboko/Aramati-Safaris/virtual/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/claudia/Documents/kiboko/Aramati-Safaris/virtual/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/claudia/Documents/kiboko/Aramati-Safaris/virtual/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/claudia/Documents/kiboko/Aramati-Safaris/virtual/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- packages/django/db/migrations/operations/fields.py", line 86, in database_forwards field, File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- packages/django/db/backends/base/schema.py", line 414, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/home/claudia/Documents/kiboko/Aramati- Safaris/virtual/lib/python3.5/site- … -
Getting the message from defined in a Django RegexValidator object
I defined a RegexValidator using Django's built-in class. Like as follows: from django.core.validators import RegexValidator validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.') The issue is that I am using this from outside of the model definition. Like as follows: try: validate_alphanumeric("++") except: # Somehow get the message defined above, that is get 'Only alphanumeric characters are allowed.' In other words, if the string passed causes an error, I want to get the message stored in my RegexValidator object definition. How can I do this? -
django request.POST.get not woking while working with react
way one: not working def register(request): if request.method == "POST": username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") print(username,email,password) way two: working def register(request): if request.method == "POST": data = request.body convert = data.decode("utf-8") ds = json.loads(convert) username = ds["username"] email = ds["email"] password = ds["password"] print(username,email,password) react function onSubmitSignUp = () => { fetch('http://127.0.0.1:8000/register/', { method:'post', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ username:this.state.username, email:this.state.email, password:this.state.password }) }) .then(response => response.json()) .then(user => { if(user){ console.log(user); }else{ console.log("error"); } }) } when i am sending some data from frontend(react) via post method it is working in the second way. but i want the first one(django standard) i checked firstone is woking in postman also but in browser first way is not working. please have a look in to my code. -
Docker DefectDojo Error: A server error occurred. Please contact the administrator
I used this docker container: https://hub.docker.com/r/appsecpipeline/django-defectdojo/ Dashboard When I run with Docker, I get an 8000 port error. I can't see the Dashboard. OS: Centos 7 -
Django Chained Dropdown List for form
I have the following model: class Technology(models.Model): short_name = models.CharField(max_length=30, null=True, unique=True) name = models.CharField(max_length=100, unique=True) provider = models.CharField(max_length=100) def __str__(self): return self.name class Entity(models.Model): short_name = models.CharField(max_length=30, null=True) name = models.CharField(max_length=100) description = models.CharField(max_length=500, null=True) is_storage = models.CharField(max_length=1) is_presentation = models.CharField(max_length=1) technology = models.ForeignKey(Technology, on_delete=models.CASCADE) class Meta: unique_together = (('short_name', 'technology'),) def __str__(self): return '{0} - {1}'.format(self.technology.name, self.name) class Node(models.Model): name = models.CharField(max_length=255, unique=True) display_name = models.CharField(max_length=100, null=True) description = models.CharField(max_length=500, null=True) entity = models.ForeignKey(Entity, on_delete=models.CASCADE) class Meta: unique_together = (('name', 'entity'),) def __str__(self): return self.name I'd like to build the following form for Node model: technology - dropdown list from Technology model entity - dropdown list from Entity model - limited to selected technology from the first dropdown (above) name - charfield for node name rest of Node fields The problem is the first dropdown - how to achieve this ? I've tried : https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html but technology dropdown list doesn't appear on the form page, and in most examples all form fields are taken from the model to insert / update. Please provide template definition as well. Thanks a lot, Pawel -
Django : Add kwargs parameters from get_context_data() to ModelForm
I would like to use kwargs and pass kwargs element from Django CBV to my form file in the __init__. I have a View class with get_context_data() which let to pick up email input, filled by user : class HomeView(FormView): form_class = CustomerForm def get_context_data(self, **kwargs): if "DocumentSelected" in self.request.GET: customer_email = self.request.GET['EmailDownloadDocument'] kwargs['customer_email'] = customer_email return super(HomeView, self).get_context_data(**kwargs) And I have a forms.py file with this part class CustomerForm(forms.ModelForm): def __init__(self, *args, **kwargs): customer_email = kwargs.pop('customer_email', None) super(CustomerForm, self).__init__(*args, **kwargs) if customer_email is not None: self.fields['email'].initial = customer_email self.fields['first_name'].initial = Customer.objects.get(email__iexact=customer_email).first_name self.fields['last_name'].initial = Customer.objects.get(email__iexact=customer_email).last_name self.fields['country'].initial = Customer.objects.get(email__iexact=customer_email).country_id self.fields['institution'].initial = Customer.objects.get(email__iexact=customer_email).institution class Meta: model = Customer fields = ['email', 'first_name', 'last_name', 'country', 'institution'] widgets = { 'email': forms.TextInput(attrs={'placeholder': _('name@example.com')}), 'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}), 'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}), 'institution': forms.TextInput(attrs={'placeholder': _('Agency, company, academic or other affiliation')}), } However it returns None in my form file while my get_context_data() prints the email address. Something is wrong in this part ? -
Django API: get authenticated user from request
The user is authenticated using allauth. I want to create a profile and set the authenticated user as the owner of the profile. How can I get the user? Model class: from django.db import models from allauth.utils import get_user_model from courses.models import Course class Profile(models.Model): owner = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) courses = models.ManyToManyField(Course, blank=True) def get_courses_items(self): return self.courses.all() def __str__(self): return self.owner.username Views: from rest_framework.generics import CreateAPIView from profiles.models import Profile from .serializers import ProfileSerializer class ProfileCreateView(CreateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer -
Binding to Active Directory using django-auth-ldap
I'm trying to create user login authentication in my django app via Active Directory using django-auth-ldap. The problem is that I cannot bind to the AD using username (which is sAMAccountName LDAP equivalent). Part of my settings.py below: import ldap from django_auth_ldap.config import LDAPSearch AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', ] AUTH_LDAP_START_TLS = False AUTH_LDAP_ALWAYS_UPDATE_USER = False AUTH_LDAP_SERVER_URI = 'ldap://ip_address:389' AUTH_LDAP_BIND_DN = '' AUTH_LDAP_BIND_PASSWORD = '' AUTH_LDAP_USER_SEARCH = LDAPSearch('DC=example,DC=com', ldap.SCOPE_SUBTREE, '(sAMAccountName=%(user)s)') AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0, } Console log: ERROR search_s('DC=example,DC=com', 2, '(sAMAccountName=user)') raised OPERATIONS_ERROR({'desc': 'Operations error', 'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece'}) DEBUG search_s('DC=example,DC=com', 2, '(sAMAccountName=%(user)s)') returned 0 objects: DEBUG Authentication failed for user: failed to map the username to a DN. Any idea why this is not working? -
Gunicorn3 not starting with systemd
My systemd gunicorn3 configuration looks like this in /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn daemon for Django Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/betadmin/current ExecStart=/usr/bin/gunicorn --name=betadmin --pythonpath=/home/django/betadmin/current --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py betadmin.wsgi:application Restart=always SyslogIdentifier=gunicorn User=django Group=django [Install] WantedBy=multi-user.target My Django installation is located in: /home/django/betadmin/current I have added aliases for pip3 and gunicorn3 in ~/.bash_aliases alias python=python3 alias pip=pip3 alias gunicorn=gunicorn3 My nginx site configuration is located here: /etc/nginx/sites-enabled/django upstream app_server { server unix:/home/django/gunicorn.socket fail_timeout=0; } server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; server_name _; keepalive_timeout 5; # Your Django project's media files - amend as required location /media { alias /home/django/betadmin/current/betadmin/media; } # your Django project's static files - amend as required location /static { alias /home/django/betadmin/current/betadmin/static; } # Proxy the static assests for the Django Admin panel location /static/admin { alias /usr/lib/python3/dist-packages/django/contrib/admin/static/admin/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://app_server; } } If I run sudo service gunicorn status ● gunicorn.service - Gunicorn daemon for Django Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2018-11-07 15:27:18 UTC; 16min ago Process: 2783 ExecStart=/usr/bin/gunicorn --name=betadmin --pythonpath=/home/django/betadmin/current --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py betadmin.wsgi:application (code=exited, status=1/FAILURE) Main … -
Django rest-auth Token authentication
I'm trying to use axios to get information from the /rest-auth/user/ page. This is my function: export const fetchUser = () => { const token = localStorage.getItem('token'); return dispatch => { dispatch(fetchUserPending()); axios.get('http://localhost:8000/api/v1/rest-auth/user/', {headers: { 'authorization': `Bearer ${token}`}}) .then(response => { const user = response.data; dispatch(fetchUserFulfilled(user)); }) .catch(err => { dispatch(fetchUserRejected(err)); }) } } It uses the django token I get from login, that is stored in localStorage. I get error status 403, authentication credentials were not provided. I've tried editing my django settings.py file to include REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } and then I get error code 401 unauthorized. Can anyone direct me in the right direction? Thanks! -
How to run Django 2.0 on 1-click app Digital Ocean?
Does anyone know if it's possible to run django 2.0 on Digital Ocean's 1-click django application? My project is in 2.0 and the 1-click runs 1.11. I've tried sudo apt install python3-pip -y pip3 install django ln -s /usr/bin/pip3 /usr/bin/p Now I get a 502 bad gateway error on my page. I know the option of setting the server up from scratch (which I will end up doing probably) I'm just wondering if anyone has successfully run 2.0+? -
How to change root URL configuration in order to use a namespace for the user URLs
Site-Wide URL: from user import urls as user_urls app_name='user' urlpatterns = [ re_path(r'^user/',include(user_urls)), ] Since the admin app ,also defines URL patterns named login and logout in django/contrib/admin/sites.py .I need Django pointing to user app..Its still pointing towards registration/login.html(i.e admin app). I tried namespacing but its been removed in Django 2.0.. user/urls.py : urlpatterns = [ path(r'',RedirectView.as_view()), re_path(r'^login/$',auth_views.LoginView.as_view(), {'template_name':'user/login.html'}, name='login'), re_path(r'^logout/$',auth_views.LogoutView.as_view(), {'template_name':'user/logged_out.html', 'extra_context':{'form':AuthenticationForm }},name='logout'), ] -
'AnonymousUser' object has no attribute '_meta' login error with a user
Here is my code : from django.contrib.auth import login as login_auth, authenticate def index(request): # Render the HTML template index.html with the data in the context variable loginForm = None if not request.user.is_authenticated : loginForm = LoginForm() if request.method == 'POST': # create a form instance and populate it with data from the request: form = LoginForm(request.POST) # check whether it's valid: 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_auth(request, user) return render( request, 'index.html', context={'loginForm':loginForm} ) else : return render( request, 'dashboard.html', ) I've seen other post on stack overflow woth this error, but i'am using vanilla django 2.2 and no jwt. So when i use my form i have a : 'AnonymousUser' object has no attribute '_meta' from : login_auth(request, user) So now i'am scratching my head. normally you get the user then you authentificate him no ? regards -
Django access foreignkey fields in a form
I'm working on a Virtual Library app (using Django v2.1, python v3.5) where anyone should be able to access the book catalog and request a loan by simply leaving some personal info like name, surname, email, etc. These are some of the models in models.py: class Profile(models.Model): name = models.CharField(max_length=50) # more fields like surname, email, phone... class TrackBook(models.Model): # Somefields to keep track of date and status... borrower = models.ForeignKey(Profile, on_delete=models.SET_NULL, null=True, blank=True) class Book(TrackBook): #info about title, author, etc. What I'm trying to do is to update a Book instance's borrower with a Profile instance that I created in the Form. 1)I've tried directly accessing borrower fields in a BookForm, but it didn't work. # views.py class BookRequestView(UpdateView): template_name = 'core/book_request.html' model = Book form_class = BookProfileForm #forms.py class BookProfileForm(forms.ModelForm): class Meta: model = Book fields = ['borrower'] # book_request.html <form class="" action="" method="post"> {% csrf_token %} <div class="row"> {{ form.borrower.name }} <! -- and all other fields --> </div> {% for field in form.hidden_fields %} {{ field }} {% endfor %} <button type="submit" class="btn btn-block btn-success btn-flat">Save</button> </form> 2) I've tried creating an inlineformset_factory() of Profile model but it doesn't work since what I want to achieve … -
Django Migrations - Dependencies reference nonexistent parent node
Unlike normal migrations, this is a different one. I have deleted the entire project and database. Used a basic Django project without any app in it. The error always points to my older migrations. To ensure I used default SQL lite. Steps lead to this error: I tried adding columns to the Group Model using add_to_class and contribute_to_class methods in the process of doing this I lost track of the migration. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001E7701610D0> Traceback (most recent call last): File "E:\Python_365\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "E:\Python_365\lib\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "E:\Python_365\lib\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "E:\Python_365\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "E:\Python_365\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "E:\Python_365\lib\site-packages\django\db\migrations\loader.py", line 267, in build_graph raise exc File "E:\Python_365\lib\site-packages\django\db\migrations\loader.py", line 241, in build_graph self.graph.validate_consistency() File "E:\Python_365\lib\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\Python_365\lib\site-packages\django\db\migrations\graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "E:\Python_365\lib\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0022_group_openid dependencies reference nonexistent parent node ('Task', '0003_auto_20181107_1811') I am not sure why Django is still referring to my … -
ModelForm extra field is missing
I have the following structure: class ModelA(models.Model): # ... class ModelB(models.Model): modela = models.ForeignKey(ModelA) # ... And a form for ModelA: ModelAForm. By default, a field for modelb_set does not exist because it is a reverse relationship, so I tried adding it to the form: class ModelAForm(forms.ModelForm): modelb_set = forms.SelectMultiple() class Meta: model = ModelA exclude = [] def __init___(self, *args, **kwargs): # ... self.fields['modelb_set'] # this throws KeyError Why is a KeyError thrown when trying to access that field, when I explicitly declared it in the form? -
Django detailed url
I'm trying to make seperated url for every entry for my blog app. But every time i try to go for example: localhost:8000/blog/3 it sends me response for regular localhost:8000/blog I tried to google it, and... i have no idea what i'm doing wrong. My standard url.py: from django.conf.urls import url, include from django.contrib import admin ... import blog.views urlpatterns = [ url(r'^admin/', admin.site.urls), url('home/', jobs.views.home, name='home'), url(r'^blog/', include('blog.urls')), ] urls.py (in "blog app" folder): from django.conf.urls import url, include from . import views urlpatterns = [ url('<int:blog_id>/', views.detail, name="detail"), url('', views.allblogs, name="allblogs"), ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Article def allblogs(request): #Mega object from database blog = Article.objects return render(request, "blog/allblogs.html", {'blog':blog}) def detail(request, blog_id): blog = get_object_or_404(Article, pk=blog_id) return render(request, "blog/detail.html", {'blog':blog}) In models.py don't know why i choosed "Article" instead of "Blog", but i don't think that matters here... Any ideas... ? -
Django: forms.ChoiceField, overriding forms __init__
I am trying to implement a forms.ChoiceField() with values from a view. I already can do it if I declare the choices in the forms.py, but that's not what I need. views.py: def add_crime(request): values = [('1','um'),('2','dois'),('3','tres')] if request.method == 'POST': form = AddCrimeForm(request.POST, values) if form.is_valid(): # do stuff return redirect('show_crime') else: form = AddCrimeForm(request.GET) return render(request, 'add_crime.html', {'form': form}) forms.py: class AddCrimeForm(forms.Form): tests = forms.ChoiceField() def __init__(self, testList, args, **kwargs): self.testList = testList super(AddCrimeForm,self).__init__(*args, **kwargs) # testList not in args! self.fields['tests'].widget = forms.CheckboxSelectMultiple() self.fields['tests'].choices = self.testList Error: AttributeError: 'tuple' object has no attribute 'get' From the feedback, do I have to implement another __init__ with one argument in forms.py? That's what I would try in Java. My final goal is to implement two ChoiceField and the second one would depend from the first one. Is there a better way? -
How to extend the operators supported by dynamic rest?
I have this little Frankenstein: from dynamic_rest.viewsets import DynamicModelViewSet class QuarterFilter(django_filters.Filter): def get_quarter_range(self, quarter): if quarter == 1: return [1, 3] elif quarter == 2: return [4, 6] elif quarter == 3: return [7, 9] elif quarter == 4: return [10, 12] else: raise ValidationError("quarter value must be range from 1-4") def filter(self, qs, value): try: year, quarter = value.split("Q") year, quarter = int(year), int(quarter) qs = qs.filter(date__year=year) qs = qs.filter(date__month__range=self.get_quarter_range(quarter)) except: pass return qs class OperationViewSet(DynamicModelViewSet): queryset = Operation.objects.all() serializer_class = OperationSerializer permission_classes = (AllowAny,) def get_queryset(self, *args, **kwargs): # TODO: how to implement a .quarter operator at the Dynamic REST level? queryset = Operation.objects.all() quarter = self.request.query_params.pop('filter{date.quarter}') if quarter: queryset = QuarterFilter().filter(queryset, quarter[0]) return queryset Which is a mixture of Dynamic Rest and Django Filter. It works, but I do not like it, specially because if does not allow any flexibility in choosing the field to which the filter applies to: currently it is hardcoded to date.quarter. I do not want to extend this concept by reinventing the wheel. Instead, I would like to extend the powerful mechanism implemented by dynamic rest. Dynamic rest supports a bunch of operators. What would be the accepted way of extending the …