Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python selenium in html select value option
i have this html form using django framework : <form action="" method="POST">{% csrf_token %} <select name="index" class="form-control"> {% for post in posts %} <option value="{{ post.name }}"</option> {% endfor %} </select> <input class="btn" type="submit"> </form> and i want to test it using selenium but how to can use selenium to test this html form ? i am confused at <option value="{{ post.name }}"</option> because this is dynamic. some help ? -
Django raises a page not found for all forms on shared hosting
This is my first time posting here and so, I am sorry if I am doing something wrong. So, I am a beginner in the world of hosting and web development with django. I have built a basic website and tried hosting it via shared hosting on a2hosting. There seemed to be some problems with FastCGI and they suggested to use django as a wsgi application. This was done by first, creating a virtualenv using the cpanel's setup python. Then, installing django and, using passenger, to run the project. The basic website that I created works no problem on my system. However, on the server, it seems to be having problems with pages leading from a form. (For example, it allows me to get to the django's admin site but says page not found once I try to login). So, I experimented a bit and soon realized something: I have a form with "action" url leading to something like this, examplewebsite.com/new_book. Once the form is filled and submitted, it should submit to this url. And then, it should redirect to, examplewebsite.com/books. However, the request is being made to, examplewebsite.com/new_book/books. The view function has: HttpResponseRedirect(reverse('namespace:name')) I tried removing the reverse bit … -
Getting Error in user Login in Django
When I try to log-in in this code getting some error. Django 2.0 and Python 3.6.3 views.py def user_login(request): context = RequestContext(request) if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user)#Error in this line return HttpResponseRedirect('/') else: return HttpResponse("Your account is disabled.") else: print("Invalid login details: {0}, {1}".format(username, password)) return HttpResponse("Invalid login details supplied.") else: return render(request, 'Login/login.html', context) Error in Terminal:- Internal Server Error: /user_login/ .... .... File "/home/rails/projects/DevProject/DataCraft/DataSearch/views.py", line 45, in user_login login(request, user) TypeError: 'str' object is not callable Please help me -
upload multiple image in django model from admin panel
I have this model.py file but in django admin I can't upload images...how can I upload multiple images for each product? (1 to many relationship) Models.py TYPE = (('small', 'small'), ('medium', 'medium'), ('big', 'big')) class Products(models.Model): name = models.CharField(max_length=50) category = models.CharField(max_length=50, choices=TYPE) description = models.TextField() def __unicode__(self): return self.name class Gallery(models.Model): image_name = models.TextField() image_up = models.ImageField(upload_to='prodotti/') product = models.ForeignKey(Products) def __unicode__(self): return self.image_name -
Fetching data from database Django
I am making a project using python 3.5 and Django 1.8 ,there is a feature for login and signup, so login and signup are two different apps Using view I pass the form and when I enter the credentials in the table eg checkit and 12345 (username and password) ,I get this error user not found THE ERROR= I have two tables in my project ,Users and allusers1 (see image) . The users table has records of superusers(those required to login to localhost:8000/admin) where as allusers1 table has users registered on my website.See image allusers1 has a record called checkit and 12345 as password where as users(table) doesn't have it,so what is happening is that the app is selecting records from the users table instead of allusers1 table How do I change the table? This is login/forms.py from django import forms from signup.models import allusers1 from django.contrib.auth import ( authenticate, login, logout, get_user_model, ) User=get_user_model() class UserLoginForm(forms.ModelForm): class Meta: model = allusers1 fields=['username','password'] widgets = { 'password': forms.PasswordInput(), } def clean(self ,*args,**kwargs): username=self.cleaned_data.get("username") password=self.cleaned_data.get("password") user_qs = User.objects.filter(username=username) if user_qs.count() == 0: raise forms.ValidationError("The user does not exist") else: if username and password: user = authenticate(username=username, password=password) if not user: raise … -
Heroku Internal Server Error. ParamValidationError. Invalid bucket name "": Python/Django
absolute beginner here having an absolute nightmare deploying a tiny website to Heroku. I have worked through numerous issues to get to this point, but I now seem to have hit another wall. I have raised this as a support ticket with Heroku, but unless it is an issue on their side I doubt whether they will come back to me with a clear answer. I can successfully deploy to Heroku, however, when opening up my web app I can only see the words "Internal Server Error" in place of my site. I receive an issue/error through to my Sentry log, which is as follows: MESSAGE ParamValidationError: Parameter validation failed: Invalid bucket name "": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$" EXCEPTION(most recent call first)App OnlyFullRaw ParamValidationError Parameter validation failed: Invalid bucket name "": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$" storages/backends/s3boto3.py in exists at line 478 def exists(self, name): name = self._normalize_name(self._clean_name(name)) if self.entries: return name in self.entries try: self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) return True except ClientError: return False def listdir(self, name): name 'CACHE/css/cf136be60f95.css' self <storages.backends.s3boto3.S3Boto3Storage object at 0x7fbe4b7f4e80> compressor/base.py in output_file at line 321 """ The output method that saves the content to a file and renders the appropriate template … -
Can't update django to newest version
I am a django beginner trying to set up django newest version 2.0.2 in my virtual environment. I am running python 2.7 on my mac, currently using django 1.01.It wouldn't allow me to update any other versions.When I do pip install django==2.0 Collecting django==2.0 Could not find a version that satisfies the requirement django==2.0 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, … -
Django celery beat attributeError: 'NoneType' object has no attribute 'localize'
I'm trying to get periodic tasks running with my Django project as per this tutorial. When running celery beat with the command below: celery -A proj beat -l info -S django I get the following error: celery beat v4.0.2 (latentcall) is starting. __ - ... __ - _ LocalTime -> 2018-02-24 13:42:37 Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) [2018-02-24 13:42:37,244: INFO/MainProcess] beat: Starting... [2018-02-24 13:42:37,245: INFO/MainProcess] Writing entries... [2018-02-24 13:42:37,255: CRITICAL/MainProcess] beat raised exception <type 'exceptions.AttributeError'>: AttributeError("'NoneType' object has no attribute 'localize'",) Traceback (most recent call last): File "...lib/python2.7/site-packages/celery/apps/beat.py", line 107, in start_scheduler service.start() File "...lib/python2.7/site-packages/celery/beat.py", line 528, in start humanize_seconds(self.scheduler.max_interval)) File "...lib/python2.7/site-packages/kombu/utils/objects.py", line 44, in __get__ value = obj.__dict__[self.__name__] = self.__get(obj) File "...lib/python2.7/site-packages/celery/beat.py", line 572, in scheduler return self.get_scheduler() File "...lib/python2.7/site-packages/celery/beat.py", line 567, in get_scheduler lazy=lazy, File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 183, in __init__ Scheduler.__init__(self, *args, **kwargs) File "...lib/python2.7/site-packages/celery/beat.py", line 204, in __init__ self.setup_schedule() File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 191, in setup_schedule self.install_default_entries(self.schedule) File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 290, in schedule self._schedule = self.all_as_schedule() File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 199, in all_as_schedule s[model.name] = self.Entry(model, app=self.app) File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 88, in __init__ model.last_run_at = self._default_now() File "...lib/python2.7/site-packages/django_celery_beat/schedulers.py", line 106, … -
show checkboxes based on values of previous fields checkboxes in django/js
I have this dynamic loading problem in my django project for making a worksheet by the teacher. Problem I have classrooms which have Topics, and Topics have SubTopics. I have to create a dropdown for classroom where teacher can select one class. Based on the class I am showing Topics as checkboxes so that teacher can select various topics. I have solved the issue so far. Now based on the checked topics and selected class I want to show subtopics as checkboxes to teacher. filter.html <form method="post" id="questionForm" data-topics-url="{% url 'qapp:ajax_load_classroom_topics' %}" data-subtopics-url="{url 'qapp:ajax_load_topics_subtopics'}" novalidate> {% csrf_token %} <table> {{form.as_table}} </table> <button type="submit">Submit</button> </form> <script> $("#id_classroom").change(function() { var url = $('#questionForm').attr("data-topics-url"); var classroomId = $(this).val(); $.ajax({ url: url, data: {'classroom':classroomId}, dataType: 'json', success: function(response_data) { $("#id_topic").empty().append(response_data.topics.map((t1) => { return $('<div class="checkbox"><label><input type="checkbox" name="topics_all" id="' +t1.id+"_id "+'value="' +t1.id+ '"/>' +t1.topic_name+'</label>'); })); } }); }); </script> <script> $(".checkbox").change(function(){ console.log($("#id_topic").val()); }); // --> stuck here! how to dynamically show subtopics in checkboxes </script> views.py for ajax_load_topics_subtopics url def topics_subtopics(request): classroom = request.GET.get('classroom') topics = request.GET.getlist('topics_all[]') temp_subtopics = SubTopic.objects.filter(classrooms__classroom=classroom).filter(topic__id__in=topics) subtopics = temp_subtopics.order_by('subtopic_name').values('subtopic_name', 'id') response_stopics = {} try: response_stopics['subtopics'] = list(subtopics) except: response_stopics['error'] = "No Subtopics available in this class and Topics" print(response_stopics) print('classroom', classroom) … -
Getting result of query in django view in d3
I've researched this topic for forever, but I can't seem to get there. I have a brand new Django site, with an app called dashboard. I've fed my sqlite db from Django with external data and I have a table called resource (matched to a Model Resource). I would like to be able to go to http://localhost:8000/resource/xxxxx, where xxxxx is a resource_id and see the result of a query on this particular resource_id presented on a web page (with d3.js graph built on the query result). urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('resource/<resource_id>', views.resource_profile, name='resource_profile'), path(r'api_utilization_per_resource', views.api_utilization_per_resource, name='api_utilization_per_resource'), ] I've borrowed the api trick from https://stackoverflow.com/a/26455798/1374353. views.py def resource_profile(request, resource_id): return render(request, 'dashboard/dashboard.html', { 'request': request, 'resource_id' : resource_id, }) def api_utilization_per_resource(request): resource_id = request.GET.get('resource_id') with connection.cursor() as cursor: #This is the current query that (obviously) does not include the resource_id, but the graph shows up. result = cursor.execute("SELECT tdate, period, period_utilization, year_utilization FROM timedetails_utilization WHERE gpn = 'NL01002' GROUP BY period ORDER BY period") #This is the query (I think) I need. #result = cursor.execute("SELECT tdate, period, period_utilization, year_utilization FROM timedetails_utilization WHERE gpn = %s GROUP BY period ORDER … -
Django - Slugify string and use it only in url
I have get_aboslute_url function in my model in Django. Here is my code: def get_absolute_url(self): return reverse('detail', args=[self.author.full_name, self.title]) Here is my code for detail function: def detail(request, author, title): book = get_object_or_404(Book, author__full_name=author, title=title) context = {'book': book} return render(request, 'booksreview/books_list.html', context) And here is my problem. I want to use author and title as a slug in my url. How can I do it? Thanks in advance for the help. -
Django Models- Alternative for repetitive null=True, blank=True
I have Django models with many uncompulsory fields Is there an alternative to avoid null=True and blank=True ? Is there something like blank_fields = ('email','image',) and null_fields = ('email', 'image') ? -
How to access PostgreSQL database in Django application
I have created a simple Django application which tries to access table named fruits present in PostgreSQL database and display its contents. I followed the official Django documentation and implemented below code as far as I understand. But below procedure is incomplete I believe as fruits.objects.all() is failing to fetch any data. I am missing something can anybody point it out any help would be appreciated. Table: fruits models.py from django.db import models class fruits(models.Model): ID = models.CharField(max_length=20) Name = models.CharField(max_length=20) def __str__(self): return self.Name views.py from database.models import fruits def index(request): data = fruits.objects.all() print(len(data)) for item in data: print(item) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '<database_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<host_name>', 'PORT': '', } } -
Is it possible to run a PoS Wallet on a VPS next to Django
I have a vps on digitalocean.com where i'm running a django webserver for my website. I was now thinking about investing some money in a crypto coin witch is staking. All Pos Coins i know need a 24/7 open wallet for staking. I dont want/can run my home pc 24/7. So my question: Is it possible to run this wallet on my vps next to the django webserver? And if yes, is there a high security risk? -
Django TruncMinute show timezone
I created a Django ORM query and I use TruncMinute to set seconds to zeros. Unfortunately when I run my query the result show my timezone. I attached my result with my query and I also show my desired output. My query: MyResul=MyTable.objects.all() .filter(time__range=(start_date, end_date)) .annotate(time_stamp=TruncMinute('time')) .values('data', 'time_stamp') My result: data time_stamp 1 2017-01-04 18:56:00+00:00 My attempt: .annotate(time_stamp=TruncMinute('time', tzinfo=None)) My desired output: data time_stamp 1 2017-01-04 18:56:00 -
Dynamic models' relation in Django
I've wanted to use a djago-plans application for creating and administrating plans of my project. However, there was a caveat that django-plans makes an assumption that plans are purchased by the User model. It is not a case for my project, I want a custom Company model to be associated with Plan model. Therefore, I've forked the repo and changed the code to create a dynamic relation using ForeignKey to Buyer model defined in project settings. It works as expected but now I have to generate migrations every time I install the forked app using pip. It added another step to my deployment: makemigrations. It seems to me like a bad practice. I can see a 3 ways to tackle the problem: Leave it as is. Add the django-plans app to my project so that migrations will be stored inside a project and there will be no need to generate them every deployment. The downside here is that this app won't be reusable to other projects and I was even thinking about maintaining that fork for other people to use. Use GenericRelations in Django. I don't have any experience with them and wanted to ask if they are a possible … -
What does "from exc" mean when used to raise an exception: raise ImportError("...") from exc
When looking at Django code (manage.py) I noticed that after raising an exception there is a from statement. #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) I could not find any information about this in the Python documentation for exception: https://docs.python.org/3/tutorial/errors.html. What is the purpose of the from statement and what does it do? -
Reverse for 'add_comment' with keyword arguments '{u'slug': None}' not found. 1 pattern(s) tried: [u'blog/(?P<pk>\\d+)/comment/$']
I am getting an error - Reverse for 'add_comment' with keyword arguments '{u'slug': None}' not found. 1 pattern(s) tried: [u'blog/(?P\d+)/comment/$'] I added - app_name= 'blog' - to urls to solve the earlier error of namespace but now I am stuck with a new error my urls.py url(r'^(?P<pk>\d+)/comment/$', views.add_comment, name='add_comment') my views.py def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post', slug=post.slug) else: form = CommentForm() template = 'blog/add_comment.html' context = {'form': form} return render(request, template, context) my models.py class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() date = models.DateTimeField() slug = models.SlugField(max_length=250, blank=True, null=True) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absoulte_url(self): return reverse('blog:post.html', args=[self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', blank=True, null=True) user = models.CharField(max_length=250) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.user my template add_comment.html {% extends "personal/header.html" %} {% block content %} <h1>Add new comment</h1> <form method='POST'>{% csrf_token %} {{ from.as_p }} <button type='submit'>Submit</button> </form> {% endblock %} -
Creating docx with header & footer, using HTML template in python
Currently I am using HttpResponse(content, content_type='application/doc', charset='utf-8') to generate the doc file. Can you please suggest me the way to insert the footer into the doc file generated in Python, Django. -
Modify data in Formset before validation
I'm trying to pass a Django Formset some sort of instances attribute before I parse the POST data, but there is no way to pass a variable amount of instances, depending on how many instances will be created. If I do the following, it doesn't validate (here, field is invalid if set to 2 in the model and I want to validate AFTER I correct it to 1). Is this a bug in Django? Should the validation be done at all for commit=False?: formset = forms.SimpleFormset(request.POST) context = {'formset': formset} template = loader.get_template(self.template) simple_models = formset.save(commit=False) for simple_model in simple_models: simple_model.field = 1 formset.save() If someone wants a sample project, I could upload a ZIP but I have been asked in the past not to link to external sites. -
Stuck in redirecting from listview to detailview in django
guys i am stuck in redirecting from list view to detail view of the list item that i have added.when i click on the list item it does not adds any url pattern and the site just reloads and does nothing.I want to redirect from list template to the details of that particular list item.I have added pics of my projects models,views,urls,templates for class based views in django.please help me out. And thanks in advance. I am using django.1.11 and python 3 for version info. models.py these are models views.py these are views urls.py urls list_view template list_view template detailview this is the detailview template of the project -
Django Social Auth issue with Coinbase
Im using https://github.com/python-social-auth/social-app-django to make it easy to add new oauths to my django app. I have added it to my settings files and filled in the keys. settings.py SOCIAL_AUTH_COINBASE_KEY = os.environ.get('COINBASE_ID') SOCIAL_AUTH_COINBASE_SECRET = os.environ.get('COINBASE_SECRET') AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'social_core.backends.coinbase.CoinbaseOAuth2', # for Coinbase authentication 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <- Here 'social_django.context_processors.login_redirect', # <- Here ], }, }, ] INSTALLED_APPS = [ 'user.apps.UserConfig', 'django.contrib.humanize', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] However when I see the oauth screen of coinbase, I press next, I get redirected to my redirect uri, Then it gives me an error HTTPError at /auth/complete/coinbase/ 403 Client Error: Forbidden for url: https://api.coinbase.com/v2/user I have been trying to fix this issue for hours now but I cant seem to find anything on this -
django - detect which apps are user-authored and not packages
In my project, I try to enforce logging format for apps that are not imported as packages but created within project by my fellow devs (as logs from these apps can contain user-sensitive data). For this, I created a logging.Filter that checks if the LogRecord has the name of the module and then conditionally modifies it. For example, if this is my app list (part of it): INSTALLED_APPS = [ # django-supplied 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', # third-party apps 'webpack_loader', 'django_tables2', 'django_s3_storage', # user-created apps 'nlp', 'catalog', 'broker', ] then the filter checks if the LogRecord.name starts with any of ['nlp', 'catalog', 'broker']. The question is, how do I detect user-created apps without hardcoding their names into the filter? -
boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request
i am getting this error please tell me the solution my region is mumbai boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request InvalidRequestThe authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.7BD86CC040523574I1zzUtAgjBS0dOUo/mP/Z7uei/l+f8YXEdlqeu1N+7mXrHV9IwYxWBLkx1E/y4DNm6QzPdyRihE= -
Django: Dynamic url not expanding in Template tags
I have an Ajax call which returns link to load data from. if (data.verified == 1) { var link = "{% data.target_link %}"; alert(link) $('#my-modal').load(link); } In view I set url like this: url = "url 'health:add_doctors_staff' " + doctor_id I also tried var link = data.target_link; and url = "{% url 'health:add_doctors_staff' " + doctor_id + " %}" But it is not working. It seems Django template is not able to expand the url received from Ajax. How can I fix this issue. I don't want to send expanded(partially harcoded) url from the Ajax call view. Please help