Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I prevent Django's admin interface from silently suppressing errors?
Suppose I have a simple Django model: class MyModel(Model): created = models.DateTimeField(default=datetime.utcnow) @property def my_property(self): raise ValueError('Is anyone there') Then in my admin GUI, I show my_property as a read-only field. @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): ... readonly_fields = ['my_property'] To my surprise, if any exception is raised in generating a value in the Django admin GUI, Django suppresses the error and just shows a "-" as the value. It took me some time to realize this was the case. Is there a way to force Django to show exceptions when exceptions occur? -
Django - PubSub or workflows or combined?
I am building a chemistry application with django that focuses on reactions. It bonds an atom to an existing molecule. The reaction event triggers a bunch of (a) validations to make sure the feasibility of the molecule checks out (b) subsequent events as the molecule Nested Functions: So I could have my logic layer just keep feeding Python functions into other Python functions, but my fear is that this will become a tangled mess quickly. I also want to have a record of the steps with success/fail and other basic stats, so one hanging process is probably not the best. PubSub: So I could have multiple functions that subscribe/ listen for a reaction and then run/ don't run based on criteria. Using something like django-redis-pubsub. Workflows: Enter workflows. I suppose I could structure the whole reaction process as a giant workflow which would have better transaction atomicity? Should I combine this approach with a pubsub? rule NAME: input: "path/to/inputfile", "path/to/other/inputfile" output: "path/to/outputfile", "path/to/another/outputfile" script: "path/to/script.py" -
How to update python code and see changes live using daphne, Django Channels?
I just made some changes over 1 python file in my production server, then tested the changes using "runserver" command: python3 manage.py runserver 0.0.0.0:3031 The changes are done correctly, then I try to see the same changes in production but using websockets with Django Channels, but the result seems to be that the server is running the old code. daphne -b 0.0.0.0 -p 3031 asgi:channel_layer What could be the reason, is there any code cache?, what can I do to refresh the code? -
Where do files created in Django go?
I have a view where I create a file (call it .something.txt). I see that I can access it from another view as well. Also, it is in the same folder where I have my manage.py. I am trying to understand whether someone from outside can have access to this unencrypted file and how they can get it? Is what I am doing safe, from a privacy perspective, if I store the data as an encrypted text file in the same way? -
Django ViewSet filtering with Foreign Key name
I have 2 Django models with the following structure: class Title(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=256) class Component(models.Model): id = models.AutoField(primary_key=True) code = models.CharField(unique=True, max_length=256) title = models.ForeignKey('Title', on_delete=models.PROTECT) So i have a ComponentViewSet as follows: class ComponentViewSet(viewsets.ModelViewSet): queryset = Component.objects.all() serializer_class = ComponentSerializer filter_fields = { 'id': ['exact'], 'name': ['exact', 'istartswith'], 'title': ['exact'], } So if i want to filter Components via Title the URL is http://localhost:8010/api/components/?title=1. How can I make a view filtering with Title.code value i.e http://localhost:8010/api/components/?title=Test ? -
utf-8 codec can't decode BinaryField from database
I'm currently trying to get a Binary data from the database using the Django ORM. In addition to CharFields, the model also has a BinaryField. When i get my QuerySet, i cannot convert it to a list, Django trows DjangoUnicodeDecodeError. There is any way to decode the BinaryField and convert the QuerySet into a List? models.py class TBL_Form(models.Model): name = models.CharField(max_length=150, blank=True, null=True) category = models.CharField(max_length=64, blank=True, null=True) geometry = models.BinaryField(blank=True, null=True) class Meta: managed = False db_table = 'Form' views.py query = TBL_Form.objects.filter(TBL_Entity).select_related().values_list('id', 'geometry') [item for item in query ] Error DjangoUnicodeDecodeError at / 'utf-8' codec can't decode byte 0xba in position 14: invalid start byte. You passed in b'\x01\x00\x00\x00\x01\x02\x00\x00\x00\x03\x00\x00\x00"\xba\x07W\xb7\xf2\xf2\xc0\xab\x13\xdcW\xfd}\xfc\xc0\xe6yz\xe9\xbb\xf3\xf2\xc0k\x91f4u~\xfc\xc0\xaeM\r\xa2\xfa\xf3\xf2\xc0,wR\x0e\x92~\xfc\xc0' () -
Django CreateView request pass
I'm using django-better-form. A great tool for multi form support. One problem is I want to pass request to the modelform. Using kwargs.pop("request") I faced KeyError. How to fix this -
Django safe filter breaks jinja template
<p class="card-text"> {{ blog_post.description_from_content|safe}} </p> The above comes from the Django/Mezzanine web framework The above will render an empty p tag, and place the contents outside the p tag. If you remove the safe filter then it renders as expected. (inside the p tag). Any idea why this is happening? I can't just remove safe as the content contains html How it renders -
Django 2.1.3 Error: __init__() takes 1 positional argument but 2 were given
i am trying to develop a website whith Django 2.1.3 and python 3.7.1 When i go to the homepage i get this error: TypeError at / __init__() takes 1 positional argument but 2 were given Here some details about the code i write: Trceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\andre\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) Exception Type: TypeError at / Exception Value: __init__() takes 1 positional argument but 2 were given core/models.py This is just one table on DB: from django.db import models class Evento(models.Model): titolo_evento = models.CharField(max_length=30) data_inizio = models.DateTimeField() data_fine = models.DateTimeField() def __str__(self): return self.titolo_evento class Meta: verbose_name = 'Evento' verbose_name_plural = 'Eventi' core/views.py Here i want to see the DB "Eventi" on the homepage only if the user is authenticated, i think the mistake is here, but i don't know where: from django.contrib.auth.decorators import login_required from .models import … -
Integrating Oracle JET with Django
I have created / downloaded the Oracle JET NavBar example with NPM. I have copied and setup the CSS and JS assets in Django and setup the baseURL in require.js to get the static files from django the right way. All seems to work fine, except that the DOM Listener (DOMContentLoaded) does not work. Seems to have something to do with Backbone.JS etc. Has anyone an example if how to setup Oracle JET with Django properly? Thanks! -
How to change page title of password reset form?
I am using the default password reset form, that comes with django..I have changed the title of Admin Site by adding the following line of code in urls.py admin.site.site_header = 'My Site Name' But, the password rest form still says "Django Administration" in place of the site title, as show in the image attached. How do I change it? Password Reset Form -
django celery cannot start worker
I am having an issue with starting up my celery worker for my django project. Thank you for giving any help here. I think I shut down the celery process inappropriately (ctrl+c first, and ran the "celery -A proj worker " command again before it was shut down completely). Since then I have never been able to start up my celery worker. It basically gives no response from the command line, not moving forward, no error, and nothing happens literally. It is just stuck there. I also tried to reinstall my celery and rabbitmq, but this doesn't help either. Does anyone know what could be wrong here? Thank you very much for your help. sen -
Unknown user named demo on my ubuntu server. server hacked
Please read full details before answer. I am develover working on a client's server machine on a site. Site went down sudden. So i checked the dashboard i got error server ip is reported as abused on abuseipdb.com for hacking attempts 126 times. I spockwith support they put site back live. Then i checked the server for issue. I am not system admin person. I am web developer still with help of google i checked the logs and found out that a user named demo entered in the server. When i try to delete it it said it have associated process with him. So i checked there we rsync process. I checked google find out that these are file synchronisation process. I have deleted process and deleted user too. There are still rsync process suspisious to me. How to check what files these process are using and what they are doing. How to identify any other suspisious process. Please help me out. Me and client only both persion have the access to site. So if something happen i will be blamed. one more thing i think it is somehow related with apache because demo user have directory assigned /var/www/html -
normal distribution from django model
How can one build the distribution graph from the model data on the client side: class Parameters(models.Model): par_time = models.DateTimeField('date') par_recipe = models.CharField(max_length=200) par_machine = models.CharField(max_length=200) par_fa = models.CharField(max_length=200) par_ag_typ = models.CharField(max_length=200) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) par_value = models.IntegerField(default=0) By value, if I use html and Data is already loaded in the database -
Django Form based on Form
I am writing my code based on the principle don't repeat yourself. I keep violating that rule because I am new to Django but this one should be straight forward. The code below is no problem for ModelAForm: model.py class ModelA(models.Model): id = model.AutoField(primary_key=True) name1 = models.CharField(max_length=100) name2 = models.CharField(max_length=100) ... right = models.BooleanField(default=True) class ModelB(models.Model): id = model.AutoField(primary_key=True) mod = model.ForeignKey(ModelA, on_delete=models.CASCADE) above30 = models.BooleanField(default=True) forms.py class ModelAForm(forms.ModelForm): class Meta: model = ModelA exclude = ['id'] class ModelBForm(forms.ModelForm): class Meta: model = ModelB exclude = ['id'] But this way I don't see the other fields of modelA in the ModelBForm. How can I do this? Thanks! -
Link JavaScript Button to Django Form
I have a JavaScript Function for showing fullcalendar. There I added a custom button (addEventButton) for adding new events: $('#calendar').fullCalendar({ header: { center: 'addEventButton', }, events: '/schedule/api/occurrences?calendar_slug=calendar', customButtons: { addEventButton: { text: '+', click: function() { var dateStr = prompt('Enter a date in YYYY-MM-DD format'); var date = moment(dateStr); if (date.isValid()) { $('#calendar').fullCalendar('renderEvent', { title: 'dynamic event', start: date, allDay: true }); } } } }); To get this new events into my django-model, where all events are stored, I've made a forms.py: class create_calendar_event(forms.Form): Title = ModelChoiceField(label='Title', queryset=Title.objects.all()) INPUT_FORMATS = ['%Y-%m-%d %H:%M'] start = forms.DateTimeField(input_formats=INPUT_FORMATS, widget=forms.DateTimeInput()) end = get_end_time(start) calendar = ModelChoiceField(label='Calendar', queryset=Calendar.objects.all()) How can I link this create_calendar_event form into the JavaScript addEventButton? -
How to query the number unique relations in Django
I have difficulties to create a more complex model query in Django. My model structure looks like this: date 1 - n cases case n - 1 employee employee n - 1 company What I want is to query the number of unique 'companies' used in all 'cases' at a specific 'date' (for other reasons 'date' is its own model in this case) in a method of the date model. -
Combining Ember REST Adapter with Django rest_framework ModelViewSet
I am creating an application that uses Ember and Django. For the backend of Django do I use rest_framework with the ModelViewSet as my view class. In the frontend with Ember do I use the RESTAdapter. My backend sends data back like this: { "id": 22, "name": "test", "startdate": "2019-01-01", "enddate": "2018-12-26" } while my frontend expects it like this: { "appointment": { "id": 1, "name": "test", "startdate": "2019-01-01", "enddate": "2018-12-26" } } I can't figure out how to make either end conform the other end in a nice and clean way. In the Django view class could I do this: def list(self, request): """Send all appointments.""" serializer = AppointmentSerializer(self.queryset, many=True) return Response({'appointment': serializer.data}) and it would work to get the appointments, but then I would have to alter all the functions like create, update, delete etc. I feel like there has to be a clean and better maintainable way to fix this issue. -
Multiple forms on django page
Below is the view def TestPageView(request): if request.method == 'POST': contactform = ContactForm(request.POST,prefix="contact") subscriptionform = SubscriptionForm(request.POST,prefix="subscription") suggestionform = SuggestionForm(request.POST,prefix="suggestion") globalmessageform = GlobalMessageForm(request.POST,prefix="globalmessage") if contactform.is_valid() and subscriptionform.is_valid() and suggestionform.is_valid() and globalmessageform.is_valid(): contact = contactform.save() subscription = subscriptionform.save() suggestion = suggestionform.save() globalmessage = globalmessageform.save() else: print(form.errors) else: contactform = ContactForm(prefix="contact") subscriptionform = SubscriptionForm(prefix="subscription") suggestionform = SuggestionForm(prefix="suggestion") globalmessageform = GlobalMessageForm(prefix="globalmessage") return render(request,'dashboard/test_page.html',{'contactform':contactform,'subscriptionform':subscriptionform,'suggestionform':suggestionform,'globalmessageform':globalmessageform}) How to write html code to show and save these forms on test_page.html.I know how to show one form but there are 4 forms in this case. -
[DJANGO][GUNICORN] Operation not permitted
I followed this tutorial : http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ My directory structure is quite the same: -rw-r--r-- 1 django webapps 0 Nov 30 15:58 access.log drwxr-xr-x 3 django webapps 4096 Nov 30 17:27 bin -rw-r--r-- 1 django webapps 6450 Nov 30 15:58 error.log drwxr-xr-x 2 django webapps 4096 Nov 30 15:58 gunicorn drwxr-xr-x 2 django webapps 4096 Nov 30 16:10 include drwxr-xr-x 3 django webapps 4096 Nov 30 16:10 lib lrwxrwxrwx 1 django webapps 3 Nov 30 16:10 lib64 -> lib drwxr-xr-x 2 django webapps 4096 Nov 30 17:12 logs drwxr-xr-x 5 django webapps 4096 Nov 30 13:36 narcisse -rw-r--r-- 1 django webapps 59 Nov 30 16:11 pip-selfcheck.json -rw-r--r-- 1 django webapps 75 Nov 30 16:10 pyvenv.cfg -rw-r--r-- 1 django webapps 85 Nov 30 15:50 README.md drwxrwxrwx 2 django webapps 4096 Nov 30 17:51 run I have a /etc/supervisor/conf.d/filename that looks like this: [program:site] command = /var/www/site/bin/gunicorn_start -user=django user = django stdout_logfile = /var/www/site/logs/gunicorn_supervisor.log redirect_stderr = true My gunicorn_start is located inside /var/www/site/bin ()and looks like this: NAME="api" DJANGODIR=/var/www/site/site SOCKFILE=/var/www/site/run/gunicorn.sock USER=django GROUP=webapps NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=api.settings DJANGO_WSGI_MODULE=api.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname … -
data acquisition optimization
There are a lot of records in the table(450k records), how can I get them faster than in this way? def index(request): params = Parameters.objects.all() return render(request, "core/data_table.html", {"params": params}) I bring in the table on html {% extends 'base.html' %} {% block content %} <html> <body> {% if params.count > 0 %} <h2>Data</h2> <table> <tr><th>Id</th><th>par_time</th><th>par_recipe</th><th>par_machine</th><th>par_fa</th><th>par_ag_typ</th><th>par_rollennr</th> <th>par_def_id</th><th>par_name</th><th>par_value</th></tr> {% for person in params %} <tr><td>{{ params.id }}</td><td>{{ params.par_time }}</td><td>{{ params.par_recipe }}</td><td>{{ params.par_machine }}</td> <td>{{ params.par_fa }}</td><td>{{ params.par_ag_typ }}</td><td>{{ params.par_rollennr }}</td><td>{{ params.par_def_id }}</td> <td>{{ params.par_name }}</td><td>{{ params.par_value }}</td></tr> {% endfor %} </table> {% endif %} </body> </html> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django: Validate GET request
I have written a few simple API endpoints (without Django REST). I have problems figuring out how to validate the input data. class CarTypeForm(forms.Form): car_type= forms.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(6)], required=False ) def car_data_as_json(request): """ API Endpoint """ # Receive and validate variables from get request car_type= request.GET.get("car_type", 0) car_type_form = CarTypeForm() car_type_form.car_type = int(car_type) if car_type_form.is_valid(): do something return JsonResponse(something) else: return JsonResponse({'err': 'invalid car_type'}, status=400) I don't understand why if car_type_form.is_valid(): is not True despite the value being 5 for example. I'm using Django 2.1 -
Django TypeError at /signup/ create_user() missing 1 required positional argument: 'username'
I am doing according to the django's docs which say if you are using a custom models which defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django’s default user, you can just install Django’s UserManager, My intentions are i do not want to use username for creating a user, i want to use but an email so when i do that i keep getting this error "TypeError at /signup/ create_user() missing 1 required positional argument: 'username'". here is my code models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager class User(AbstractBaseUser): email = models.EmailField(unique=True, blank=False) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = UserManager() views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): if form.cleaned_data['password'] != form.cleaned_data['repeat_password']: context['form'] = SignUpForm(request.POST) context['error'] = 'Passwords did not match' return render(request, 'shopapp/signup.html', context) else: # Creating the user here email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = User.objects.create_user(email=email) user.set_password(password) return HttpResponse('{} {}'.format('User created succesfully', User.objects.all())) return HttpResponse('Form is not ok') else: form = SignUpForm() context['title'] = 'Signup' context['form'] = form return render(request, 'shopapp/signup.html', context) -
Django doesn't recongnize Gensim
I'm using Python, Django, IDE PyCharm. I imported Gensim for my project, however, seems like Django does not recognize it. Here are my versions: gensim-3.6.0 numpy-1.15.4 scipy-1.1.0 The following error is: Traceback (most recent call last): File "C:/Users/Me/PycharmProjects/sma-capstone-2018/sma_core/brinfluence/lib/doc2vec.py", line 4, in <module> import gensim File "C:\Users\Me\venv\lib\site-packages\gensim\__init__.py", line 5, in <module> from gensim import parsing, corpora, matutils, interfaces, models, similarities, summarization, utils # noqa:F401 File "C:\Users\Me\venv\lib\site-packages\gensim\parsing\__init__.py", line 4, in <module> from .preprocessing import (remove_stopwords, strip_punctuation, strip_punctuation2, # noqa:F401 File "C:\Users\Me\venv\lib\site-packages\gensim\parsing\preprocessing.py", line 40, in <module> from gensim import utils File "C:\Users\Me\venv\lib\site-packages\gensim\utils.py", line 40, in <module> import scipy.sparse File "C:\Users\Me\venv\lib\site-packages\scipy\sparse\__init__.py", line 229, in <module> from .csr import * File "C:\Users\Me\venv\lib\site-packages\scipy\sparse\csr.py", line 15, in <module> from ._sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \ ImportError: DLL load failed: The specified module could not be found. -
save extra field values into the database from django signup page
I manage to get a extra field (state name) on Sign-Up page (using forms.ModelForm) but I am struggling to save it in the database. I have 2 database connections, the default database is to keep Django tables and project_db to keep program tables wondering if this is causing the issues? or with forms.py file. below is forms.py file. class UsersRegisterForm(forms.ModelForm): class Meta: model = User fields = [ "username", "state_name", "email", "confirm_email", "password", ] username = forms.CharField() state_name = forms.ModelChoiceField(queryset=SchPartneredStates.objects.all(),empty_label=None) email = forms.EmailField(label="Email") confirm_email = forms.EmailField(label="Confirm Email") password = forms.CharField(widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(UsersRegisterForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({ 'class': 'form-control', "name": "username"}) self.fields['state_name'].widget.attrs.update({ 'class': 'form-control', "name": "state_name"}) self.fields['email'].widget.attrs.update({ 'class': 'form-control', "name": "email"}) self.fields['confirm_email'].widget.attrs.update({ 'class': 'form-control', "name": "confirm_email"}) self.fields['password'].widget.attrs.update({ 'class': 'form-control', "name": "password"}) def clean(self, *args, **keyargs): email = self.cleaned_data.get("email") confirm_email = self.cleaned_data.get("confirm_email") username = self.cleaned_data.get("username") state_name = self.cleaned_data.get("state_name") password = self.cleaned_data.get("password") if email != confirm_email: raise forms.ValidationError("Email must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError("Email is already registered") username_qs = User.objects.filter(username=username) if username_qs.exists(): raise forms.ValidationError("User with this username already registered") if len(password) < 8: # you can add more validations for password raise forms.ValidationError("Password must be greater than 8 characters") return super(UsersRegisterForm, self).clean(*args, **keyargs)