Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save multiple objects with a unique attribute using Django formset
TL;DR: How do you save/validate multiple objects with a unique attribute using a formset? Let's say I have a Machine which has multiple Settings (see models below). These settings should have a unique ordering within the machine. This can be accomplished by defining a unique_together attribute in the Meta class of the Setting model: unique_together = (('order', 'machine'), ) However, I'm using an inline formset to update all the Settings of a Machine. Assume I have the following info in my formset: Setting 1: machine=1; order=1 Setting 2: machine=1; order=2 If I were to switch the order on the two Settings: Setting 1: machine=1; order=2 Setting 2: machine=1; order=1 and save the form using the following piece of code: self.object = machine_form.save() settings = setting_formset.save(commit=False) for setting in settings: setting.machine = self.object setting.save() Then I get a Unique Constraint Error since I'm trying to save Setting 1 with order=2, but Setting 2 still has that order. I can't seem to find a clean solution for this problem. I would like to keep the unique_together constraint to ensure the correctness of my data. I know how to solve this in the frontend using Javascript, but I want a check in my … -
Django-admin forgot password
login.html {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} <div class="password-reset-link"> <a href="{{ password_reset_url }}">{% trans 'Forgotten your password or username?' %}</a> </div> {% endif %} urls.py from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views app_name = 'Web' urlpatterns = [ url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), ] as you can see pasword_reset_url included but i'm not able to see this href in my login page how can i configure ? -
hvad translation error __str__ returns NoneType
I am trying to localize some of my models and adopted hvad. It works fine but not when in related models. I have the following two models: class Family(TranslatableModel): sciencename=models.CharField(max_length=50,verbose_name='Scientific Name',blank=True,null=True) translations=TranslatedFields( name=models.CharField(max_length=50, unique=True), note=models.TextField(null=True,blank=True) ) def __str__(self): return self.safe_translation_getter('name',) And child: class Child(TranslatableModel): sciencename=models.CharField(max_length=50,verbose_name='Scientific Name',blank=True,null=True) family=models.ForeignKey(Family,related_name="child_family") translations=TranslatedFields( name=models.CharField(max_length=50) ) def __str__(self): return 'Dude'#' , '.join([self.family.name,self.safe_translation_getter('name',)]) class Meta: #ordering=('family','name',) unique_together=(('name','language_code')) Now I want to access this from the admin page and have this in admin.py, which generates TypeError. Without languages, it was listing families so I can chose one when adding a child: class cHILDAdmin(TranslatableAdmin): # ... other admin stuff def get_fieldsets(self, request, obj=None): return ( (_('Common fields'), { 'fields': ('sciencename','family' ), }), (_('Translations'), { 'fields': ('name',), }), ) change_form_template = 'change_form.html' list_display = ('__str__','family','sciencename', ) def apply_select_related(self, qs): return qs.prefetch_related('family') def get_family(self, obj): return obj.family def get_name(self,obj): return obj.name get_name.short_description = _('Name') -
How does django rqworker notify the browser that job has been done?
I have to create a major feature of my system. Here are the spec Software Versions: python3.6.2 Django1.11 Requirements: 1. Upload an Excel file with the correct format. Correct sheetname, columns all are set. 2. Dispatch the data processing to child-process. 3. Notify whether the error occur or not and summarize the error all at once to the user. 4. If the error occur. Rollback all the transactions. Planning: 1. Upload File and validate sheetname, and column is not difficult. I had done this before 2. Dispatch with rqworker is very easy 3. Hard part is here 4. Deal with Rollback by using decorator @transaction.atomic Question: 1. How can I let child-process notify the browser that the assigned job has been done? -
Django i18n_patterns with non-standard language codes
I am trying to use django's i18n_patterns in my root URL config to do automatic switching of the page language based on the URL. From looking at the related LocaleMiddleware code code, it does indeed look like hitting the server with a language prefix in the URL it switches the language. The issue I am facing though is that the translations we have in our system all have a country specific code, i.e. en-us instead of en or fr-be instead of fr. For the URLs themselves however we require the short form to be used. Our current solution is to run our custom locale middleware, mapping the current short form language code to the long form language code for activating the translations. I would like to know however if there would be another way around this, such that we could use this standard django implementation. -
I wanna send type1 of select tag
I wanna send type1 of select tag to test.html. I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} <select name="type1" id=type6> {% for value1 in preprocessed1 %} <option value="{{forloop.counter1}}">{{ value1 }}</option> {% endfor %} </select> </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var key; var value; $('select[name="main"] option:selected').each(function(index, option) { key = $(option).text(); }); $('select[name="type"] option:selected').each(function(index, option) { value = $(option).text(); }); $('select[name="type1"] option:selected').each(function(index, option) { value1 = $(option).text(); console.log(value1); }); document.querySelector("input[type=submit]").onclick = e => { const test = window.open(`test_view?${key}=${value}`, "_blank"); } }); $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== … -
How can I get the data passed from the ajax in Django?
How can I get the data passed from the ajax in Django? In the js, I use ajax to pass the data: $.ajax({ type:'post', url:'/app_admin/myServerDetail/', data:JSON.stringify({'server_id':server_id}), // I want to pass the server_id to views.py dataType:'json', success:success_func }) In my views.py, I print the request.POST, and server_id: server_id = request.POST.get("server_id") print (server_id, request.POST) The result is bellow: (None, <QueryDict: {u'{"server_id":"f55dbe56-7fa8-4d13-8e1e-2dc67499b6ac"}': [u'']}>) So, how can I get the server_id in my views.py ? -
Form has been tampered with - django form validation
I have a formset that I am working with right now of a model form that has other forms included in the html template. I am submitting the form into the views.py file in order to process the form. It is saying that the form has been tampered with and I have no idea why it is saying that. I will include all of the related code below: error: ValidationError at /17/hello/update_expense_individual/ ['ManagementForm data is missing or has been tampered with'] here is the form template: {% extends "base.html" %} {% block content %} <h2>Add expense - {{ currentGroup.name }}</h2> {% if message %} <p>{{message}}</p> {% endif %} <form action="." method="POST"> {% csrf_token %} {% for f in form %} {% for expense in expenses %} {% if forloop.parentloop.counter == forloop.counter %} <p>{{ expense.user.username }}</p> {% endif %} {% endfor %} {{ f.as_p }} {% endfor %} <p> Tax: <input type="number" name="tax" value="0.00"> </p> <p> Tip: <input type="number" name="tip" value="0.00"> </p> <input type="submit" name="submit" value="submit"> </form> {% endblock %} here is the views.py that is processing the form: the error referenced the if form.is_valid() def updateExpenseIndividual(request, groupId, groupName): currentUser = loggedInUser(request) currentProfile = Profile.objects.get(user = currentUser) currentGroup = Group.objects.get(id = … -
Django - customize admin site's login with additional features
I'm trying to override the default login used in Django 1.10 when logging in to the admin site. I need to add the following features to my django-admin login: -> 2 factor authentication. -> dashboard can't be logged in more than 2 browser or duplicate within the same browser at the same time. ->Auto session expire after 15 minutes of inactivity. My question: how can i make this work ,best way to override default admin login? -
I cannot get javascript's value
I cannot get javascript's value.I wrote in index.html <body> <form method="post" action=""> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option value="{{forloop.counter}}">{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=type{{forloop.counter}}> {% for counter, value in values %} <option value="{{forloop.counter}}">{{ value }}</option> {% endfor %} </select> {% endfor %} </form> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { var thisType = "type" + $(this).val(); for(i=1; i<6; i++) { var thisId = "type" + i; if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> <form id="postform" action="http://localhost:8000/app/test_view" method="POST"> {% csrf_token %} <input type="submit" value="SEND"> </form> <script type="text/javascript"> $('[name=type]').change(function() { var key; var value; $('select[name="main"] option:selected').each(function(index, option) { var key = $(option).text(); console.log(key); //A }); $('select[name="type"] option:selected').each(function(index, option) { var value = $(option).text(); console.log(value); //A }); console.log(key); //B console.log(value); //B document.querySelector("input[type=submit]").onclick = e => { const test = window.open(`test_view?${key}=${value}`, "_blank"); } }); </script> </body> I wanna get i& value variables console.log(key); & console.log(value); with //B,but now undefined is shown.console.log(key); & console.log(value); with //A is shown ideal values I really cannot understand why I can not get these values in last console.log.How should I fix this? What should … -
AttributeError: 'Resume' object has no attribute 'prefetch_related'
I am trying to understand the use of prefetch_related and select_related for optimization. I learned somewhere in the blog that one of the where to use prefetch and select is, prefetch_related is used for reverse relation and select_related for the forward relation. In my case there is Resume model and Education Model. Education model has FK of resume with the related_name for reverse relation instead of writing additional _set when querying. I need to list all the education of an requested user with the requested user resume. I could do this without those optimization techniques as follow education_instance = Resume.objects.get(applicant=request.user).educations.all() When I tried to use the following instead, I get the error I stated in the title education_instance = Resume.objects.filter(applicant=request.user).prefetch_related('educations') Here is my model class Resume(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=False, null=False, help_text="Full Name") class Education(models.Model): resume = models.ForeignKey(Resume, related_name='educations') name = models.CharField(max_length=100, blank=False, null=False, help_text="Name of an institution") Can anyone make me clear on select_related and prefetch_related with simple layman terms ? I could not understand the issue I am getting -
Can't add a choice form field on custom usercreateform
I've been trying to create a custom signup form using an extended user model in django. One of the custom fields I've been trying to add is a user type which can only be either "Employee" or "Admin". My signUpForm class looks like this from .models import EMPLOYEE_TYPE_CHOICES class SignUpForm(UserCreationForm): usertype = forms.CharField( max_length=10, choices=EMPLOYEE_TYPE_CHOICES, ) userID = forms.CharField(label="User ID") class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'userID', 'usertype') EMPLOYEE_TYPE_CHOICES comes from my models.py which look like this EMPLOYEE_TYPE_CHOICES = ( ('admin', 'Admin'), ('employee', 'Employee'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ADMIN = 'Admin' EMPLOYEE = 'Employee' EMPLOYEE_TYPE_CHOICES = ( (ADMIN, 'Admin'), (EMPLOYEE, 'Employee'), ) usertype = models.CharField( max_length=10, choices=EMPLOYEE_TYPE_CHOICES, ) userID = models.CharField( max_length=10, ) When running the server, I receive the error TypeError: init() got an unexpected keyword argument 'choices' Is there a different method for adding the choices to my form field? -
Reverse for 'post_draft_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I'm working on DjangoGirls Django Extensions Tutorial and I'm hitting an error. The web app runs perfect locally, but isn't running on when pulled on pythonanywhere. I don't know what's wrong. Here is the error message: Environment: Request Method: GET Request URL: -- Django Version: 1.10 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/vivianphung/my-first-blog/blog/templates/blog/post_list.html, error at line 0 Reverse for 'post_draft_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 : {% extends 'blog/base.html' %} 2 : 3 : {% block content %} 4 : {% for post in posts %} 5 : <div class="post"> 6 : <div class="date"> 7 : {{ post.published_date }} 8 : </div> 9 : <h1><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h1> 10 : <p>{{ post.text|linebreaksbr }}</p> Traceback: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vivianphung/my-first-blog/blog/views.py" in post_list 11. return render(request, 'blog/post_list.html', {'posts': posts}) File "/usr/local/lib/python3.5/dist-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.5/dist-packages/django/template/loader.py" in render_to_string 68. return … -
How to do remote authentication in dpahne server
Currently I am using Django channels, so to run the web server I have used daphne and run worker. How please help me how to do remote authentication ? or any reverse proxy Please help -
How to construct csrfmiddlewaretoken from a given csrftoken using javascript?
I'm working how to login to a django site with postman. Using Charles I can see that a csrfmiddlewaretoken token is created somehow. Given csrftoken=JDmmXqnLK35WCLha1PVOhFWITaKZs9eeAWBfuqXUxZEt3yDHmNoOyzMyJUQF5aQd the csrfmiddlewaretoken sent was v3I6Io9H8OoZcp4ATyszhAepdQAEp617mmXZfoJQVKXwDcq7ewVzyu4f3AGk27D6 Can v3I6Io9H8OoZcp4ATyszhAepdQAEp617mmXZfoJQVKXwDcq7ewVzyu4f3AGk27D6 be constructed from JDmmXqnLK35WCLha1PVOhFWITaKZs9eeAWBfuqXUxZEt3yDHmNoOyzMyJUQF5aQd using javascript? -
how to make left join in django?
this is my first model class DipPegawai(models.Model): PegID = models.AutoField(primary_key=True) PegNamaLengkap = models.CharField(max_length=100, blank=True, null=True) PegUnitKerja = models.IntegerField(null=True,blank=True) and this is my second model class DipHonorKegiatanPeg(models.Model): KegID = models.AutoField(primary_key=True) PegID = models.ForeignKey(DipPegawai, blank=True,null=True) KegNama = models.Charfield(max_length=100,null=True,blank=True) i want to make left join with this model, something like this in mysql query SELECT PegNamaLengkap, KegNama_id FROM karyawan_dippegawai AS k LEFT JOIN honorkegiatanpeg_diphonorkegiatanpeg AS h ON k.PegID = h.PegID_id WHERE PegUnitKerja = 3 GROUP BY k.PegID how to make left join with django orm same like mysql query above? -
Django does not appear to be sending disabled fields with POST data
I have the following in my forms.py class RegistrationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.fields['amount_due'].widget.attrs['disabled'] = True This shows the field grayed out on the form. But from the Debug output, I see that the field is not being passed along with the POST data. Once I change it to 'readonly' from 'disabled', it works. What is the difference between readonly and disabled? -
Session auth_user_id not correct in django
In my views.py, in some view, i have uid = request.user.id this gives the id of the user that is logged in right now which i display on my template and is coming out to be correct. But the same id should also be sent to the session as auth_user_id which is according to sessions table /admin/sessions/ here is not getting displayed. No matter which user is logged in, it always shows {u'_auth_user_hash': u'ca7e738308ed261de83fe3c80c9a4657b37e8c81', u'_auth_user_id': u'2', u'_auth_user_backend': u'django.contrib.auth.backends.ModelBackend'}. uid=2 is the superuser(admin) in my table. I can't seem to figure out why this is happening? Any ideas? Also only one session is stored in the session table. -
django two model serializer in filter count
i want django serializer list in filtering count (Model <-> Foreign <-> Foreign(Count)) look my Model class Test(models.Model): item = CharField title = CharField class TestChild(models.Model): test = ForeignKey(Test) child_title = CharField class TestChildType(model.Model): child = ForeignKey(TestChild) type = BooleanField Test ChildType Model type field use filter(type=false).count() filter(type=true).count() testFalseCount in filtering false value testTrueCount in filtering true value and want serializer { item:'mouse', title:'goood Mouse' child:[ { child_title:'childGood' testFalseCount:4 testTrueCount:3 }, ... ] } -
Extract only used styles in html from style sheet
I am trying to increase the performance of my site by getting past render blocking css. Only one file seems to be a problem, and thats a minified bootstrap stylesheet I get from a CDN. I have tried multiple different approaches, but nothing has worked. I would like to have a copy of the Bootstrap CDN stylesheet in my project, and edit it so it only has the css I am currently using on my site. Is there a way to serialize your site, and remove any styles from a stylesheet that aren't being used ? I have read about several different takes on it, but most of them don't work in browsers besides Chrome, and break when hitting media queries in the stylesheet. -
Django CSRF verification failed even with {% csrf_token %}
POST requests to the Django view below result in (403) CSRF verification failed. I've confirmed that the hidden csrf token gets rendered in the page's source. I am also able to make POST requests without errors in other views. I'm unsure how to debug further. views.py: def email(request): if request.method == 'POST': email = request.POST['email'] fd = open('emaildb.csv','a') fd.write(email+',somefile\n') fd.close() return render(request, 'receipts/email.html', {'text':'Thanks, we''ll get back to you soon.'}) else: return render(request, 'receipts/email.html',) email.html: <form action="email" method="post" enctype="text/plain"> {% csrf_token %} E-mail:<br> <input type="text" name="email"> <input type="submit" value="Send"> </form> -
How to find User queryset matching self.request.user
How do we find User queryset matching self.request.user? logged_in_user = User.objects.filter(id=self.request.user.id) I wish there is much efficient way to doing this. (such as get_user_model(self.request.user)) ? Thanks! -
Django multiple schemas with foreign keys on each
So I have a database that has multiple schemas in django. One schema holds the api service end if you will, while the other schema has the cms and user information. How do I reference items from the other schema? postgres spits up a relation "" does not exist The trouble is that I need items on each schema for foreign keys. Any hacky solutions are welcome, as I believe I am dealing with a poorly put together project. -
docker is not running django server
I am new to docker and I'm trying to host a django project in docker. I tried to follow the tutorial from here but instead of postgresql, I use sqlite. I tried to run docker-compose up but docker was stuck at this: my Dockerfile: FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ and my docker-compose.yml: version: '3' services: db: image: spartakode/sqlite3:latest web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db Can anyone help me with this? Thank you -
Checkbox instead of boolean writting
models.py @python_2_unicode_compatible class Request(RequestProcess, FolderLinkMixin, TimeStampedModel): DENIED_AT_STATE_CHOICES = ( ('application', _('application')), ('documents', _('Documents')), ('validation', _('Validation')), ('evaluation', _('Evaluation')), ('signature', _('Signature')), ('deposit', _('Deposit')), ) folder_auto_create_childs = [] customer = models.ForeignKey('customers.CustomerProfile') request_type = models.CharField( _('Type'), max_length=15, choices=settings.LOANWOLF_REQUEST_TYPE_CHOICES) state = dxmodels.StateField(RequestWorkflow) validation = models.OneToOneField( 'core.ValidationData', blank=True, null=True) created_by = models.ForeignKey('users.User') rejection_reason = models.CharField( _('Reason of denial'), max_length=250, blank=True, null=True) expires_at = models.DateTimeField(_('Expires at'), blank=True, null=True) copied_from = models.OneToOneField( 'requests.Request', blank=True, null=True, default=None) delete = models.BooleanField(default=False) notes = GenericRelation(Note) contract = models.OneToOneField('contracts.Contract', on_delete=models.SET_NULL, blank=True, null=True, default=None) models.py class RequestsIndexView(StaffRestrictedMixin, FrontendListView): ... class Meta: ordering = ('-created', '-modified') sortable = ('created', 'state', 'modified') list_filter = ('state', 'request_type', created_at, modified_at, entered_state, entered_state_at, expired_at, expired_at_state, 'denied_at_state', rejected_or_denied_state, rejected_or_denied_state_at,) list_display = ( 'product', 'customer_menu', 'state', 'request_type', 'modified', 'created', 'delete_request' ) I put delete = models.BooleanField(default=False) in a my models.py file and I added delete in the Meta class from Request class view, and it showed me that picture instead of multiple checkboxes. How could I fix that so that it show me a checkbox? Please let me know if the question is unclear