Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django validation: Use field label insted of field name in error
Is it possible to use label name instead of field name in django form validation. For example in a invalid form one might get errors like these: "passenger_email":["This field is required."] How can I get "Passenger email":["This field is required."] -
Delete Model object in django Using jquery Ajax
Having a hard time deleting an object using jquery/ajax. I have implemented a table that has rows containing a list of objects from Appointment model. There is a delete button in each row. Template for objects' table is : <table class="table table-striped table-bordered table-list"> <thead> <tr> <th><em class="fa fa-cog"></em></th> <th class="hidden-xs">ID</th> <th>Patient Name</th> <th>Day</th> <th>Time</th> <th>Location</th> </tr> </thead> <tbody> {% for appointment in appointments %} <tr> <td align="center"> <button class="delete_button" id="{{ appointment.id }}"><em class="fa fa-trash"></em></button> </td> <td>1</td> <td class="hidden" id="appointment_id">{{ appointment.id }}</td> <td>{{ appointment.patient }}</td> <td>{{ appointment.day }}</td> <td>{{ appointment.time }}</td> <td>{% if appointment.clinic %} {{ appointment.clinic }} {% endif %} {% if appointment.hospital %} {{ appointment.hospital }} {% endif %}</td> </tr> {% endfor %} </tbody> </table> Javscript is as below : $(document).ready(function(){ $(".delete_button").click(function() { var id = $(this).attr('id'); $.ajax({ url: "{% url 'deleteappointment' %}", data: { 'id' : id }, beforeSend: function(xhr) { xhr.setRequestHeader("X-CSRFToken", {% csrf_token %} ); }, success: function(response){ } }); }); }); Nothing is happening when I click on the delete button. What am I doing wrong here ? -
How to display error messages from form with ajax using python django
I'm trying to display the error messages that I provided on my forms, but it only display the id name instead of error message. Here's my code Form.py class SecurityCode(forms.Form): sCode = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(id="scode", name="scode", required=True, size=25, placeholder=" Security Code")), error_messages={ 'invalid': "This value must contain only letters, numbers and underscores." }) Views.py def security(request): if request.method == 'POST': securityField = SecurityCode(request.POST) if taxpayerField.is_valid(): return HttpResponse("success") else: return HttpResponse(taxpayerField.errors) Note: I'm trying to get the error message in this views not on my html because I'm trying to alert that on my javascript. Also this is just my sample code not the original one. -
UnboundLocalError : local variable 'toto' referenced before assignment
I got an error with Django and I didn't find a solution : UnboundLocalError at /Identity/recherche local variable 'toto' referenced before assignment This is the part of my script : def Consultation(request) : identity = Identity.objects.all().order_by("-id")[:10] #Les 10 dernières fiches créées identity_France = Identity.objects.filter(country='64').order_by("-id")[:10] #Les 10 dernières fiches où la personne habite en France query = request.GET.get('q') if query : toto = Identity.objects.filter(lastname__icontains=query) context = { "identity" : identity, "identity_France" : identity_France, "query" : query, "toto" : toto, } return render(request, 'resume.html', context) Thank you so much :) -
Reviewboard tests.py how to run it
I have a fresh install of Reviewboard 1.6.3 which is running through python and django. The folder structure is basically as follows: /reviewboard -manage .py -settings .py -settings_local .py -/diffviewer --tests .py In that case how would I run tests .py because it seems that it is looking for so-called DJANGO_SETTINGS_MODULE. I'm not sure how to really use that environment variable. Can you help me how will this work -
Running a Python function from Ansible script
I have a Django project hosted on a remote server. This contains a file called tmp_file.py. There's a function called fetch_data() inside that file. Usually I follow the below approach. # Inside Django Project $ python manage.py shell [Shell] from tmp_file import feth_data [Shell] fetch_data() Also the file doesn't contain __name__ section. So can't run as a stand alone script. What's the best way to perform this task using Ansible. I couldn't find anything useful from Ansible docs. -
maintain same authentication in angular as well as in django
What i am trying to achieve here, 1) I have my angular project which is accessing api's created in django-rest framework. authentication and everything works fine. 2) I have same django-rest project with some templates. My concern here is that i don't want user to login two different times for angular project as well as for django base project as both accessing the same database. Consider an example A --> is angular project B --> Django project with rest-api's A's url is http:localhost:4200/#/ B's url is http:localhost:8000/dashboard/ A is accessing the B's api. Now when user log's in to A, i want same user to get logged in to B i.e. When i hit http:localhost:8000/dashboard/ the user should be already logged in to django and vice versa. Any help will be appreciated. -
What can i do on django-oscar to ensure that my catalogue displays products on the frontend?
I'm currently setting up a store on oscar and the challenge I'm facing has to do with products not showing up in the frontend catalogue. The products are visible from the dashboard at the backend and when I click on each product to see how it would look on the frontend, that usually works. But when I visit the frontend I always see "No Products Found". Is there something I'm missing? -
Change Django-Mezzanine-Cartridge From - email after placing order
In Mezzanine I am using cartridge and I want to change the From email when the shipping details are mailed to the user. The default one is do_not_reply@WINCTRL-4UBSUNC. Where can i change this? Also I want to mail the admin about the order details where can I do this or how do I use post_save() on Order model? -
Realtime mobile app with Django and Ionic
Is it possible to develop a realtime mobile app with Django and Ionic? The project contains a web application and a mobile application run with Django backend. There are different ways to make the web application realtime, as I know Ionic communicates with through with http calls, how can I make the mobile application realtime too? If it is possible how is the best way to structure such a project? The web application should have different functions then the mobile application. -
Detect first time user has authenticated using Django Rest Framework
I'm using DRF to allow users of my mobile app to authenticate to my web application. I want to create a model instance associated with this user the first time a user "logs in" using the client. I'm using token-based authentication in DRF, and for my /api/authenticate/ endpoint I'm pointing at url(r'^authenticate/', restviews.obtain_auth_token), It seems like the best way to handle this is to override ObtainAuthToken(APIView), by adding this class to my api/views.py. This class looks like this: class ObtainAuthTokenCustomized(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) obtain_auth_token = ObtainAuthTokenCustomized.as_view() It looks like I would want to insert a test prior to get_or_create for whether a token has been created previously for this user. And if so, perform the model instance creation I have planned. Is this the best way to handle this? -
Get new tag list M2M Field
One object have some tags, While update request data have list of tags. We have separate permission for add & remove tags. For example, A question have two tags `important`, `python`. Add new tag means, the request data is [`important`, `python`, `django`] Remove tag means, the request data is [`python`, `django`] Add & Remove means, the request data is [`python`, `drf`]. Remove Permission Check is, delete_tags = question.tags.exclude(name__in=[`python`, `drf`]) delete_tags is [`django`] How to get add_tags list using query set ?? is it possible to do like delete_tags ?? Advance Thanks -
can't change model instance
views.py def patient_num(request): if request.method == 'POST': form = EditToBeSaveForm(request) if form.is_valid(): num = form.cleaned_data['病人编号'] new_p = Patient.objects.filter(p_number=num)[0] new_p.p_name = form.cleaned_data['姓名'] new_p.p_sex = form.cleaned_data['性别'] new_p.p_age = form.cleaned_data['年龄'] new_p.p_tel_number = form.cleaned_data['电话号码'] new_p.save() return render(request, 'polls/patient_edit.html') else: form = EditToBeSaveForm() return render(request, 'polls/patient_num.html', {'form': form}) models.py class Patient(models.Model): sex_choice = ( ('男', '男'), ('女', '女'), ) p_name = models.CharField(max_length=100, default='template') p_age = models.IntegerField(default=0) p_number = models.IntegerField(default=0) p_tel_number = models.IntegerField(default=0) p_sex = models.CharField(choices=sex_choice, max_length=2, default='男') forms.py class EditForm(forms.Form): 病人编号 = forms.IntegerField() class EditToBeSaveForm(forms.Form): sex_choice = ( ('male', '男'), ('female', '女'), ) 病人编号 = forms.IntegerField(label='你要修改的病人编号') 姓名 = forms.CharField(max_length=100) 年龄 = forms.IntegerField() 电话号码 = forms.IntegerField() 性别 = forms.ChoiceField(choices=sex_choice) after i populate the form and submit it, the view didn't update the database instance,why? i can do it one by one in shell as below. -
How to get ID from another model in django?
I have 2 models that it must be input to database in same time by submit button in my template. this is my first model class DataPribadiSiswa(models.Model): SiswaID = models.AutoField(primary_key=True) WaliKelasID=models.CharField(max_length=5,blank=True,null=True) SiswaNIS = models.IntegerField(null=True, blank=True) second model class RiwayatSekolah(models.Model): SekolahID=models.AutoField(primary_key=True) SiswaID_FK=models.CharField(max_length=10,blank=True,null=True) and this is my view.py def tambah_siswa(request): form = datasiswa(request.POST) form2 = riwayatsekolah(request.POST) if request.method == 'POST': if form.is_valid() and form2.is_valid(): form.save() form2.save() return redirect('index') else: form = datasiswa() form2 = riwayatsekolah() return render(request, 'siswa/tambah_siswa.html', {'form': form, 'form2': form2}) how to insert SiswaID fromDataPribadiSiswa to SiswaID_FK in RiwayatSekolah at same time? -
How to validate a foreign key field for Django
For my example, I have a members model and its primary key is a foreign key in another model. How can I check that the member exists using validation. Also its on a form, so I would like error message to appear. How I have the form right now, is with a drop down of all the members. But due to this being a school project, and not something just for playing around, I need to due back end testing which would fail in a test case if the member did not exist. -
filter queryset returned from ManyRelatedManager
I have a queryset of model "A" that I'm attempting to do some values/annotate computation on. Model "A" has a ManyToMany relationship with model B. From model "A", I would like to be able to access a filtered subset of "B" models based on a field in "B". How would I change my model "A" to support this sort of pattern? Dummy example: class Publication(models.Model): is_digital = models.BooleanField(default=True) readership = models.IntegerField() class Article(models.Model): language = models.CharField() published_in = models.ManyToManyField(Publication) # returns a queryset of {publications: total readership} for the articles $ articles = Articles.objects.filter(language='en') $ articles.values('published_in').annotate(Sum('readership')) I would like to return a query of publications and total readership for the articles only for publications that are digital. -
How to unittest Django admin inline forms
How do you use Django's unittesting Client to fill in inline forms? In my test, I've tried: response = client.get('/admin/myapp/prospect/add/') initial = response.context['adminform'].form.initial initial['name'] = 'Jon Doe' response = client.post('/admin/myapp/prospect/add/', initial, follow=True) but this throws a "ManagementForm data is missing" error because my ModelAdmin has some inline forms, and the form.initial object doesn't appear to include the boilerplate fields for these inlines, like *-INITIAL_FORMS, *-MAX_NUM_FORMS, and *-TOTAL_FORMS. Is there a way around this, or does Django's unittest framework not support testing inline forms? -
Accessing files from mounted file system vs local files on web server (production vs dev)
I have a Django web application that requires accessing audio wav files. I have a file server containing the wav files which is mounted onto my web server which stores my web application files. I then downloaded the files onto my local filesystem so my web application can access it when I'm developing it locally. My question is about how to access those files from my web application on production versus local. I'm thinking in my Javascript I'd need to have two different configurations that check if my web application is in production or development. If in production, I'd use the path to the mounted file server, and if in development, I'd use the path to the local filesystem on my computer. Does Django or Javascript provide a way of doing that somehow? And is this the right way of approaching getting files from the web application? The other option I can think of just uploading the wav files along with my web application to the web server so I can access it locally on production and not have to access it from the mounted file system. Would that be better or would the first approach be better? -
Using setattr() to update an object instance
I have a model class which has an attribute that refers to django DB objects. I would like to change this attribute using a single view with setattr() which I use to make changes to any attributes for this object. The problem is, I can't seem to pass an object instance through the stack. I'm not sure if I can even use setattr() for this. Actually I'm not even sure if the problem is with my attempted use of setattr() or something else - please let me know! Error on POST attempt: ValueError at /dollhouseupdate/1 Cannot assign "u'Citadel'": "Dollhouse.dh_background" must be a "Background" instance. Model: class Dollhouse(models.Model): dollhouse_name = models.CharField(max_length=100) user = models.ForeignKey(User) dh_background = models.ForeignKey(Background) def __str__(self): return self.dollhouse_name Template: <select id="background-select"> <option value="null">Change Background</option> {% for background in background_objects %} <option value="{{ background }}">{{ background.bg_name }} </option> {% endfor %} </select> View: def dollhouseupdate(request, dollhouseid): if request.method == 'POST': workingdollhouse = Dollhouse.objects.get(id=dollhouseid) if request.POST.get('erase') == "true": workingdollhouse.delete() return HttpResponse("Dollhouse deleted!") else: data = (request.POST).dict() for key, value in data.items(): setattr(workingdollhouse, key, value) workingdollhouse.save() return HttpResponse("Dollhouse {} saved!".format(workingdollhouse.dollhouse_name)) Javascript: //change dollhouse background $("#background-select").change(function() { if($("#background-select").val() != null) { var dollhouseid = workingDollhouse; var dh_background = $("#background-select").val() console.log("changing background to … -
Django `SECRET_KEY` settings
I have some "easy" questions about the SECRET_KEY settings in django: What is its minimum, maximum and recommended length? Can I leave it blank? What if I use a very long SECRET_KEY, will some of it be "wasted"? What are the allowed characters on it? Does it allow non-printable characters (including but not limited to whitespaces)? When should I change it? I know that when I change it, all existing cookies/sessions, signature etc. will be invalidated. Is it OK to retrieve it from database (or other sources) rather than directly written in settings.py? -
Django loaddata error __init__() takes exactly 3 arguments (1 given)
I'm having trouble trying to initialize some data. When I run manage.py loaddata --verbosity=1 initial.json With this as my initial.json file: [ { "model": "listen.Playlist", "pk": 1, "fields": { "message": "Hello There!", "url": "pl8675309", "background": "citylights.png" } } ] And the output I get is: File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Library/Python/2.7/site-packages/django/core/management/commands/loaddata.py", line 64, in handle self.loaddata(fixture_labels) File "/Library/Python/2.7/site-packages/django/core/management/commands/loaddata.py", line 104, in loaddata self.load_label(fixture_label) File "/Library/Python/2.7/site-packages/django/core/management/commands/loaddata.py", line 161, in load_label for obj in objects: File "/Library/Python/2.7/site-packages/django/core/serializers/json.py", line 86, in Deserializer six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) File "/Library/Python/2.7/site-packages/django/core/serializers/json.py", line 80, in Deserializer for obj in PythonDeserializer(objects, **options): File "/Library/Python/2.7/site-packages/django/core/serializers/python.py", line 183, in Deserializer obj = base.build_instance(Model, data, db) File "/Library/Python/2.7/site-packages/django/core/serializers/base.py", line 218, in build_instance obj = Model(**data) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 556, in __init__ super(Model, self).__init__() django.core.serializers.base.DeserializationError: Problem installing fixture 'initial.json': __init__() takes exactly 3 arguments (1 given) -
Using a callable/dynamic for queryset in ModelChoiceField?
I have a form that is used to make a formset, like so: class PreferenceForm(forms.Form): preference = forms.ModelChoiceField(SchoolClass.objects.currently_enrolling()) The method currently_enrolling() queryset returns a queryset which ModelChoiceField takes its choices from. This works until the data this queryset returns (i.e. the classes that are currently enrolling) changes - the form does not show the new classes that are now enrolling. Restarting django fixes the problem, but this is not an optimal solution. I presume this means this code is run once on startup, and not subsequently. Is there a way to make this work for a changing queryset? -
Can not GET JSON data with API created by Django
I want to get the json data using the API created by Django and show it in the table view. There is nothing in value in the following program. What should I do? Json data: { "books": [ { "id": 1, "name": "Django", "publisher": "GeekLab Nagano", "page": 10, "impressions": [] }]} Code: var tableTitle = [String]() var tableDetail = [String]() let url:String = "http://127.0.0.1:8000/api/v1/" func loadData() { Alamofire.request(url).responseJSON { response in guard let value = response.result.value else { return } let json = JSON(value) let books = json["books"] for item in books.arrayValue { self.tableTitle.append(item["name"].stringValue) self.tableDetail.append(item["publisher"].stringValue) } print(self.tableTitle) print(self.tableDetail) self.tableView.reloadData() } } -
How to get Django JsonResponse use null as key instead of string "null"
I am using Ajax in a Django app where it calls a View to get a list of items associated with an Account model. In the View, I return a dictionary where the account_id is the key, but some items don't have an Account associated with it, so I want to use None as the key. However, in the Ajax response, that key ends up as the string "null" instead of the value null. Here is the view: class ItemsFromAccountView(generic.View): def get(self, request, *args, **kwargs): json_data = {} items = models.Item.objects.values() for item in items: account_id = item['account_id'] if account_id not in json_data: if account_id is None: json_data[None] = { #Hoping to use null as key 'account_object' : None, 'items' : [] } # other stuff return JsonResponse(json_data) And the Javascript in the front-end: $.ajax({ url: "{% url 'ItemsFromAccountView' %}", method: 'GET', success: function(data) { for(var account_id in data) { if (account_id === null ) { //"null" is key instead of null // Do something } } } }); The Ajax response ends up being { "null" : { "account_object" : null, "items" : [] }, "1" : { ... } } I see the "account_object" value is null properly, … -
Test Django Forms submitted through Ajax view
I I'm trying to test a view that is used by Ajax. While with the server (manual testing) everything works, when I ran my unit test an error I can't explain appears. If you take a look at the following lines, where I present my code the most simplified as possible, you will see that although I add a variable to the json dict named something (just as I do in ajax) the field appears as missing in the form. My Test (tests.py): def test_edit_profile_user(self): self.user = User.objects.create_user( username='user', email='test@awesome.org', password='top_secret') self.client.login(username=self.user.username, password='top_secret') data = {'something': 'data'} response = self.client.post(reverse('edit_something'), json.dumps(data), content_type='application/json', HTTP_X_REQUESTED_WITH='XMLHttpRequest') print(response.content) self.assertEqual(response.status_code, 200) While my Ajax view works, my test gives the following traceback: b'{"something": ["This field is mandatory."]}' Failure Traceback (most recent call last): File "***\tests.py", line 81, in *** self.assertEqual(response.status_code, 200) AssertionError: 400 != 200 What am I doing wrong in the test? The rest of the code: My view (views.py): def edit_something(request): if request.method == 'POST': form = CustomForm(request.POST) if form.is_valid(): form.save() response_code = 200 response_data = {'something':'updated') else: response_code = 400 response_data = form.errors return JsonResponse( response_data, status=response_code, ) My JS (something.js): $.ajax({ url : form_endpoint, // the endpoint type : "POST", // …