Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Photologue XML Error
Does someone know why I get an XML-Error when I try to open a picture via Django-Photologue? Unfortunetly the Error message is in German: XML-Verarbeitungsfehler: nicht wohlgeformt Adresse: http://example.com/photologue/photo/name_of_photo/ Zeile Nr. 1, Spalte 1: before it said instead of something like <!Doctype html> so I assume it has something to do with a certain template of photologue. How can I fix this? -
Django: detecting users coming from google adwords using Google analytics Universal Tracking
By using the universal suite the utmz cookie is no longer exists. What is the best practices today to detect users coming through cpc campaign? I've searched online and couldn't find an answer. Thanks -
Add 'yesterday' field to Django admin date list filter
In my Django application, in the admin, for one of my models, I am allowing the option to filter by its 'create_date' field. Django by default gives me some options (Today, Past 7 Days, This Month, This Year). I want to simply add the option to choose 'Yesterday' as well. I looked at other Stack overflow questions regarding the same issue, but they were all looking for the ability to search by a date range, and I only want the one preloaded option. Is their a way in the admin class that configures this model to override some of their filter functionality ? Admin Class class User_LikeAdmin(admin.ModelAdmin): def fb_view_link(self, obj): if len(obj.user_facebook_link) > 2: return u"<a href='%s' target='_blank'>Facebook Page</a>" % obj.user_facebook_link else: return "" fb_view_link.short_description = '' fb_view_link.allow_tags = True list_display = ('vehicle', 'user', 'fb_view_link', 'dealer', 'create_date') list_filter = ('create_date', ('vehicle__dealer', custom_titled_filter('Dealer'))) raw_id_fields = ('vehicle', 'user') actions = [export_csv] def dealer(self, obj): return obj.vehicle.dealer -
Travis CI Django Build Fails
For the past few days, I have been working with Travis CI to automatically run my test cases. However, I cannot get it to work. Running my test cases locally works great. I use the command: python manage.py test myApp My travis.yml file is as follows... language: python os: linux python: - "3.5.2" services: postgresql install: - pip install -r requirements.txt script: - python manage.py test myApp I keep getting this error: django.db.utils.ProgrammingError: column myApp_userdocument.createdOn does not exist I have tried running migrate before running the script with no luck. Does anything look blatantly wrong with my travis file? -
Header image and Table Header missing when overflowing using [xhtml2pdf]
As the title says, I'm building a generic invoice pdf using xhtml2pdf and django. The image and table headers display correctly on the first page, but when the main table overflows, the image and table header aren't repeated. (The image in header is still drawn however as shown with -pdf-frame-border: 1;). Any advice appreciated <!-- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style type="text/css"> @page { size: a4 portrait; @frame header_frame { /* Static frame */ -pdf-frame-content: header_content; -pdf-frame-border: 1; left: 50pt; width: 512pt; top: 50pt; height: 60pt; } @frame header_sub {/*Static frame */ -pdf-frame-content: subheader_content; -pdf-frame-border: 1; left: 50pt; width: 512pt; top: 120pt; height: 50pt; } @frame col1_frame { /* Static frame 1 */ -pdf-frame-content: subheader_contentL; -pdf-frame-border: 1; left: 50pt; width: 250pt; top: 190pt; height: 120pt; } @frame col2_frame { /* Static frame 2 */ -pdf-frame-border: 1; -pdf-frame-content: subheader_contentR; left: 312pt; width: 250pt; top: 190pt; height: 120pt; } @frame main_content { /* Content frame */ -pdf-frame-border: 1; left: 50pt; width: 512pt; top: 330pt; height 220pt; } @frame second_table { /* Static frame 3 */ -pdf-frame-border: 1; -pdf-frame-content: second_table; left: 312pt; width: 250pt; top: 560pt; height: 70pt; } @frame sub_main { /* Content frame */ } @frame … -
Get value of label from Django form
I've created a CustomChoiceField from a queryset in Django with a custom label that passes the name, url, and aspect attributes of each object into the label. Here's the relevant code from forms.py: class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("%s<img src='%s' class='teams__filter__image' value='%s'/>" % (obj.name, obj.image.url, obj.aspect)) filter_pic = CustomChoiceField(required=False, label=mark_safe('Image Filter'), widget=forms.RadioSelect(attrs={'id':'filter-choice'}), queryset=FilterPic.objects.filter(activated=True), empty_label='None') It renders in HTML like so: <p class="teams__form__label">Image Filter</p> <p><label for="filter-choice_0"><input checked="checked" id="filter-choice_0" name="filter_pic" type="radio" value="" /> None</label></p> <p><label for="filter-choice_1"><input id="filter-choice_1" name="filter_pic" type="radio" value="2" /> WeHealth Orange<img src='/media/images/2017/08/28/orangefilter.png' class='teams__filter__image' value='0.7'/></label></p> <p><label for="filter-choice_2"><input id="filter-choice_2" name="filter_pic" type="radio" value="1" /> WeHealth Blue<img src='/media/images/2017/08/28/bluefilter.png' class='teams__filter__image' value='0.7'/></label></p> Everything looks great in HTML. The problem, is that I need the aspect attribute (current the value attribute in the label) in order to trigger a subsequent Javascript function (cropper.js aspect ratio). How can I obtain the aspect value in Javascript? -
Django API REST Framework : Generate a string based on CreateAPIView
I'm looking to use Django API REST Framework in my web application but I get an issue in my project. In my application, I fill a Django form in order to register a new person in my database. My model looks like : class Individu(models.Model): NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numero Identification physique', unique=True) Civilite = models.CharField(max_length=12,choices=CHOIX_TITRE, verbose_name='Civilité') NomJeuneFille = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True) Nom = models.CharField(max_length=30, verbose_name='Nom de famille') Prenom = models.CharField(max_length=30, verbose_name='Prénom(s)') Sexe = models.CharField(max_length=30, choices=CHOIX_SEXE, verbose_name='Sexe') Statut = models.CharField(max_length=30, choices=CHOIX_STATUT, verbose_name="Statut civil") DateNaissance = models.DateField(verbose_name='Date de naissance') VilleNaissance = models.CharField(max_length=30, verbose_name='Ville de naissance') PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') ... The field NumeroIdentification is Null but when I submit my form and I am redirected to the next template, I have this function : def Identity_Individu_Resume(request, id) : personne = get_object_or_404(Individu, pk=id) obj = Individu.objects.filter ( Prenom=personne.Prenom, Nom=personne.Nom, DateNaissance=personne.DateNaissance, VilleNaissance=personne.VilleNaissance ) if obj: sc_obj = obj[0] #check if multiple objects are there, means obj[1] #Man = 1 / Woman = 2 sex_number = [] if personne.Sexe == 'Masculin' : sex_number = 1 else : sex_number = 2 #Get birthday birthyear_temp = str(personne.DateNaissance.year) birthyear_temp2 = str(birthyear_temp.split(" ")) birthyear = birthyear_temp2[4] + birthyear_temp2[5] #Get birthmonth birthmonth_temp … -
Django Forms query
I have created a app using the following Model models.py class Vendor(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) def __str__(self): return self.name class Model(models.Model): name = models.CharField(max_length=100, unique=True, blank=False) def __str__(self): return self.name class Request(models.Model): job_reference = models.CharField(max_length=100, unique=True, blank=False) def __str__(self): return self.job_reference class Device(models.Model): Vendor = models.ForeignKey('Vendor') Model = models.ForeignKey('Model') device_id = models.CharField(max_length=255, unique=True, blank=True) is_encrypted = models.BooleanField() is_medical = models.BooleanField() request_job_reference = models.ForeignKey('Request') submitted = models.DateTimeField(default=timezone.now) When i go to the admin page I can add new devices which displayed each of the fields and the "Vendor" and "Model" allows me to either select an existing entry or has a plus icon to add a new entry (which is great) Django_Admin_form When i create a form for my app forms.py from django import forms from . models import Device class AddDevice(forms.ModelForm): class Meta: model = Device fields = ('Vendor', 'Model', 'device_id', 'is_encrypted', 'is_medical', 'submitted') The form on my webpage display ok however there is no option to insert a new entry to "Vendor" or "Model". Webpage Form I have looked on other posts on here as users have had the same issue and it's been suggested to use "ModelChoiceField" but unfortunately it still doesn't make any sense to … -
Incorporating "Like Post" feature
Hey so I am making a color scheme posting site where people can register and post color schemes they come up with. So far everything is working great, the only thing I have left to do is add a "Like Post" feature. I'm wondering what the best way to implement this would be. I have two ideas on how this could be done, the first is add an additional field to both the ColorSet (posts) and the User models (for the user model I would set up a new model with a OneToOne relationship to add onto the User model) which would record users that have each single post, and which posts each user has liked to keep track of everything. So this could look something like this: from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. class ColorSet(models.Model): user = models.ForeignKey(User,related_name='colorset') published_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=50,blank=False) color_one = models.CharField(max_length=6,blank=False,default='cccccc') color_two = models.CharField(max_length=6,blank=False,default='ffffff') color_three = models.CharField(max_length=6,blank=False,default='e5e5e5') color_four = models.CharField(max_length=6,blank=False,default='f0f0f0') color_five = models.CharField(max_length=6,blank=False,default='bababa') liked_by = models.IntegerField(blank=True) def publish(self): self.save() def get_absolute_url(self): return reverse('index') def __str__(self): return self.name user model: from django.db import models from django.contrib.auth.models … -
Django filter datetime elements
I use django 1.11.2 for my project. I had defined some models and all work right. Now I need to get some data from one of my models by date. For example all entry wich have month=8, month=9.... I have this, MyModel(....some fields...., created_date) and in models.py I have: .... created_date=models.DateTimeField() .... .... self.created_date=(datetime.now()) .... Created_date is a datetime field and its values are in this format: YYYY-MM-DD HH:MM:SS, for example 2017-08-31 14:25:58. So, I see this: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#month And this will be perfect for me, but don't work. From shell I write this: >>> from project.models import MyModel >>> from datetime import * >>> MyModel.objects.all() ---> Work ok, I get all entries >>> MyModel.objects.filter(created_date__month=7) <QuerySet []> In this case I get an empty Quertset. -
Sessions handle datetime like django wizard
I'm using sessions in a current django project and recently got a 'Object of type 'date' is not JSON serializable' error - due to the move_in_date field When saving a modelform of the below model to the session via: if form.is_valid(): request.session.update(form.cleaned_data) my model: class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) house_name_number = models.CharField(max_length=255, verbose_name="house name or number") street_name = models.CharField(max_length=255) town_city = models.CharField(max_length=255) county = models.CharField(max_length=255) postcode = models.CharField(max_length=8) same_address = models.BooleanField() move_in_date = models.DateField(null=True, blank=True) Reading through the django docs on sessions I'm not clear why sessions use a serializer? (I'm using the db to store the session) From my understanding isn't just the session ID going to the browser in a cookie and the session data is stored in the db? The data in the session can be accessed via the ORM like a normal model. However when I look at the database table there is just one field, session_data (apart from expiry date and session id). Looking at the docs seems to be signed (but not encrypted? - not sure of the difference). So I'm not clear where the serializer is being used? Additionally I was using django wizard before which stores intermediate data (such as the field … -
elasticsearch.exceptions.RequestError: Mapping definition for [name_complete] has unsupported parameters: [payloads : true]
I was working on a Django Project where I have 3 models. Student, University, Course. I set up the model, populated the database and trying to use Elastic Search for searching. So, I installed Elastic Search version 5.5.0. Here is the Meta class of my models.py. class Meta: es_index_name = 'django' es_type_name = 'student' es_mapping = { 'properties': { 'university': { 'type': 'object', 'properties': { 'name': {'type': 'string', 'index': 'not_analyzed'}, } }, 'first_name': {'type': 'string', 'index': 'not_analyzed'}, 'last_name': {'type': 'string', 'index': 'not_analyzed'}, 'age': {'type': 'short'}, 'year_in_school': {'type': 'string'}, 'name_complete': { 'type': 'completion', 'analyzer': 'simple', 'payloads': True, 'preserve_separators': True, 'preserve_position_increments': True, 'max_input_length': 50, }, "course_names": { "type": "string", "store": "yes", "index": "not_analyzed", }, } } def get_es_name_complete(self): return { "input": [self.first_name, self.last_name], "output": "%s %s" % (self.first_name, self.last_name), "payload": {"pk": self.pk}, } es_index_name, es_type_name, es_mapping are defined in the top portion of the file like this: import django.db.models.options as options options.DEFAULT_NAMES = options.DEFAULT_NAMES + ( 'es_index_name', 'es_type_name', 'es_mapping' ) To push all the data from the database to the index in bulk I have a command file named push-to-index.py. When I execute it by python manage.py push-to-index, it generates the following error: elasticsearch.exceptions.RequestError: TransportError(400, mapper_parsing_exception', Mapping definition for [name_complete] has unsupported … -
Django as.view how it works
I'm trying to understand how as.view(method) works, how is interacting with CBV and how the all mechanism is trigger in Django. I don't understand very well what the following line of code is doing: update_wrapper(view, cls, updated=()) update_wrapper(view, cls.dispatch, assigned=()) as.view() return the internal view function, but what happens with view and the relation with dispatch ? -
django-tenant-schemas relation "django_content_type" does not exist
I'm willing to use django-tenant-schemas for a SaaS project, so I followed the docs and tried to integrate it in my project but an error occured when I run ./manage.py migrate_schemas --shared. I googled it with no results I'm on ubuntu using python3, Django 1.11 and postgres 9.5.8 her's the Traceback [standard:public] === Running migrate for schema public [standard:public] Operations to perform: [standard:public] Apply all migrations: admin, auth, contenttypes, customers, sessions, sites [standard:public] Running migrations: [standard:public] No migrations to apply. Traceback (most recent call last): File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: ..... ..... ..... cursor.execute(sql, params) File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/db/backends/utils.py", line 80, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/media/user/B2F01DF5F01DC111/Code/Code/projects/test/test_env/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ -
How to get CSRF token from mobile apps when CSRF_USE_SESSIONS is True ? (Django 1.11)
Good evening everybody, As a student group, we are developing an API using Django 1.11.2 and we would like to consume our API from mobile apps (such as Android applications). Currently, we are struggling getting the CSRF token from mobile applications, here's the background : We are using CSRF_USE_SESSIONS = True. From what I understand from the Django CSRF documentation, the token is stored in the session instead of a cookie. We are using the SessionMiddleware in which the SESSION_ENGINE is configured as 'django.contrib.sessions.backends.signed_cookies' For the big authentication part, we are using class-based views. In multiple templates, we are using {% csrf_token %} into forms in order to protect them during POST requests. Everything works great when consuming the API from a non-mobile web client. However, when consuming it from an Android application, we face multiple problems. What we tried so far was - during a GET request - getting the CSRF token from the session and sending it through Accept: 'application/json' : class Login(LoginView): form_class = AuthenticationForm template_name = 'users/login.html' def get(self, request, *args, **kwargs): if request.META.get('HTTP_ACCEPT') == 'application/json': csrftoken = request.session.get(CSRF_SESSION_KEY) return JsonResponse({ 'csrf-header-name': 'X-CSRFToken', 'csrf-token': csrftoken }, status=200) return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): … -
Command Prompt freezes when creating a venv
I am starting a new django project and when I try to add a venv to the project folder my command prompt freezes at the last line of the following code: C:\Users\ab\workspace\rc>virtualenv venv Using base prefix 'c:\\users\\ab\\appdata\\local\\programs\\python\\python36-32' New python executable in C:\Users\ab\workspace\rc\venv\Scripts\python.exe Installing setuptools, pip, wheel... Same thing when I try to install it using the command prompt in my PyCharm project. When I Control-C I see the following: Traceback (most recent call last): File "c:\users\ab\appdata\local\programs\python\python36-32\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\ab\appdata\local\programs\python\python36-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\ab\AppData\Local\Programs\Python\Python36-32\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 713, in main symlink=options.symlink) File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 945, in create_environment download=download, File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 901, in install_wheel call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=SCRIPT) File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 786, in call_subprocess logger.info(line) File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 198, in info self.log(self.INFO, msg, *args, **kw) File "c:\users\ab\appdata\local\programs\python\python36-32\lib\site-packages\virtualenv.py", line 220, in log if self.level_matches(level, consumer_level): KeyboardInterrupt I am on Windows 7. Any idea what is holding it up? -
POST request with a form action on another page returns 405, doesn't process request.POST
The idea is to display a search box, where a user can type in the address, which get's completed by Google Autocomplete. Then, we save the lat and long parameters and redirect to the /search (using POST) or (maybe use a GET request) alternatively /search?lat=xxx&long=xxx. For the second case, with URL parameters I could use lat = request.GET('lat') My Index.html form <form action="{% url 'users:index' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" /> <input type="hidden" id="cityname" name="cityname" /> <input type="hidden" id="Lat" name="Lat" /> <input type="hidden" id="Lng" name="Lng" /> <button type="submit">Submit</button> </form> When user picks from the dropdown, the javascript gives me values of Lat , Lng and cityname. Upon submit, they are redirected to /users/, which is a ListView and has the following views.py class IndexView(ListView): # context_object_name = 'latest_teacher_list' model = Teacher def get_context_data(self, **kwargs): if self.request.method == 'POST' and 'Lat' in self.request.POST: if self.request.POST['Lat'] != '': lat = self.request.POST['Lat'] else: lat = None else: lat = None context = super(IndexView, self).get_context_data(**kwargs) context['teacher_list'] = Teacher.objects.all()[:5] context['lat'] = lat return context However, this gives me a blank page when I submit the form. When form action is blank, it submits the form … -
Image size/resolution based on webpage layout
For the given below webpage, <!DOCTYPE html> <html lang="en"> <head> <title>xyz</title> <meta charset="utf-8" /> {% load staticfiles %} <link rel="stylesheet" href="{% static 'personal/css/bootstrap.min.css' %}" type = "text/css"/> <meta name="viewport" content = "width=device-width, initial-scale=1.0"> <style type="text/css"> html, body { height:100% } </style> </head> <body class="body" style="background-color:#f6f6f6"> <div class="container-fluid" style="min-height:95%; "> <div class="row"> <div class="col-sm-2"> <br> <center> <img src="{% static 'personal/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> </center> </div> <div class="col-sm-10"> <br> <center> <h3>My blog</h3> </center> </div> </div><hr> <div class="row"> <div class="col-sm-2"> <br> <br> <!-- Great, til you resize. --> <!--<div class="well bs-sidebar affix" id="sidebar" style="background-color:#fff">--> <div class="well bs-sidebar" id="sidebar" style="background-color:#fff"> <ul class="nav nav-pills nav-stacked"> <li><a href='/'>Home</a></li> <li><a href='/blog/'>Blog</a></li> <li><a href='/contact/'>Contact</a></li> </ul> </div> <!--well bs-sidebar affix--> </div> <!--col-sm-2--> <div class="col-sm-10"> <div class='container-fluid'> <br><br> {% block content %} {% endblock %} </div> </div> </div> </div> <footer> <div class="container-fluid" style='margin-left:15px'> <p><a href="#" target="blank">Contact</a> | <a href="#" target="blank">LinkedIn</a> | <a href="#" target="blank">Twitter</a> | <a href="#" target="blank">Google+</a></p> </div> </footer> </body> </html> <img src="{% static 'personal/img/profile.jpg' %}" class="responsive-img" style='max-height:100px;' alt="face"> is loaded using Django templating. Above page uses bootstrap css framework, for responsive design Image size/resolution impacts utilisation of network bandwidth. Appropriate image size helps in creating responsive UI design. Question: How to decide the size/resolution of image, for … -
override create method in django rest generics CreateAPIView
My views.py of django app is as below, class MemberCreate(generics.CreateAPIView): queryset = members.objects.all() serializer_class = MemberSerializer permission_classes = (permissions.IsAdminUser,) def create(self, serializer): ''' I wanted to do some stuff with serializer.data here ''' pass Here in the above if I override the create function the return is failing with following error, Even If I don't do any thing and just write pass it is failing , AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` -
Nesting django modules
I am trying to create some (witout knowing any better name) nested modules. I have: An Album module An asset module A Track module An Image module I want to be able to create (using serializer) the following structure: { 'name': 'My first Album', 'assets': [ 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act' ], 'images': [ 'Sunflower.jpg', 'Whitetail.jpg', 'Dinosaur-Act.jpg' ], ] } The thoughts behind this is to allow an easy addition of assets to Album. I followed this example and tried to modify it a bit to achieve the desired structure but it didn't work. class Album(models.Model): name = models.CharField(max_length=100) class Assets(models.Model): album = models.ForeignKey(Album, related_name='assets', class Track(models.Model): assets = models.ForeignKey(Assets, related_name='tracks', on_delete=models.CASCADE) title = models.CharField(max_length=100) class Image(models.Model): assets = models.ForeignKey(Assets, related_name='images', on_delete=models.CASCADE) path = models.CharField(max_length=100) What am I missing? -
javascript control one tag
How to use Django design the model and form to achieve the threaded-comment, especially the reply function presented in the semantic-ui like this Besides, I use the form with modal action, and the code is here: <div class="ui container" style="padding: 5%;"> <form class="ui error tiny form" method="post" action="{% url "comment" detail.id %}" style=""> //comment is from views.py context which has been selected the certain article's comments {# wrong form #} {% if form.errors %} <div class="ui error message"> {{ form.errors }} </div> {% for hidden in form.hidden_fields %} <div class="field"> {# avatar #} //this is a function which allows users to choose a picture <div class="ui inline dropdown"> <span>Pick up</span> <div class="comment text"> an avatar </div> <i class="dropdown icon" id="avatar-tri"></i> <div class="menu"> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/matt.jpg" %}"> matt </div> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/justen.jpg" %}"> justen </div> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/jenny.jpg" %}"> jenny </div> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/elliot.jpg" %}"> elliot </div> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/stevie.jpg" %}"> stevie </div> <div class="avatar item"> <img class="ui avatar image" src="{% static "img/christian.jpg" %}"> christian </div> … -
How to make Django LiveServerTestCase log requests
Django has a feature to log each http request. Eg.: INFO 2017-08-31 11:52:40,725 arnaud basehttp "GET /design/projects/ HTTP/1.1" 200 3852 Unfortunately, it seems to be disabled when running a LiveServerTestCase. In order to ease the debugging of my end-to-end tests, I would like this feature to remain activated. -
Autocreate new database rows
My application creates several rows of data per customer per day. Each row is modified as necessary using a form. Several modifications to a row may take place daily. At the end of the day the customer will "commit" the changes, at which point no further changes will be allowed. In each row I have a 'stage' field, stage=1 allows edits, stage=2 is committed, no further changes allows. How can I update the stage value to 2 on commit? In my model I have: @property def commit_stage(self): self.stage = 2 self.save() Is this the correct way to do this? And if so, how to I attach this function to a "commit" button. -
No module named jsoneditor error in django app
Here's the error: /app$ python3 manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/python/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/python/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked ModuleNotFoundError: No module named 'jsoneditor' But actually I have jsoneditor installed pip3 install django-jsoneditor Requirement already satisfied: django-jsoneditor in/usr/local/lib/python3.5/dist-packages Requirement already satisfied: packaging in /usr/local/lib/python3.5/dist-packages (from django-jsoneditor) Requirement already satisfied: six in /usr/lib/python3/dist-packages (from packaging->django-jsoneditor) Requirement already satisfied: pyparsing in /usr/lib/python3/dist-packages (from packaging->django-jsoneditor) my installed app INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jsoneditor' ] Then why this error? What's wrong? -
Send data by post from AngularJs to Django
I want to send data from AngularJS to the back end (Django) via Http request. I tried many ways but I keep not getting the sent data when receiving the request in django. Before I paste my code, I just have changed the configurations in AngularJS in my project as the following var myApp = angular.module('myApp',[]).config(['$httpProvider', '$interpolateProvider', function ($httpProvider, $interpolateProvider) { $interpolateProvider.startSymbol('{/'); $interpolateProvider.endSymbol('/}'); $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';}]); The urls: urlpatterns = [ url(r'^save_comment/', views.save_comment, name='save_comment'),] Sending Https POST in Angular: $scope.submit_comment = function () { $http({ method: "POST", url: 'save_comment', data: $.param({ 'fish_id' : "1" }) }).success(function (response) { console.log(response.result); }).error(function () { console.log("failed") }); } Receiving the request in the Views def save_comment(request): data = request.POST.get('fish_id') return JsonResponse({'result': data}, content_type="application/json", safe=False) But I didn't get any result. the console gave me this error: POST http://127.0.0.1:8000/brain_browser/save_comment 500 (Internal Server Error) So what should I do to send Post data from Angular to Django? Thank in a dvance.