Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save parent and child model object together
I use Django 2.0 and mysql database and my project model is like: class Parent(models.Model): name = models.CharField() class Child(models.Model): number = models.IntegerField() parent = models.ForeignKey(Parent) what I want is to save both parent and child object together at the same time so that if in any case the child object has error(like number field is "some text") and can not be saved the parent object doesn't save. if Flask sqlalchemy there is add(object) and add_all([parent, child]) methods and I used add_all so if child has error parent doesn't save neither. but in Django I couldn't find this method. the default method is: parent = Parent(name = "my name") parent.save() child = Child(number=3, parent=parent) child.save() what I want is something like this: parent = Parent(name = "my name") child = Child(number=3, parent=parent) and then: child.save(with related parent) or: save(parent, child together) PS: I read this link but I couldn't figure it out: django relations -
Writing to HEROKU logs in Django
I've created a project in Django and have deployed it to HEROKU. Unfortunately, a number of things that were working locally, now don't work on HEROKU. To troubleshoot I need to be able to write to the Heroku logs when my program runs so that I can troubleshoot better. So far I have not gotten it to work My settings/staging.py file contains: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } I have an APP called accounts, so my accounts/views.py file contains: import logging log = logging.getLogger(__name__) def auth_profile(request): log.debug('TESTING THE DEBUGGER') When auth_profile is accessed I want to see the text 'TESTING THE DEBUGGER' show up in the Heroku logs, but so far I get nothing. How do I get this to work? -
Django Sitemap.xml and Robots.txt
I've tried set sitemap.xml and robots.txt up on my django project but it doesn't go well. I've already followed some tutorials I could find on the Internet, but none of them works for my case. Errors are basically about "non-existing template" even after I've tried to replace these files to all different directories. So I don't really get what the reason against it. I know I'm asking a very stupid question, but could someone recommend me any good tutorial to sort this out from the beginning Thanks a lot!!! -
Celery not revoked tasks
I have a task on Celery 4.1. I want to revoke this task like task.revoke() all is nang up on this time, then i raise KeyboardInterrupt and have the same Traceback: File "/usr/local/lib/python3.6/queue.py", line 164, in get self.not_empty.wait() File "/usr/local/lib/python3.6/threading.py", line 295, in wait waiter.acquire() After that, i can revoke tasks. Python 3.6, Celery 4.1, Django 1.11, Redis -
Why get_user_model() return empty in Django
I've been writing a Django web app and a i create new model user, i've been writing functions login, Register.... and i need to use get_user_model(), but when i use it, it return empty Models: class Login(models.Model): id = models.CharField(db_column='id', primary_key=True, max_length=50,unique=True) username = models.CharField(db_column='username', unique=True, max_length=50) password = models.CharField(db_column='password', max_length=254) email = models.CharField(db_column='email', unique=True, max_length=50) security_stamp = models.CharField(db_column='security_stamp', max_length=20) last_login = models.DateTimeField(db_column='last_login') def set_password(self,password): self.password = make_password(password, 'pbkdf2_test', 'md5') def is_authenticated(self): return True class Meta: db_table = 'Login' backend: def authenticate(self, username=None, password=None): try: # Try to find a user matching your username user = Login.objects.get(username=username) # Check the password is the reverse of the username if check_password(password, user.password): # Yes? return the Django user object user = Login.objects.get(username=username) return user else: # No? return None - triggers default login failed return None except Login.DoesNotExist: # No user was found, return None - triggers default login failed return None # Required for your backend to work properly - unchanged in most scenarios def get_user(self, user_id): try: return Login.objects.get(pk=user_id) except Login.DoesNotExist: return None return get_user_model() enter image description here i search in google and i found that must be add AUTH_USER_MODEL = 'myapp.MyUser' in setting but when i added it … -
How to get multi-valued url parameters with request.GET in django template?
I'm just wondering if there is a way to obtain multi-valued URL parameters in Django Template. For example you can get a parameter from an URL like below, http://127.0.0.1:8000/list/?search=SomeValue&color=Red with the code: {{ request.GET.search }} But when it comes to multi-valued parameters like: http://127.0.0.1:8000/list/fuel_types=Benzin&fuel_types=Dizel&fuel_types=LPG I couldn't find a way to obtain it in template. I know that I can get the values in views.py and send it to template with the code: request.GET.getlist('fuel_types') But I want to know if there is a way to achieve that in Django Template without using views.py Thanks! -
Django Models - 'Pcaps.uuid' must set unique=True because it is referenced by a foreign key
In essence I am trying to create a few tables that are populated with attributes of pcaps. I am receiving quite an odd error. This is the code in the models class: class Pcaps(models.Model): uuid = models.CharField(max_length=50) filename = models.CharField(max_length=200, default='') datetime = models.DateTimeField(default=datetime.now, blank=True) filehash = models.ForeignKey(Malwares, to_field="filehash", db_column="filehash") class PcapsIps(models.Model): domainname = models.CharField(max_length=100) ip = models.CharField(max_length=100) uuid = models.ForeignKey(Pcaps, to_field="uuid", db_column="uuid") class PcapsPorts(models.Model): number = models.CharField(max_length=100) uuid = models.ForeignKey(Pcaps, to_field="uuid", db_column="uuid") The error in question is as follows: ERRORS: analyser.PcapsIps.uuid: (fields.E311) 'Pcaps.uuid' must set unique=True because it is referenced by a foreign key. analyser.PcapsPorts.uuid: (fields.E311) 'Pcaps.uuid' must set unique=True because it is referenced by a foreign key. -
Can you use Django channels as an HTTP server and websocket client
Can I use Django channels to subscribe to multiple websocket servers to receive messages and serve http requests at the same time? -
Delete multiple records in django with a list
Simple question, I think. I have an array with ids of my records that I don't want to delete. How can I got about to delete all records that don't have their id in the list in django? Thank you very much -
User login/panel for bjj event - how to approach this project
I`m a programing newbie and a bjj student. I want to design a user panel for bjj event. My school organizes many local bjj competitions and we need a competitors registration panel. I want to create a web page where competitor can register and sign to a event, enter data such as name/surname/club affiliance/weight devision and a user panel with informations like his weight devision and confirmation that he is signed to a tournament, and that his entry fee has been accepted . I also need an admin page where i can see all competitors, that have paid their entry fee, divided by weight class and to be able to create a tournament bracket out of it in a spreadsheat. How should approach this project? I have good understanding of html css, and curently learning python. i want to help my bjj school and give something back, since they accpted me for free and bjj changed my life and set it back to the right track. I think this is good for the first project. How should i approach it? I`m willing to learn new technologies and just want some basic guidlines. What technologies should i use (preferably based on … -
How to configure django with xampp mysql?
I'm new at Django. After configuring the settings when I tried to migrate with mysql then it said "Did you install mysqlclient or MySQL-python?" I have already xampp installed on my machine so I don't want to install mysql server again and mysql is running well on xampp. Then I've installed "python-mysqldb" for mysql binding. But the same error again. After that I've installed mysqlclient as the error then ran the migrate again but now its saying I don't have a mysql server. But the mysql is running on xampp. What should I do? Should I install mysql server? There is no way to use xampp? I didn't find any useful article on google about that. Here is my database configuration, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todolist', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } error that asking for mysql And error that saying there is no mysql server -
django cookiecutter extending base.html wipes out my web page
I am working on a project that I started in June 2017 with the cookiecutter I had just installed. At the time, with respect to django, I was an absolute beginner. (I am a bit more advanced by now, but just a bit.) Cookiecutter put a base.html in the templates directory (one level above the app subdirectories). For a list of model rows, I have a template that works all by itself, as follows: {% if brand_list %} <ul> {% for brand in brand_list %} <li><a href="/brands/{{ brand.id }}/">{{ brand.cTitle }}</a></li> {% endfor %} </ul> {% else %} <p>No brands are available.</p> {% endif %} But, if I put this at the top, I do not get the list:: {% extends "base.html" %} What I get instead is the project root webpage, the one at /. Is this base.html the problem, or something else? -
Session Variable destroyed only in chrome python django
I have my session caches set up like so in the base.py settings file: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "samy_python" } } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' I set my session in the @csrf_exempt callback view like so: if request.method == 'GET': code = request.GET.get('code') # Get Code from parameter request.session['code'] = code # Set Code to session return redirect('/close/') # Close Window I know it is set because I will use a logger and log the code. The close.html is this: <script> window.open('', '_self', ''); window.close(); </script> However, when I catch the close in another html file and post to a different view, the "request.session.get('code')" is empty. This only happening on chrome so far. Does anyone know why this is happening? I have found a few ways to solve it, buy working around it doesn't seem right. Esp if it works just fine in firefox... Thank you. -
Global Variable in Django?
I am writing a Django project which will use Chrome Headless to produce PDF documents. There are lots of Apps, each of which will produce PDFs, so it made sense to have a class, that launches Chrome, makes a connection to it, and kills the Chrome process when the class is deleted. There will be a class method, which opens a new tab, renders some HTML, and returns the PDF data, and closes the tab. It seems slightly inefficient to create a new instance of the Class, every time I want to print a PDF (which is the primary purpose of the project). It seems better to create a global instance of the Class, and have one copy of headless Chrome running the whole time, rather than starting Chrome, connecting to it, getting the PDF data, and then closing everything every time. Other posts on this issue, suggest that any kind of global variable (aside from some constants in settings) is a bad idea. In this particular case, is this still a bad idea? Why is this the case? Importantly, is there an alternative approach? -
How to configure Django with XAMPP MySql?
I'm new at Django.I have already XAMPP installed and created a database as the name of my project. I have modified the settings for mysql but getting error. It asking for the mysql. I don't know where is the problem is. I've searched on google a lot but didn't find useful answer. Here I'm giving a picture of the error, error for connecting django with xampp mysql Here I'm giving my mysql configuration settings, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todolist', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } -
Django 2.0 url regex
I had a url pattern like 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.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'), how can I use this as new path pattern -
The diminishing of my python knowledge? [on hold]
I learned the basics of python and jumped into Django, I like both. I start to get deeper into Django but somehow feeling the opposite goes with python as a pure language, I feel like that Django would make me no python developer like know how to work with the language itself without any framework. Should I quit the Django for now and start-over with python until getting a good knowledge of problem-solving, or I will learn more about python along the way and this is just an illusions. -
AWS EB container command permission denied
I have the following container_command in my django.config that points to a script at path .ebextensions/supervise.sh: container_commands: 01-supervise: command: .ebextensions/supervise.sh However when I deploy I get a permission error. Command failed on instance. Return code: 126 Output: /bin/sh: .ebextensions/supervise.sh: Permission denied. I'm wondering what is required to set permissions correctly? What is causing this error? As far as I can tell the issue isn't well documented. Thanks! -
Change button size bootstrap 4 (Django)
I'm working with Django and I'm trying to line up a Bootstrap button with a select field. I've got the form inline where I'd like it to be, but I can't seem to make the button smaller to make it align properly. I'm sure there is a simple solution but I've been struggling with this for hours and can't seem to find anything that works for me. Here is a picture as it is currently to give you a better idea of the problem: button not aligned And here is my current code in my template: <form class="form-inline" action="{% url 'displayStats:proindvleaders'%}" method="post"> {% csrf_token %} <div class="row"> {{ form.as_p }} <button id="submit" type="submit" class="btn btn-primary btn-sm">Submit</button> </div> I've tried just setting height on the button ID with css but it doesn't seem to be working for me. Any ideas? -
Django module object is not iterable
I'm currently trying to build a blog using Django. I've been facing this error for a few hours now. I'm not quite sure if this has anything to do with the directories but the error occurs when I try to register my model in the admin.py file. from django.contrib import admin from .models import Post # Register models admin.site.register(Post) The directories look as follows: blog models Post Category admin.py settings static templates Trace: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ffb589a67b8> Traceback (most recent call last): File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate app_config.ready() File "/usr/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/usr/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/usr/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
showing dynamic data from database in all views
I'm using Django 2.0 I have a Model withing notes application notes/models.py class ColorLabels(models.Model): title = models.CharField(max_lenght=50) In the sidebar navigation which will be displayed on all pages, I want to show the list of color labels and it will show on all pages. How can I show dynamic data in all views or say on all pages? -
Forbidden (403) CSRF verification failed. Request aborted.in Django
Why is Django having this error 'Forbidden (403)CSRF verification failed. Request aborted.' when I already have {% csrf_token %} in the form. {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endblock %} -
django get associated data one to one field
I'm working in Django 2.0 I have a model Note to save note and two another models to add color labels to the note. class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=250, blank=True, default='Untitled') content = models.TextField(blank=True) class ColorLabels(models.Model): title = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=100) default = models.BooleanField(default=False) class NoteLabel(models.Model): note = models.OneToOneField(Note, on_delete=models.CASCADE) color_label = models.OneToOneField(ColorLabels, on_delete=models.CASCADE) with the object of Note note = Note.objects.get(pk=1) I want to access associated ColorLabels's title and value fields or the NoteLabel object. since they are one to one field. I tried doing note.note_label note.NoteLabel note.note_label_set But all returns error as AttributeError: 'Note' object has no attribute 'note_label_set' -
dynamically add / remove fields django
How do I create a button to add and remove a fields, and then save some fields using django (2.0)? my views.py def add_preventivo(request): if request.method == "POST": form = PreventivoForm(request.POST) if form.is_valid(): preventivo = form.save(commit=False) preventivo.published_date = timezone.now() preventivo.save() else: form = PreventivoForm() return render(request, 'add_preventivo.html', {'form':form}) my models.py class Preventivo(models.Model): cliente = models.ForeignKey('Cliente',on_delete=models.CASCADE) prestazione = models.ForeignKey('Prestazione',on_delete=models.CASCADE) numero = models.IntegerField(default='1') prezzo = models.IntegerField(default='0') I must be able to repeat "prestazione" and "numero" and I must have a sum of the various repetitions on "prezzo" -
Queryset and Templates: Loop thru multiple connected models inside a template, starting from a model that have Foreign keys to all of them
I have 4 models: Account, Company, Product, Action. class Action(models.Model): account = models.ForeignKey(Account, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) company = models.ForeignKey(Company, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) product = models.ForeignKey(Product, blank=True, null=True, related_name='activity', on_delete=models.CASCADE) sent_at = models.DateTimeField(blank=True, null=True) Beside the Action model, the relations are: 1) User to Account -OneToOne 2) Company to Account OneToOne 3) Product to Company, ForeignKey (a Company can have multiple products) I need to filter by sent_at is Null, an in Template, to have: For Loop Account -> inside For Loop Company (companies corresponding to account) - not necessary in case of OneToOne -> inside For Loop Products (products corresponding to account) Using as context in a template: actions = Action.objects.all().filter(sent_at__isnull=True) It is possible to do the above loops, and how ? If not what other solutions do I have ? It is possible that all ForeignKeys keys are not null, or just some of them are null. For example Account,Company are not null , but product is null. If Product is not null always Account,Company are not null. If Company is not null always Account is not null.