Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apply django's template filters inside a `js` script on an object's attribute
I'm unable to use django's template filters inside a js script on an object's attribute. This piece of code returns a js SyntaxError: <script> {{ obj.geometry.geojson | safe }} </script> While if the filter is applied on an object, no error is thrown: <script> {{ obj | safe }} </script> The content of the GeoJson file above is shown below: { "type": "Polygon", "coordinates": [ [ [ 3, 36 ], ... I obviously don't want to have the quote character (") escaped into a (& quot ;) so I can JSON.parse() it later to convert it from a string into an object. -
How to connect django project to mysql database if the mysql database reside in wamp server?
I googgled alot and see many solutions, but none of the worked for me. I have a project in django and also an app as well. now, I want a connection to mysql database the reside in wamp server in order to interact (sending data or getting data) to database through my app.I also installed MYSQLDB for python. and I have done neccessary things in settings.py file.following is content of settings.py regradding of database DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'flask', 'USERNAME':'root', 'PASSWORD':'', 'HOST':'127.0.0.1', 'PORT':'', } } -
Year Field in Django
I want my users to enter their birth year. I don't want them to type the same in the form rather select the year from available options. I known that I can do something like this in my model if I needed to date instead of year: class MyModel(models.Model): birthday = models.DateField(null=True, blank=True) I can do this in forms to let the user choose date from datepicker. birthday = forms.fields.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) For year, I can use a CharField/IntegerField with choices similar to what has been done in this SO answer. import datetime YEAR_CHOICES = [(r,r) for r in range(1984, datetime.date.today().year+1)] year = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) The problem, however, is that change of current year from say, 2018 to 2019, will not change the available options. Can you help or provide hints to achieve what I want to do? -
Error Uncaught SyntaxError: Unexpected token {
I'm using a well known library. So I don't think the problem is with the code. The error and console are referring to this line--typed.js:1: import { initializer } from './initializer.js'; Here's the script tag: {% block javascript %} <script src="{% static 'js/typed/typed.js' %}"></script> what am I doing wrong? -
If celery/redis fails to load the other forms in a formset are not saved
On a Model on the save method I call the celery task. The Model is used in a formset at is called multiple times, per each from in a formset. Normal Django default formset, nothing special. The issue is, if celery fails to load(celery/redis not started blocked), the first form/image is save, but the others are not(probabilly because is the same model). How can I let the other forms in formset be saved, even if celery/redis is failing. By failing I'm not meaning task failing but redis failing. I execute the task on the model and not formset/form because I need to be available also in Django Admin. class Image(models.Model) .... def save(self, *args, **kwargs): super().save(*args, **kwargs) transaction.on_commit(lambda: image_crop_task.delay(self.image.path, self.pk)) -
How to use opencv's captureVideo in django?
i am making a web app in django. I am making an object recognition app. I need to capture video live from camera and find objects in it and stream that video with bounding boxes on the template. I am capturing video through opencv. The problem is it just streams one frame to the template and stuck there. Here is my code. class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) def __del__(self): self.video.release() def get_frame(self): ret,image = self.video.read() ret,jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() def gen(camera): while True: frame = camera.get_frame() yield(frame) time.sleep(1) def Index(request): return StreamingHttpResponse(gen(VideoCamera()),content_type='multipart/x- mixed-replace') Help me with it if anyone can and if not please suggest me some other way to do it. -
Failure in importing using Django import export in fields that are supposed to be generated in model.save overridden function
I have a model Candidate with a customized save() that generates a username/password and create a new user for it as a foreign key. It works well in django admin, but in django import-export I get the error: django.db.utils.IntegrityError: null value in column "utilisateur_id" violates not-null constraint Full traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/import_export/resources.py", line 471, in import_row self.save_instance(instance, using_transactions, dry_run) File "/app/.heroku/python/lib/python3.6/site-packages/import_export/resources.py", line 281, in save_instance instance.save() File "/app/conference_manager/models.py", line 112, in save self.QR_code.save(filename, filebuffer) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/files.py", line 97, in save self.instance.save() File "/app/conference_manager/models.py", line 130, in save super(Personne, self).save(force_update=force_update) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 796, in save force_update=force_update, update_fields=update_fields) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 823, in save_base self._save_parents(cls, using, update_fields) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 848, in _save_parents self._save_table(cls=parent, using=using, update_fields=update_fields) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/base.py", line 947, in _do_insert using=using, raw=raw) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 1043, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise … -
Unable to serve Django static files on AWS elastic-beanstalk
I have searched many questions and answers, AWS and Django(2.0) docs but still unable to serve static files. I am new to AWS and have made just basic web app. My settings.py have: INSTALLED_APPS = [ .. 'django.contrib.staticfiles', .. ] STATIC_ROOT = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' My project directory: |.ebextensions |--django.config |.elasticbeanstalk |--config.yml |app |--migrations |--static |--tempates |--admin.py |--...... |--views.py |project |--settings.py |--urls.py |--wsgi.py |static |manage.py |requirements My django.config has: container_commands: 01_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: awtest/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static/" HTML source : <html> <head <title>Home</title> </head> <body> <img src="/static/app/symbol-logo.png" alt="" style="width:50px;height:60px;""> <h1>AWS</h1> </body> </html> When I run this on my computer it works fine, i can see the image but as soon as I deploy on AWS beanstalk I am unable to see the image and when I check source and click on image url, it says Forbidden, you don't have permission to access the image on server. Can anyone point where I might be going wrong? Any help will be appreciated! -
Django: url language prefix doesnt work in reverse
I have a website that supports both the Dutch and French languages. I am using Django's translation features with languages url prefixes like so: www.example.com/nl/rest-of-url/ www.example.com/fr/rest-of-url/ I am using the following root urls config from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.conf.urls.i18n import i18n_patterns from django.utils.translation import ugettext_lazy as _ admin.autodiscover() urlpatterns = [ url(r'^admin-url-thingy/', include(admin.site.urls)), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( url(_(r'^django-app/'), include('django-app.urls'), name='django-app'), ) if settings.DEBUG: urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now, this all works out just fine in the main list view. However, as soon as other views are called with a reverse in the main template, the language defaults back to nl <a href="{% url "some_view" %}>{% trans 'Dutch or French sentence' %}</a> So accessing the above from www.example.com/fr/rest-of-url/ sends me to www.example.com/nl/rest-of-url/some-view/ Does anyone know why this is / what I am doing wrong? -
Django restframework documenting Views
My questions is: how can i fill the field Description? in tha table of Parameters in my docs page, here an example of my function and a screenshot how does it look def delete(self, request, id_): """ ###### Delete an analysis by ``` id_ ```. return an answer without body """ -
Django Form field initial value when updating an instance
I have a custom Django ModelForm that I use to update a model instance. This is the example model: class MyModel(models.Model): number = models.CharField(_("Number"), max_length=30, unique=True) sent_date = models.DateField(_('Sent date'), null=True, blank=True) When creating an instance I will pass only the number field, that is why I don't want the sent_date to be required. Then I have a view that updates the sent_date field, using this custom form: # Generic form updater class MyModelUpdateForm(forms.ModelForm): class Meta: model = MyModel fields = [] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Make fields mandatory if hasattr(self, 'required_fields'): for field_name in self.required_fields: self.fields[field_name].required = True # Set initial values if hasattr(self, 'initial_values'): for field_name, value in self.initial_values.items(): self.initial[field_name] = value class SentForm(MyModelUpdateForm): required_fields = ['sent_date'] initial_values = {'sent_date': datetime.date.today()} class Meta(MyModelUpdateForm.Meta): fields = ['sent_date'] field_classes = {'sent_date': MyCustomDateField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) MyModelUpdate is a generic ancestor for concrete forms like SentForm. In my view whenever there is a GET I manually instantiate the form with: my_form = SentForm({instance: my_model_instance}) So in this case I would expect the sent_date field to have an initial value set to today's date even tough the real model instance field is None. If I inspect … -
Why can't I use this django template variable in conditions?
Following the advice here, I have access to the allowed_contributors variable in the template and I can print it out, but using it in any kind of if-else statement doesn't work. It doesn't give me a 500 error, but it acts like it's empty. Here's what I've put in the template (not showing the "load" command at the top, but I guess that must be working). <div class="container"> <h1>Create new project</h1> <p> {% allowed_contributors %} </p> {% if "true" in allowed_contributors %} <p>"true" found in allowed_contributors!</p> {% endif %} {% if "false" in allowed_contributors %} <p>"false" found in allowed_contributors!</p> {% endif %} </div> The HTML output looks like: <div class="container"> <h1>Create new project</h1> <p> ('auth', 'false') </p> </div> I've tried outputting the allowed_contributors multiple times in case it's being consumed the first time, but it seems to make no difference. Do I need to reference it in a different way when I'm using it as a condition for an if statement? -
how to design the django model?
I need to use django to develop a feature,the Depending on what is requested, different people need to approve the request or perhaps send it back to the requester for modification. The approvers need to keep track of what to approve what has been approved and the requesters need to see the status of their requests. -
How do I create a form controlled by another user?
I need a piece of advice. Let's presume three models: Teacher, Student and Lecture. Say the teacher wants the student to upload a document for a lecture, but teacher can also cancel the form when he wants to. How can I create this behaviour ? Give the teacher the power to add or remove the form for his students, for a particular lecture. -
How to get a tag in views from html with django
I have a html page which uses jinja to display a list. I want to be able to get the user to click a button and the list will be added to a database. I have put the button in side a form and got it to link to my url which then calls a function. HTML: <form method='post' action='../../accounts/myaccount/' name= '{{item}}'> {% csrf_token %} <a name = '{{ item }}'><button type='submit' class='btn'><img src={% static 'results/images/basket_02.png' %} alt='Image cannot be displayed right now'></button></a> </form> Views: def myaccount(request): if request.user.is_authenticated(): if request.method == 'POST': product = request.GET.get('name') print('product: ' , product) return render(request, 'signup/myaccount.html') The function is called and it prints: product: NONE , whereas i want product to be set to the list. I know how to add to database within my views but is there a way to actually access my list? -
Change logo of AdminLTE in django
I am using AdminLTE in my django admin site. I want to change its logo to my site name and also want to change its redirect link. But not getting any help related to that. Please give the solution if anyone has an idea about that. -
Debugging Django in VSCode error
I try to debug my Django app in VSCode my launch.json settings: { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": false, "pythonPath": "D:\\software\\program_books\\python\\exercises\\mezzanine\\env\\Scripts\\python.exe", "program": "${workspaceFolder}\\mezzanine-themes-master\\mezzanine-themes-master\\manage.py", "cwd": "${workspaceFolder}", "args": [ "runserver", "--noreload", "--nothreading" ], "env": {}, "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput", "DjangoDebugging" ] } cosole error info Traceback (most recent call last): File "D:\software\program_books\python\exercises\mezzanine\mezzanine-themes-master\mezzanine-themes-master\manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle self.run(**options) File "D:\software\program_books\python\exercises\mezzanine\env\lib\site-packages\django\core\management\commands\runserver.py", line 112, in run self.inner_run(None, **options) TypeError: inner_run() got multiple values for argument 'show_banner' Anybody know what my issue could possibly be? I just want to debug my application! -
Windows Error 10061 - Django Channels
There is a problem when using Django Channels In some Windows 10 machines. Basically i can not connect to the Socket [Error 10061] and python gives me out an error ERROR - server - Exception inside application: Multiple exceptions: [Errno 10061] Connect call failed ('::1', 6379), [Errno 10061] Connect call failed ('127. 0.0.1', 6379) I know it's Windows/OS level problem. I have already turned off all firewalls etc. Still cant connect to the socket Example repo: https://github.com/andrewgodwin/channels-examples -
select_related and prefetch_related - not getting results in query
I am trying to make simple learning project where i am getting all records and displaying on html. My models are : class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) from this model i am trying to display student , course and dept information using below query : course = Course.objects.all().prefetch_related('students').select_related('dept') my html code is : {% for c in course %} <tr> <td>{{c.students.stuName}}</td> <td>{{c.students.stuCity}}</td> <td>{{c.dept.deptName}}</td> <td>{{c.courseName}}</td> <td><a href="#">Edit</a> </td> </tr> {% endfor %} I am unable to display student information.. Can any one please help me to correct my mistakes.I am assuming my query is not correct. Jordan -
Invalid HTTP_HOST header: '127.0.0.1:8000' error
When my settings.py has ALLOWED_HOSTS = [] - the server works fine. But When I do ALLOWED_HOSTS = config('ALLOWED_HOSTS') - it gives the error: DisallowedHost at /admin/login/ Invalid HTTP_HOST header: '127.0.0.1:8000'. You may need to add '127.0.0.1' to ALLOWED_HOSTS. However when I go into python shell I'm successfully able to import ALLOWED_HOSTS - and it prints [] which is the correct value. Any reason why I still get the error? PS: The config is a feature of the python-decouple package - used to store sensitive values. -
Django one-one relation IntegrityError: UNIQUE constraint failed
I want to make a website which creates a 14 weeks therapy session for its users. The course/therapy has a one to one relationship with the user and the therapist. And a many to one relationship with the weekly sessions model. When I simply created the course without creating the weekly sessions, everything worked fine. But when I added code for creating weekly sessions(in the same views function), it shows integrity error. models.py : class Therapist(models.Model): name = models.CharField(max_length=20) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") contact = models.CharField(validators=[phone_regex], max_length=17,blank=True) region=models.CharField(max_length=30,default='online') def __unicode__(self): return self.name class UserProfile(models.Model): user = models.OneToOneField(User) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex],max_length=17,blank=True) age=models.IntegerField() region=models.CharField(max_length=30) def __unicode__(self): return self.user.username def get_region(self): return self.region class CBT_therapy(models.Model): """docstring for CBT_therapy : has one to one relationship with user and therapist. Many to one relation with weekly session. """ start_date = models.DateField() session_time=models.TimeField() therapist=models.OneToOneField(Therapist) user=models.OneToOneField(User,on_delete=models.CASCADE) class WeeklySession(models.Model): session_date=models.DateField() session_time=models.TimeField() week_no = models.IntegerField() challenge=models.CharField(max_length=150) therapy = models.ForeignKey(CBT_therapy) class Challenge(models.Model): title=models.CharField(max_length=150) def __unicode__(self): return self.title Views.py : def registerCBT(request): if request.method == 'POST': register_form = RegisterCBTForm(request.POST or None) … -
django the same template but different content after post
I'm trying to send an email and after sending an email, redirect the user to the same page, at the same address, but with a different content - with thanks, and with the date of the event he signed up for. This is my code: class EventDetailView(DetailView, CreateView): model = models.Event form_class = forms.ParticipantForm context_object_name = 'event' template_name = 'events/event_detail.html' def get_success_url(self): messages.success(self.request, u"Success message - text only") return reverse('events:detail', kwargs={'slug': self.kwargs['slug'], 'pk': self.kwargs['pk']} def get_initial(self): return {'event': self.kwargs['pk']} def get_context_data(self, **kwargs): context = super(EventDetailView, self).get_context_data(**kwargs) context['event'] = self.get_object() return context For now, I managed to send only a simple message via messages, but that's not enough -
Django - How do I can have a big initialization required for a view (APIView)
I have a simple APIView: class MyView(APIView): symspell = Symspell() def post(self, request): res = symspell.do_something() return res Here's my issue: the constructor of my class Symspell required something like 30s to run. So when i run or do anything with my app really (like ./manage.py migrate) it adds 30s to the runtime. So my questions would be: is there a better way to do this ? (use a class with a long constructor in a view) can i only construct this view when i'm ONLY running the server and not doing other operations like migrations ? can i use the same class in several views ? Thanks for your help ! -
Getting Forbidden CSRF verification failed only when inspects debug tool is open
Forbidden (403) CSRF verification failed. Request aborted. I am getting Forbidden (403) CSRF verification failed error only when inspects debug tool is open in chrome. Same form is getting submitted successfully when I close the inspect debug tool in chrome. In Firefox it works fine both in inspecting debug tool opened and close. Here is my django application code. Django version 1.11 Python version 2.7 view.py class TestForm(View): def get(self, request): logger.info("GET TestForm.................") logger.info(request.META) self.data = dict() self.data["name"] = "test" return render(request, 'test.html', self.data) def post(self, request): logger.info("POST TestForm.................") logger.info(request.META) return redirect('/testForm/') test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test form</title> </head> <body> <form action="." method="post"> <h2>Test form for csrf token</h2> {% csrf_token %} <input type="text" name="name" value="test"> <input type="submit" value="Submit"> </form> </body> </html> Any help why and how to resolve this issue would be highly appreciable. -
How can I implement the Django Admin Foreign Key's Add button?
I would like to implement the add button we have beside a ForeignKey field, so that we can add data to the field/database. I have been following a couple tutorials, but none of them help me actually add data to the field, and in turn, my database. I have also been looking everywhere but I can't seem to find anyone that has accomplished this task. A good tutorial I have been following is this one: https://djangopy.org/how-to/reverse-engineering-of-the-django-admin-foreign-keys-addedit-button/ However, the tutorial is very good until the end. He only implements the edit button, and not the add button. So I'm not sure which AJAX call I need to make in order to replicate that of which the admin add button does, when adding data for the ForeignKey. For the sake of brevity, all code from the tutorial is exactly what I have, I just need to implement a function for the add button. If anyone has any ideas or could point me into the right direction, that would be greatly appreciated.