Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Patch an User Model of Django with Django RF?
I have UserProfile model that contains phone, profile_photo and some fields of Django default User model like first_name, last_name, email and I am trying to update some of these fields. models.py class UserProfile(models.Model): user = models.ForeignKey(User, verbose_name="User") phone = models.CharField(max_length=16, verbose_name="Phone") profile_photo = models.ImageField(null=True, blank=True, upload_to=user_directory_path, verbose_name="Profile Photo") serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('url', 'first_name', 'last_name', 'email') class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer(partial=True) class Meta: model = UserProfile fields = '__all__' def create(self, validated_data): user_profile = UserProfile.objects.create(**validated_data) return user_profile views.py class UserProfileViewSet(viewsets.ModelViewSet): queryset = UserProfile.objects.all() serializer_class = UserProfileSerializer authentication_classes = (TokenAuthentication,) @detail_route(methods=['PATCH'], url_path='update-partial') def user_profile_update_partial(self, request, pk=None): profile = UserProfile.objects.get(id=pk) serializer = self.get_serializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) else: return Response(status=status.HTTP_400_BAD_REQUEST) If I send profile_photo, phone, first_name or last_name data with this @detail_route I am only able to update phone and profile_photo fields. Also getting Bad Request error when profile_photo data not sending. How can I implement the partial_update with PATCH method? -
Is there a easy way to get the double level related_name instances in Django Queryset?
I have three models bellow: class AModel(models.Model): name = models.CharField(max_length=11) class BModel(models.Model): name = models.CharField(max_length=11) a = models.ForeignKey(AModel, related_name="bs") class CModel(models.Model): name = models.CharField(max_length=11) b = models.ForeignKey(BModel, related_name="cs") If I have a AModel instance, if I want to get all the cmodel instances of it, I will use a forloop: c_list = [] for b in a.bs: for c in b.cs: c_list.append(c) But, whether there is a easy way to get all the cmodel instances of a? -
Django use dynamic choices in model by foreignkey
I have a model; for concern to this question it matters two field one is foreignkey to other model Plan and other is choicefield as shown below: class MyModel(models.Model): CHOICES = ( (1, 'A1'), (2, 'A2'), (3, 'B1'), (4, 'B2'), ) category = models.IntegerField(choices=CHOICES, default=3) has_plan = models.ForeignKey(Plan, on_delete=models.CASCADE) Below is my Plan model: class Plan(models.Model): PLAN_CHOICES = [(1, "Individual"), (2, "Company")] plan_name = models.IntegerField(choices=PLAN_CHOICES, default=2) plan_validity = models.IntegerField(default=180, help_text="Days after plan expires") I want to update CHOICES which are to be available in category field of MyModel depending on selection of has_plan. Consider if has_plan points to Plan object with plan_name; (2, "Company") then CHOICES are to be updated to: CHOICES = ( (1, 'A1'), (2, 'A2'), (3, 'A3'), (4, 'B1'), (5, 'B2'), ) I can achieve this in views with help of form fields but in that case I have to handle it for view and admin both hence I am looking for a better and simpler way to achieve this. I am able to raise error with clean() method in model but I want to update CHOICES instead of just raising an exception. -
Gitlab runner Docker executor does not connect to postgres service
I am successfully let runner be able to do git clone in order to install Django dependencies. Now I am solving next problem. It is Postgres My ultimate goal is pytest, but for now I will test gitlab-ci script with python manager.py test. Successfully installed appnope-0.1.0 boto3-1.4.7 botocore-1.7.47 certifi-2017.11.5 chardet-3.0.4 collectfast-0.5.2 decorator-4.1.2 django-1.11.7 django-choices-1.6.0 django-cors-headers-2.1.0 django-countries-5.0 django-debug-toolbar-1.9.1 django-dirtyfields-1.3 django-environ-0.4.4 django-extensions-1.9.7 django-filter-1.1.0 django-geoposition django-guardian-1.4.9 django-money django-reversion-2.0.10 django-s3-folder-storage-0.5 django-storages-1.6.5 djangorestframework-3.7.3 djangorestframework-jwt-1.11.0 docutils-0.14 freezegun-0.3.9 gevent-1.2.2 greenlet-0.4.12 gunicorn-19.7.1 idna-2.6 ipython-6.2.1 ipython-genutils-0.2.0 jedi-0.11.0 jmespath-0.9.3 model-mommy-1.4.0 olefile-0.44 parso-0.1.0 pexpect-4.3.0 pickleshare-0.7.4 pillow-4.3.0 prompt-toolkit-1.0.15 psycopg2-2.7.3.2 ptyprocess-0.5.2 py-1.5.2 py-moneyed-0.7.0 pygments-2.2.0 pyjwt-1.5.3 pytest-3.2.5 pytest-django-3.1.2 python-dateutil-2.6.1 pytz-2017.3 requests-2.18.4 rest-framework-generic-relations-1.1.0 s3transfer-0.1.11 simplegeneric-0.8.1 six-1.11.0 sqlparse-0.2.4 traitlets-4.3.2 typing-3.6.2 urllib3-1.22 wcwidth-0.1.7 werkzeug-0.12.2 $ python manage.py test /usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead. RuntimeWarning Creating test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, … -
Video embedding
I have a Django site that I want to add videos. Currently users can upload their photos and I want each user to be able to add their videos as well. I am not sure how to do this, since I am a beginner programmer. Can you please direct me to right way? -
I wanna make a system form's column's data is required
username&email and sex&year&month&day can be registed in my app.I wrote in views.py def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): try: username = regist_form.cleaned_data.get('username', None) email = regist_form.cleaned_data.get('email', None) user = User.objects.get(Q(username=username) | Q(email=email)) messages.warning(request, 'That detailed use is already available.') return render(request, 'registration/regist.html', context) except User.DoesNotExist: regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = regist sex = request.POST.get("sex", "") profile.sex = sex profile.save() return render(request, 'registration/detail.html') else: print(regist_form.errors) print(profile_form.errors) return render(request, 'registration/regist.html', context) in forms.py class ProfileForm(forms.ModelForm): class Meta: model = NewUser fields = ( "sex" ) in models.py class NewUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=100,null=True, blank=True, default=None) When I select sex ,write username& email and put REGIST button in browser, these data is registed.However,now if i do not select sex,the data is registed.I wanna make a system putting sex data forcibly, but current system is different.What is wrong in my code?Why is profile_form.is_valid() in views.py effective?How should i fix this? -
django to elasticsearch has no index
I want to index of django models in elasticsearch.I use the Elasticsearch DSL. I have got the log from logstash successfully, but after I post models data to ES by python manage.py search_index --rebuild, I got nothing index except logstash-* in kibana. I want to index models too. Why this happened? How to solve this? Thanks settings.py: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters':{ 'verbose':{ 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'logstash': { 'level': 'DEBUG', 'class': 'logstash.TCPLogstashHandler', 'host': 'localhost', 'port': 5959, # Default value: 5959 'version': 1, # Version of logstash event schema. Default value: 0 (for backward compatibility of the library) 'message_type': 'django', # 'type' field in logstash message. Default value: 'logstash'. 'fqdn': False, # Fully qualified domain name. Default value: false. 'tags': ['django.request'], # list of tags. Default: None. }, }, 'loggers': { 'django.request': { 'handlers': ['logstash'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['console'], 'propagate': True, }, } } documents.py: #!/usr/bin/env python # _*_ coding:utf-8 _*_ from elasticsearch_dsl.connections import connections from django_elasticsearch_dsl import DocType, Index from … -
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!