Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create Django context from dictionaries made from Postgres database
I'm new to Django. I'm using Mezzanine 4.2.3 (Django 1.10.8 under the hood according to requirements.txt). I have a Postgres database of details about movies. I want to display 10 movies on a page. I tried asking about this method but couldn't get a suitable solution, so now I'm trying to to write my own SQL query. But, I don't know how to create the context. In the code below, I first randomly collect ten countries from a list of countries. Next, I iterate over the list and use each country to acquire a row in a Postgres database. Then, I make a dictionary from each row and become stuck at trying to make the context for the template. import psycopg2 from psycopg2 import sql from .countries import countries # Just a Python list of countries import random class MoviesListView(generic.ListView): model = Movies connection = psycopg2.connect([DB DETAILS]) c = connection.cursor() def get_context_data(self, **kwargs): random_countries = [] while len(random_countries) < 10: choice = random.choice(countries) if choice not in random_countries: random_countries.append(choice.lower()) else: pass for country in random_countries: get_rows = "SELECT * FROM movies WHERE LOWER(production_countries) LIKE %s LIMIT 1;" c.execute(get_rows, ('%' + country + '%',)) rows = c.fetchall() for i in rows: … -
Images on my django website are rotated incorrectly on desktop site, but are correct on mobile site
I have a django project, which is a blog website which has text and images. The images, which are a mix of GoPro and iphone 5s jpgs, on my mac are rotated the correct way up, but when I upload them to my django-admin panel, many of them are rotated 90 degrees. However, when I load the website (which is hosted) on my mobile phone, they appear correctly rotated! I have no responsive behaviour in my css as of yet, and I can confirm this when re-sizing my desktop browser, the images don't rotate when I shrink the window. I also downloaded imageoptim for the mac, to remove EXIF meta data to see if that would work, but it doesn't. Does anyone have any suggestions? I'm not sure which part of my code to post, but I am using CKeditor to upload images to the django-admin panel. Many thanks. -
How can I use is_authenticated() in django to redirect user to their own page?
I am a beginner in django framework. I would to make my website to redirect users to the personal page if they already logged at the time they request the homepage like many websites. -
disable spinning icon when the page is loading
I am working on transferring web page using Django, I intend to disable the spinning wheel icon on the tab when my page is loading. How could I fix it with the original icon? Thanks. <head> <link rel="shortcut icon" type="image/x-icon" href="/static/browsericon/cloud-icon-04.png" > </head> Spinning wheel on the tab_Google Chrome static icon on the tab -
how to exclude a password validator
I created a custom password validator called 'NoUsername' which I put in the settings file under the 'AUTH_PASSWORD_VALIDATORS'. If I'm using validate_password() to validate the password the user entered, how do I exclude my custom 'NoUsername'? Thanks. https://docs.djangoproject.com/en/2.0/topics/auth/passwords/#django.contrib.auth.password_validation.validate_password The reason is because I want to use 'NoUserName' for registering but not for changing passwords. -
Transfering from Database to django dropbox
I am trying to fill a dropbox with values from my database using Django and HTML. I have been trying to figure out how for hours but it is not updating. Here is the HTML code: <select id = "classChoice" > <option value = "base"> ----- </option> {% for class.name in objectlist %} <option value = "class.name"> {{ class.name }} </option> {% endfor %} </select> Here is the forms.py: class searchPageForm(forms.Form): className = forms.ModelChoiceField(queryset= Classroom.objects.all()) studentName = forms.CharField(max_length=120) studentID = forms.CharField(max_length=20) Here is the views.py: def search(request): form = searchPageForm() if request.GET.get('class.name'): featured_filter = request.GET.get('class.name') objectlist = searchPageForm.objects.all() return render(request, 'pollingSite/search.html', {'objectlist': objectlist}) else: classNames = Classroom.objects.filter(instructor = request.user) return render(request, 'pollingSite/search.html', locals()) I am stuck and have tried everything and it's just not populating. -
Django URL with parameters not working
I'm trying to use pass a parameter to a URL in Django, but I keep getting this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/%7B%25%20url%20review%20review_id%3D3%20%25%7D Using the URLconf defined in soundclinic.urls, Django tried these URL patterns, in this order: [name='index'] login/ [name='login'] register/ [name='register'] create_user [name='create_user'] <int:review_id>/review/ [name='review'] admin/ main/ The current path, {% url review review_id=3 %}, didn't match any of these. The link I am follow has a tag like above: {% url review review_id=3 %} I'm not sure what I'm not including right, as it looks like I'm writing out the url tag correctly and urls.py seems to be configured correcely as well. Manually entering in the URL calls the correct views.py function, so it only has to do with my urls.py file. -
Valuerror in admin form
Following is my model and form: models.py class Employee(models.Model): id = models.PositiveIntegerField(primary_key=True, verbose_name='Employee Code') name = models.CharField(max_length=200, verbose_name='Employee Name') def get_names(self): return Employee.objects.values_list('name', 'name') class JobQueue(models.Model): emp_name = models.ForeignKey(Employee, on_delete=models.CASCADE) product_code = models.ManyToManyField(Product) forms.py class JobQueueForm(forms.ModelForm): emp = Employee() prod = Product() emp_name = forms.ChoiceField(choices = emp.get_names) product_code = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=prod.get_products) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') When I try to add new employee from JobQueue form, I get the following error: ValueError at /admin/timesheet/jobqueue/add/ Cannot assign "'some_name'": "JobQueue.emp_name" must be a "Employee" instance. Any idea what I am doing wrong here? -
Testing django with mongoengine
I have a django project, defautly testing on Django only works on sql database, but I need to work on mongodb and mongoengine. I use Django 1.9, mongoengine 0.9 cause it supports django. I follow the docs here https://mongoengine.readthedocs.io/en/v0.9.0/django.html and django docs for test https://docs.djangoproject.com/en/1.8/topics/testing/tools/ The problem is how I can config the test file to tell it I want to use mongodb database. Without any setup, the test file look like this: import unittest from django.test import Client from .models import User from mongoengine.django.shortcuts import get_document_or_404 class UserTests(unittest.TestCase): def setUp(self): self.client = Client() def test_create_user(self): self.client.post('/users/', {'first_name': 'aaa', 'last_name': 'bbb', 'username': 'xxx', 'email': 'abc@gmail.com'}) new_user = get_document_or_404(User, username='xxx') self.assertIsNotNone(new_user) The error when run python manage.py test will be: mongoengine.connection.ConnectionError: Cannot connect to database default : False is not a read preference. -
How to display Image from ImageField in Django to user?
I am trying to display an image from an imagefield in Django. The imagefield works correctly. I can save an image to local storage, but the problem is that when the server is running, I see a url in the place of the imagefield. I'm guessing it should be a url to the image, but when I click on it, it just reloads the current page. How can I make it so that when I click on it, I am taken to a page with the image? This is how I have tried doing it, but it doesn't work: #views.py class CreateView(generics.ListCreateAPIView): """This class defines the create behaviour of our REST Api""" queryset = BucketList.objects.all() serializer_class = BucketListSerializerPostOnly def perform_create(self, serializer): """Save post data when creating a new bucketlist""" serializer.save() class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This Class handles the http GET, PUT, and DELETE requests""" queryset = BucketList.objects.all() serializer_class = BucketListSerializer # shows image in a new tab? def show_image(request, img): context = { 'image': img } return render(request, 'images.html', context) # my html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img src="/media/documents/{{ image }}"> <a href="/">Go Back</a> </body> </html> # urls.py urlpatterns = [ url(r'^bucketlist/$', CreateView.as_view(), name='create'), url(r'^', … -
Return ID from django template language
HTML (django template language) {% if todo_array %} <ul> {% for TodoList in todo_array %} <li class="listItems" name="listItem" id="item{{ forloop.counter }}"> {{ TodoList.todo_text }} </li> {% endfor %} </ul> {% else %} <p> Add some Todo's !! </p> {% endif %} I want to return the ID of the list objects on click. How can I do this? -
How can I run this Django Server with gunicorn?
I'm trying to run my Django app with the Gunicorn web server. But I'm having difficulty doing so. My directory structure looks like this: $ pwd /Users/my_user/my_django_project $ ls -R ./MySite: __init__.py migration_settings.py urls.py local_settings.py settings.py wsgi.py ./app1: <blah> <blah> <blah> ./app2: <blah> <blah> <blah> ./app3: <blah> <blah> <blah> This is how I run the Django test server, it works: $ ./manage.py runserver --settings=MySite.local_settings 0.0.0.0:8000 How do I run the same server with gunicorn instead of ./manage.py? Everything I have seen indicates I should do the following. But as you can see, it gives me an error: $ pwd /Users/my_user/my_django_project $ gunicorn -v gunicorn (version 19.7.1) $ DJANGO_SETTINGS_MODULE=MySite.local_settings gunicorn MySite.wsgi:application --log-file=- [2018-02-21 19:26:01 -0500] [9038] [INFO] Starting gunicorn 19.7.1 [2018-02-21 19:26:01 -0500] [9038] [INFO] Listening at: http://127.0.0.1:8000 (9038) [2018-02-21 19:26:01 -0500] [9038] [INFO] Using worker: sync [2018-02-21 19:26:01 -0500] [9041] [INFO] Booting worker with pid: 9041 [2018-02-21 19:26:01 -0500] [9041] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Python/2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/Library/Python/2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/Library/Python/2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() … -
How to properly convert value for display and back in a custom field?
I have a model with an integer field that I want to display as a series of checkboxes correponding to the binary form of the number and then convert back to integer for DB storage. I thought that this could be accomplished using to_python and prepare_value, so I wrote the following: class WeekdayFField(forms.IntegerField): @staticmethod def factorize(x): powers = [] i = 1 while i <= x: if i & x: powers.append(i) i <<= 1 return powers WEEK_DAYS = [(2 ** i, x) for i, x in enumerate(['Mo', 'Tu', 'Wd', 'Th', 'Fr', 'Sa', 'Sn'])] widget = forms.CheckboxSelectMultiple(choices=WEEK_DAYS) def to_python(self, value): cleaned_data = [int(i) for i in value] return sum(cleaned_data) or 0 def prepare_value(self, value): return self.factorize(super().prepare_value(value)) This works fine for valid forms, but when an invalid form is redisplayed, for some reason the factorized list gets run through prepare_value once more, throwing an error. What's the proper way to do this? -
Is a view required to use ajax?
I'm migrating a site to django, and part of that is some ajax calls to php scripts. All I keep getting back from my ajax calls are the contents of the php file, not the results of the script being executed. Not sure if this is because I'm only using the django dev server (project not in a folder processed by apache) or if I need url.py and views.py entries for the ajax call... My ajax call from my js file: function getLab(labId) { let data = new Object(); data['ID'] = labId; $.ajax({ url: "/static/php/fetchLab.php", type: "get", data: data, success: getLabFinish }); } And the response is the contents of the php file: <?php require('/static/php/log.php'); require('/static/php/config.php'); $log = new Log(); ... -
Install libmagickwand-dev on Google App Engine Flexible - Django
I'm trying to deploy an application on GAE Flexible and this error keeps coming up. ImportError at / MagickWand shared library not found. You probably had not installed ImageMagick library. Try to install: apt-get install libmagickwand-dev Locally everything works fine, I've installed wand on my virtual env: pip install wand In my requirements.txt I've placed wand and the other libraries I am using. On the prompts logs, after use the command gcloud app deploy, one of the logs confirms that the library is sucessfully instaled: Step #1: Sucessfully installed Django-1.11.8 .....(other libraries).. wand-0.4.4 wheel-0.30.0 I've already tried to use other versions of wand, until version wand-0.3.5 Still got the same error. Is there anyway to acess the GAE terminal to instal the libmagickwand-dev? -
Django: Using multiple fields from a ForeignKey in a ModelForm
I have the following models: class DailyTracking(models.Model): day = models.CharField(max_length=10, choices=settings.WEEKDAYS) points = models.IntegerField() arrived = models.TimeField() class BehaviourTracking(models.Model): week = models.IntegerField(choices=settings.WEEK_CHOICES) term = models.IntegerField(choices=settings.TERM_CHOICES) monday = models.ForeignKey(DailyTracking, related_name='monday', on_delete=models.CASCADE) tuesday = models.ForeignKey(DailyTracking, related_name='tuesday', on_delete=models.CASCADE) wednesday = models.ForeignKey(DailyTracking, related_name='wednesday', on_delete=models.CASCADE) thursday = models.ForeignKey(DailyTracking, related_name='thursday', on_delete=models.CASCADE) friday = models.ForeignKey(DailyTracking, related_name='friday', on_delete=models.CASCADE) I'm trying to display this in a CreateView: class TrackingView(generic.CreateView): template_name = 'tracking.html' form_class = forms.BehaviourTrackingForm using a ModelForm: class BehaviourTrackingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BehaviourTrackingForm, self ).__init__(*args, **kwargs) class Meta: model = models.BehaviourTracking My desired output would be to have the form having all the fields of the BehaviourTracking model, where the monday to friday fields are displayed as multiple form fields containing the model fields from DailyTracking. For example: <form> <input type='select' name='week'> <option>1</option> ... <option>n</option> </input> <input type='select' name='year'> <option>2018</option> ... <option>n</option> </input> <!-- Start of DailyTracking fields --> <label>Monday</label> <input type='select' name='day'> <option>1</option> ... <option>n</option> </input> <input type='number' name='points'></input> <input type='time' name='arrived'></input> ... <label>Friday</label> <input type='select' name='day'> <option>1</option> ... <option>n</option> </input> <input type='number' name='points'></input> <input type='time' name='arrived'></input> </form> However, at the moment The monday to friday fields are just being displayed as a dropdown with no options. I thought I may be able to use a … -
Django - Select only specific rows from a query
I've started to learn django and as my first project I am trying to create a catalog. I created 3 tables Students Catalog Link table between those 2 This is how my models.py looks like: class Catalog(models.Model): Class = models.CharField(max_length =30) def __str__(self): return str(self.Class) class StudentiAn4(models.Model): Username = models.ForeignKey(User) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Group = models.CharField(max_length=4) def __str__(self): return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName class CatalogStudenti(models.Model): catalog = models.ForeignKey(Catalog) student = models.ForeignKey(StudentiAn4) grade = models.IntegerField() def __str__(self): return str(self.catalog) +' ' + str(self.student) In views : def studenti(request): query = CatalogStudenti.objects.all() return render(request, 'users/Studenti.html',{'query': query}) As a logged in user(Username: 123, FirstName: test1, LastName: test1_LN), I would like to see only grades assigned to me, not all grades. Can you please tell me how can I filter the output so that I see only the grades assigned to me? Current output: 123 test1 test1_LN - SEP 5 234 test2 test2_LN - ASC 4 123 test1 test1_LN - AACEP 6 Desired Output: 123 test1 test1_LN - SEP 5 123 test1 test1_LN - AACEP 6 -
Django 'Column 'user_id' cannot be null'
Please help me resolve this issue. I'm starting to learn Django. Please tell me where the error. I was looking for similar problems, but I did not find a solution. Thanks views def register(request): args = {} args['forms'] = SignUpForm() args['form1'] = ImagefieldForm() if request.POST: newuser_form = SignUpForm(request.POST) image_field_form = ImagefieldForm(request.POST, request.FILES) if newuser_form.is_valid() and image_field_form.is_valid(): user = newuser_form.save(commit=False) user.is_active = False user.save() print ('User saved') image_field_form.save() current_site = get_current_site(request) mail_subject = 'Welcome to site' message = render_to_string('login_app/please_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = newuser_form.cleaned_data.get('username') email = EmailMessage( mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please check your email') else: args['forms'] = newuser_form return render(request, 'login_app/registration.html', args) forms class ImagefieldForm(forms.ModelForm): avatar = forms.ImageField(required=True) class Meta: model = Profile fields = ('avatar', ) models class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='images/users', blank=False) -
How to Upgrade Pinax for Django 2.0
I am trying to upgrade my django project to Django 2.0, and I have read the release notes and read several blog posts about what to change, but nothing addresses my problem so far, which relates to the package pinax: File "/Users/marlo/miniconda3/envs/project/lib/python3.6/site- packages/pinax/eventlog/models.py", line 13, in class Log(models.Model): File "/Users/marlo/miniconda3/envs/project/lib/python3.6/site-packages/pinax/eventlog/models.py", line 22, in Log content_type = models.ForeignKey(ContentType, null=True) TypeError: __init__() missing 1 required positional argument: 'on_delete' Are there any fixes for this yet? -
Clicking 'Make public' on my S3 Bucket doesn't do anything
Here is the image of me clicking 'Make Public' on one of my images in my bucket: and then subsequently clicking 'Make public' on the pop-up window: It says it completed successfully - however when I refresh the page it still gives me the option to 'Make public' so it appears it didn't work. When I go to my website the image still doesn't show up, further showing the image is still not public. This is the src the img uses on my website: https://postr-bucket.s3.amazonaws.com/static/images/settingsIcon.png?Expires=1519249290&Signature=9eixuWMxLknf%2BAnDB1XIS30ntO8%3D&AWSAccessKeyId=AKIAIDO3PF5Y7SMSOHHA I don't think the access key should be in that src, but I'm not sure how to change it. My settings for AWS are normal: from decouple import config import datetime AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY") AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'draft1.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'draft1.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'postr-bucket' S3DIRECT_REGION = 'us-west-2' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } I've also tried the same 'Make public' … -
Time passed to celery beat schedule from model object
I wonder how can I pass the time from the model object to the celery beat schedule in settings.py? Do I need to import the model in settings.py and iterate over all objects? model.py class Note(models.Model): user = models.ForeignKey(User, related_name='notes') status = models.TextField(max_length=500) publish_time = models.DateTimeField() is_publish = models.BooleanField(default=False) Task in my app: @task() def task_number_one(): // do something return something celery part in settings.py CELERY_BROKER_URL = 'amqp://localhost' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'noteapp.tasks.task_number_one', 'schedule': crontab(minute=put here min from model, hour=put here hour from model), }, } -
Django url parameters in html code
I am trying to pass the id of a todolist item to my html code so that everything works when I am editing the todolist item and I click submit. #views.py def edit(request, id): todo = Todo.objects.get(id=id) context = { 'todo': todo } if(request.method == 'POST'): title = request.POST['title'] text = request.POST['text'] todo.title = title todo.text = text todo.save() return redirect('/todos') else: return render(request, 'edit.html', context) #urls.py url(r'^details/(?P<id>\w{0,50})/edit/$', views.edit, name='edit') #my html code <h2>Edit Todo- {{ todo.title }}</h2> <form action="{% url 'edit' request.todo.id %}" method="post"> {% csrf_token %} <label for="title">Title</label> <br/> <input type="text" name="title" id="title"/> <br> <label for="text">Text</label> <br/> <textarea type="text" name="text" id="text"></textarea> <br><br> <input type="submit" value="Submit"/> </form> I think the problem is in my url in the html code. I can't figure out how to pass my todolist item's id parameter. The error I keep getting is invalid literal for int() with base 10: '' Please help -
django 2.0 Having Issue about MySql and Login check & redirect
I dedicated to learn django & python , I have decided to develop a social media platform using Django 2.0.So far I have made some progress.I have connected phpMyAdmin to settings.py.I can make user registration and keep them in my database.So far so good.When it comes to log and redirect them to my home.html , problem starts. I have followed range of tutorials to solve it but couldnt manage to do it with my lack of knowledge.Iam going to share my code below.I believe it is most basic thing sorry about it im just new lerner. Please i would preciate any little tiny info about my questions.Iam so confused , i need to understand these basics to go further. Views.py Problem: This code has some problems. It does not redirects after submit button.I also figured that I ommitted MySQLdb , query.execute basically all but log(request,email,password) and return HttpResponseRedirect section code still working ? Do i not need to connect db ? since i already set connect settings in settings.py.If so i check if user and password matchs in my db with if(query.execute("SELECT * FROM landingapp_user WHERE email = '" + email + "' AND password = '" + password + … -
Add new form prepopulated with data in Django's admin
How can you go about adding an "add new" button that prepopulates with data from an existing object within Django's admin for a given model? -
Django Model Instance as Hashable List
We have sales data for a number of brands retrieved from a remote server in JSON. Each brand has a unique API key and password. These are stored and decoupled in settings.py. Each brand is matched to its API key and password according to the below dictionary. How do we create a hashable list of brands based on the 'brand' model instance? brand = models.CharField(max_length=140, default='') brands = WHAT DO WE PUT HERE? api_key = { "BRAND1": settings.BRAND1_API_KEY, "BRAND2": settings.BRAND2_API_KEY, } password = { "BRAND1": settings.BRAND1_PASSWORD, "BRAND2": settings.BRAND2_PASSWORD, } orders_url = 'https://{}:{}@site.com/admin/orders/count.json'.format(api_key[brands],password[brands])