Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am using django forms , how would i create 2 dropdown such that the entry selected in first is not displayed in second
i am working on a Django project , i have a list of hostels to be displayed in 2 drop down , it should be such that the hostel selected in first is not displayed in second , how would i achieve this ? -
Can not install django via Ubuntu bash on windows
happy holidays to you :) I can not install the Django package by the python pip package manager. The installation returns an error that you can see below on the image If you want more pictures to help me, let me know Windows 10 - Ubuntu terminal Thank you, simply -
Django query set based on user subscription plan
So I'm trying to build a web app, the idea is I have data about homes all over the US, and I don't want to show all data to users, user will pay a monthly price (like a plan) based on number of states he selected when he subscribed, So How can I make my models, user models and views so that he can only see data within the states he selected ? and how can I represent these subscription plans as a model in my db ? a small hint can make difference, so please give it if you don't have time to explain with example. Thank you. -
Django Doesn't Send Email Notifications
Merry Christmas to everybody, Working on a contact form and i am not able to receive the emails from Django into my Inbox. This is my function: def contact(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): contact_name = form.cleaned_data['contact_name'] contact_phone = form.cleaned_data['contact_phone'] contact_period = form.cleaned_data['contact_period'] subject = contact_name + " | " + contact_phone + " | " + contact_period content = form.cleaned_data['content'] contact_email = form.cleaned_data['contact_email'] try: send_mail(subject,content,contact_email, ['office@cohen.ro']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "contact.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') These are my server's settings: Secure SSL/TLS Settings (Recommended) Username: office@cohen.ro Password: Use the email account’s password. Incoming Server: mail.cohen.ro IMAP Port: 993 POP3 Port: 995 Outgoing Server: mail.cohen.ro SMTP Port: 465 This is what i have in my Django settings: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'office@cohen.ro' EMAIL_HOST= 'mail.cohen.ro' EMAIL_HOST_USER= 'office@cohen.ro' EMAIl_HOST_PASSWORD='mypass' EMAIL_PORT = 465 EMAIL_USE_TLS = True In my server i can see the message, but does not send the email to my email address so i dont know if someone is asking me something. Thank you! Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: me | 0787877 | 12-13 From: test@test.com … -
about javascript _.each in django template
home-templateviews.jsIt seems that _.each does not work properly because there's no sprint items on page. And I guess it's sprints.models that leads to the problem. I can not figure out if sprints.models is list object. Please help me solve it. Thanks. -
Changing from standard sqlite to postgres database
I'm trying to change from the standard sqlite database to postgresql in my Django project. Here's what I've done so far: Installed postgresql Created a database and a user with privileges for writing to it Changing the database setting in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'workout', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } Then, when I try to migrate, this happens (warning for long error trace): (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying workoutcal.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying sessions.0001_initial... OK Applying workoutcal.0002_auto_20171215_1102... OK Applying workoutcal.0003_auto_20171215_1153...Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: multiple default values specified for column "id" of table "workoutcal_user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
Django: ManyToMany field between multiple applications
Not a long ago I have followed model: at the url /catalog1 I have application what looks like catalog with items, it have groups what have ManyToMany field to items (located at /catalog1/group, but all that inside one application. Now: I have another application /catalog2, it different but it should also have same groups, I decide to move groups on one level above (/groups instead /catalog_name/group) and I need to make ManyToMany relations to items in both catalogs. What can you suggest to me? Should I move them to different application called just Group? And how can I make relation to both catalogs? Model from current groups: class Group(models.Model): # fields for group class Item(models.Model): # other fields... groups = models.ManyToManyField(Group, related_name="groups", blank=True) Urlpattern in application: url(r'^(?:(?P<item_id>[\d]+)|(?P<item_name>[\w\d_+\-]+))/$', views.item, name='item'), url(r'^group/(?:(?P<group_id>[\d.]+)|(?P<group_name>[\w\d_+\-]+))/$', views.group, name='group'), Newer urlpattern will be without relation to catalog, so probably if it will be different application (/groups), it will look then: url(r'^(?:(?P<group_id>[\d.]+)|(?P<group_name>[\w\d_+\-]+))/$', views.group, name='group'), -
Media directory in production not working
The media directory is working as expected in my local machine but when i push the code to Heruko or cloud foundry the media is not working. How to rectify this issue? Thanks & Regards, Mohamed naveen -
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 …