Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SyntaxError: trailing comma not allowed without surrounding parentheses
this is the full error: File "/Users/naderabouezze/Desktop/django projects/bff/friends/views.py", line 1 from django.shortcuts import render, redirect, ^ SyntaxError: trailing comma not allowed without surrounding parentheses this is the view file: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from django.contrib import auth from groups.models import Group from posts.models import Post # Create your views here. def home(request): return render(request, 'accounts/home.html') def signup(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: try: User.objects.get(username=request.POST['username']) return render(request, 'accounts/signup.html', {'error': "An account with this username already exists"}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) auth.login(request, user) return redirect('groups:index') else: return render(request, 'accounts/signup.html', {'error':'The passwords do not match'}) else: return render(request, 'accounts/signup.html') def login(request): if request.method == 'POST': user = auth.authenticate(username=request.POST['username'], password=request.POST['password1']) if user is not None: auth.login(request, user) return redirect('groups:index') else: return render(request, 'accounts/login.html', {'error':"An account with this information does not exist"}) else: return render(request, 'accounts/login.html') def logout(request): if request.method == 'POST': auth.logout(request) return redirect('accounts:login') def profile(request, user_id): user = get_object_or_404(User, pk=user_id) groups = user.group_set.all() posts = Post.objects.filter(author=user) friends = Friend.objects.get(current_user=request.user) return render(request, 'accounts/profile.html', {'user':user, 'groups':groups, 'posts':posts}) doesnt seem to me like there are any problems with the imports this error just popped up randomly. I hadent changed anything in the imports and they … -
Django: Connection refused after switching to MySQL
I'm working on my first Django project and I kept hitting the limits of sqlite. So I decided to switch to MySQL before adding lots of additional test data. Ever since no page in my Django app loads anymore (neither the admin nor the project pages). I get no error message until Chrome eventually displays "ERR_CONNECTION_REFUSED". I added the following to my settings: 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'my.cnf'), }, The project uses Celery, so I also modified the Celery result backend: CELERY_RESULT_BACKEND = 'db+mysql://user:password@localhost:3306/dbname' Django can connect to the database (see tests like this one: how can I check database connection to mysql in django). I migrated my content according the the second answer to this question: What's the best way to migrate a Django DB from SQLite to MySQL? without any errors. All data are present in phpMyAdmin. There's nothing in the MySQL error log. Neither Django nor Celery outputs any error in the debug console/command line. I installed mysqlclient and (for Celery) SQLAlchemy. Switching back the the original sqlite configuration remedies the problem, so it's definitely linked to the MySQL db. What am I … -
Sorting images by height/orientation
I made image gallery with grid view, but I don't like the way that rows look like - vertical photos disrupt everything. As I don't want to manually change images order I'm looking for a way to sort them automaticaly by image height or just image orientation, so vertical photos go to the bottom in one row. Thats how my model in Django looks like: class Photo(models.Model): title = models.CharField(max_length=150) image = models.ImageField() description = models.TextField(blank=True) category = models.IntegerField(choices=CATEGORIES) published = models.DateTimeField(default=timezone.now) def __str__(self): return self.title Here is my grid_view: def photos_grid(request): global cat_list photos = Photo.objects.order_by('published') output = {'photos': photos, 'categories': cat_list,} return render(request, 'photos/photos_grid.html', output) I tried that (how to find height and width of image for FileField Django) way of getting image dimensions but I got "ValueError: invalid literal for int() with base 10: 'height'" every way I try to put it in my code. Other idea (by getting manually dimensions in views.py) works, but I can't put it together with my photos on the list so it get sorted. -
How to get request.user in a @classmethod Django?
I want to get request.user in a @classmethod Django. I've tried many ways but not successfully. Please help me. class Group(models.Model): name = models.CharField() .... @classmethod def get_user_request_id(self, x, y): if x === y: return self.request.user.id else: return None Error: type object 'Group' has no attribute 'request' -
How to list models migrations from command line?
I had run makemigrations and after that migrate to apply the migration python manage.py showmigrations admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length boards [X] 0001_initial contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial How to find out models in boards from command line? -
static files in Django does not upload when I changes the app name
I ran through weird issue. I have project for website. the project is still under developing process. I am using (Django 1.11). I decided to change one app named polls into ads. I have changed all related names in setting, manage, view, templates and all other related files. also I changed the table labels from the data base(mysql). then I run the server. on chrome and safari the html page is displayed but no css file is loaded. However, on fire fox is working fine. I tried to clear all data history but nothing has changed. I made sure from the setting and path inside setting file. finally, when I disable the ads blocker on chrome and safari (css, javascript, and images all are loaded) and the page displayed as it is supposed. My question here, why is this happen ( happened after I change the app name ) while before I changed the app name, the page is loaded with css and other file even though the add blockers are on. any explain or help to solve this problem here is portion of the code from the html template: {% load staticfiles %} <link rel="stylesheet" type="text/css" href=" {% static … -
Django - conditional foreign key
I have the following 4 models in my program - User, Brand, Agency and Creator. User is a superset of Brand, Agency and Creator. A user can be a brand, agency or creator. They cannot take on more than one role. Their role is defined by the accountType property. If they are unset (i.e. 0) then no formal connection exists. How do I express this in my model? class User(models.Model): """ User model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) email = models.EmailField(max_length=255, null=True, default=None) password = models.CharField(max_length=255, null=True, default=None) ACCOUNT_CHOICE_UNSET = 0 ACCOUNT_CHOICE_BRAND = 1 ACCOUNT_CHOICE_CREATOR = 2 ACCOUNT_CHOICE_AGENCY = 3 ACCOUNT_CHOICES = ( (ACCOUNT_CHOICE_UNSET, 'Unset'), (ACCOUNT_CHOICE_BRAND, 'Brand'), (ACCOUNT_CHOICE_CREATOR, 'Creator'), (ACCOUNT_CHOICE_AGENCY, 'Agency'), ) account_id = models.ForeignKey(Brand) account_type = models.IntegerField(choices=ACCOUNT_CHOICES, default=ACCOUNT_CHOICE_UNSET) class Meta: verbose_name_plural = "Users" def __str__(self): return "%s" % self.email class Brand(models.Model): """ Brand model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255, null=True, default=None) brand = models.CharField(max_length=255, null=True, default=None) email = models.EmailField(max_length=255, null=True, default=None) phone = models.CharField(max_length=255, null=True, default=None) website = models.CharField(max_length=255, null=True, default=None) class Meta: verbose_name_plural = "Brands" def __str__(self): return "%s" % self.brand class Creator(models.Model): """ Creator model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) first_name = models.CharField(max_length=255, null=True, default=None) last_name = models.CharField(max_length=255, null=True, default=None) email … -
Django easy_thumbnails reduce database queries
I am profiling a django app with django debug toolbar. I want to reduce the number of database queries from view and rendering. For each easy_thumbnail template tag, e.g. {% thumbnail coop.logo 250x250 %} there seem to be two database calls: SELECT ••• FROM "easy_thumbnails_source" WHERE ("easy_thumbnails_source"."name" = 'partner-logo/151119_Airlines_Logo_PNG.png' AND "easy_thumbnails_source"."storage_hash" = 'c536f7b8a65dd208e93ec823d3bce653') Duplicated 36 times. SELECT ••• FROM "easy_thumbnails_thumbnail" WHERE ("easy_thumbnails_thumbnail"."name" = 'partner-logo/151119_Airlines_Logo_PNG.png.250x250_q85.jpg' AND "easy_thumbnails_thumbnail"."source_id" = 1525 AND "easy_thumbnails_thumbnail"."storage_hash" = '5e4fc44a8986f46175c0675df42cf544') Duplicated 38 times. a) Why two calls? Can this be reduced? b) Why are they duplicated so many times? Is this costing me performance? -
How to export python list into the excel sheet
I will append to many data into the list like the def export_excel() all = [] all2 = [] if set=='' data = all_dataset() data.serialnumber = serialNumber data.name = name date.dob = dob data.save() all.append(data) else data = all_dataset() data.serialnumber = serialNumber data.name = name date.dob = dob data.save() all2.append(data) now i want to export these all information into the excel worksheets. how could i do this please help me out.. -
Django Rest : How to get back a base64 encoded string instead of link to the image from my serializer
I currently have something like this querySet = modelEmployee.objects.all() employeesJson = Serializer_ListEmployee(querySet,many=True).data mydict["employers"] = employeesJson; The problem with this is that value of the imageField is actually an image and I would like to get a base64 string instead.This is what the model looks like class modelEmployee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) employee_image = models.ImageField(upload_to='images/',null=True,blank=True,default='images/') employee_zip = models.IntegerField(default=0) and this is my serializer class Serializer_ListEmployee(ModelSerializer): user = Serializer_CreateOrListUser() class Meta: model = modelEmployee fields = [ 'user', 'employee_zip', 'employee_image', ] Any suggestions on how I can get back a base64 encoded string instead ? -
i want to run my django server for life long instead of running python manage.py runserver all the time
I want to run my python server for life time instead of running python manage.py runserver all the time. How can i achieve it? from django.http import HttpResponse, JsonResponse from rest_framework.views import APIView from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser I could not find solution anywhere -
Django on Pycharm community edition seems to show false-positive error message
I'm new to Django and I'm using Pycharm Community 2018.1 to do my project. While I was doing the first tutorial where you set up a model and corresponding admin page, Pycharm keeps showing this reference error which is perfectly fine when you look at the directory and the structure. Is this what I get for using free Pycharm instead of paid Professional edition? However, I know I'm a newb so I might be wrong here. Is it normal to get this error message in this situation? I took a screenshot of error message(the left screen) and working Admin page(right screen) and here are my codes for models.py and admin.py models.py (there is no problem with it) from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible # Create your models here. @python_2_unicode_compatible class Bookmark(models.Model): title = models.CharField(max_length = 100, blank = True, null = True) url = models.URLField('url', unique = True) def __str__(self): return self.title admin.py (you can see unresolved reference error) from django.contrib import admin from bookmark.models import Bookmark # Register your models here. class BookmarkAdmin(admin.ModelAdmin): list_display = ('title', 'url') admin.site.register(Bookmark, BookmarkAdmin) -
Creating a list of images
I've got a model that contains a user's profile picture as well as their information. I'm interested in obtaining a queryset of ONLY profile pictures. My idea is to get a queryset of all profiles and then add each profile image to a list IF the image exists in the profile. This isn't working. I'm getting the following error: 'NoneType' object has no attribute 'append' Can you tell me where I've gone wrong? images = UserProfile.objects.filter(user=user) validatedimages = None for image in images: if bool(image.image) == True: validatedimages = validatedimages.append(image.image) profileimages = validatedimages Thanks! -
django count data from model and show it on template
I am trying to count all the data and show it as a number on the template. here my models.py class Employee(models.Model): uid = models.CharField(max_length=100) name = models.CharField(max_length=100) def __str__(self): return self.name here my views.py class EmployeeListView(ListView): context_object_name = 'employees' model = models.Employee my employee.html <h5 class='margin-bottom'>Total Data {{ employee_set.count }}</h5> trying use _set.count but din't work. -
How Do I Create, Manage & Validate Sessions For Login & Profile Pages in Python With MongoDB as Database?
This question might be broad, but I have recently started using Python and MongoDB, and started building an application using Django. So, please guide me. I'm using Django, but since there is no official integration with MongoDB; I'm directly using PyMongo for database operations. Thus, my models.py file is fully empty. I'm using Django for HTTP page routing and for similar functions that do not need access to a database. My application has a /login, and a /profile page. The user logs in at the /login page, if the credentials are valid, I want the user to be redirected to /profile page and display his details like Name, Email etc. I want the user's session to be stored until the cookies in the browser are cleared or set an expiry for the session. If the user tries to access /profile page directly, I want to validate the session and redirect the user to the /login page if needed or display the details otherwise. I don't know how the HTTP sessions and cookies work. I've read the web for information, but I haven't understood clearly. I've also gone through some Stack Overflow links below, but they exactly don't fit my need. … -
Convert a queryset to json object using a serializer
I currently have a ListAPIView which basically returns back all the contents of a queryset and it works fine.Now I wanted to know if I could use the same serializer and get back exactly the same response but in a different view.I am trying to do something like this querySet = modelEmployee.objects.all() employees = Serializer_ListEmployee(querySet).data //Error However the last statement works if I pass an individual object to the queryset employees = Serializer_ListEmployee(querySet[0]).data I wanted to know if there was a way for me to simply pass in a queryset and get back a json object as the ListAPIView does -
Django get Data from api rest framwork
i want to know what is the method to get data from the api Im using django and i build an api with rest framwork now the question how to take data and also i dont wanna use ajax or something like that just django also the api is secured by only authenticated users can acces to it -
View new column conditioned on other columns in Django
With Django 1.11, I am trying to add a new column that is conditioned on other columns (as shown in the below image) and view it at front-end. This link is the closest example but I would like to implement it in Django. How can we do this? -
Django Python - Failed To Create Process When Creating New Virtual Env - The System Can Not Find The Path Specified
I just learned python framework, django. I installed django v3.6.4, the latest pip (10.0.1), and the latest virtual env (15.1.0), but when creating a new virtual env, i got this message failed to create process. The system can not find the path specified The system can not find the path specified The system can not find the path specified Please help me, what should i do ? Thanks -
access OneToOne relationships and pass to template in django
I am trying to access oneToOne relationship, but didn't work for me. according to this documentation https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/ A Restaurant can access its place: >>> r.place <Place: Demon Dogs the place> A Place can access its restaurant, if available: >>> p1.restaurant <Restaurant: Demon Dogs the restaurant> here my model.py class Employee(models.Model): idemp = models.CharField(max_length=100) name = models.CharField(max_length=100) def __str__(self): return self.name class EmployeeDetail(models.Model): nationality = models.CharField(max_length=50) employee = models.OneToOneField(Employee,on_delete=models.CASCADE,primary_key=True,) here my view.py class EmployeeListView(ListView): context_object_name = 'employees' model = models.Employee and here my employee_list.html {% for employee in employees %} <tr> <td>{{ employee.idemp }}</td> <td>{{ employee.name }}</td> <td>{{ employee.nationality }}</td> </tr> {% endfor %} run it and result only show idemp and name. did I miss something?... also I do separate table into 2 table for employee and employe details since I have access the data and will only show 4 column for the list of employee, and other ( details ) will access all column. which is better?... 1. use one table for many columns or 2. split the table into 2 or more for many columns ( like my case I split employee and employeedetails ) please explain with why and because, my brain little bit slow. Many thanks -
django create form with materialize modal
As far as I tried, I cannot get the form data or send it to the django view function through the materialize css modal. I'm just a novice in js, ajax and related. The "CreateView" action for my form is running outside, but it is required to be inside a modal and still get the benefits of using django form validation, security, and so on. I'm using Django version 1.11. The project has two applications: main that loads the main page, and library that performs actions on book objects. A book has only a title, and so there's a form defined like: library/forms.py: from django import forms from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = [ 'title', ] the project urls definition, mysite/urls.py : from django.conf.urls import url, include from django.contrib import admin from main import views as main_views urlpatterns = [ url(r'^$', main_views.home, name='home'), url(r'^books/', include('library.urls')), url(r'^admin/', admin.site.urls), ] Home view, main/views.py: from django.shortcuts import render def home(request): return render(request, 'main/home.html') main/templates/main/home.html: <html> <head> <title>A library</title> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> {% block body %} <div class="container"> <!--a class="waves-effect waves-light btn modal-trigger" href="#modal1">Create Book</a--> <a class="waves-effect waves-light … -
What does "self.for_fields" mean in Django? [duplicate]
This question already has an answer here: How to create custom model fields in django, and how does it works 1 answer I am currently taking a course about Django, and I have come across the for_fields class attribute that I am not managing to understand. I have already searched in the Django documentation, but I haven't found the answer yet. The following code is being built by the instructor, but he did not explain well about the meaning of the "for_fields" attribute. This code is in a "fields.py" file, because we are building a custom model field to automatically order new instances of a model. class OrderField(models.PositiveIntegerField): def __init__(self, for_fields=None, *args, **kwargs): self.for_fields = for_fields super(OrderField, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): if getattr(model_instance, self.attname) is None: # no current value try: qs = self.model.objects.all() if self.for_fields: query = {field: getattr(model_instance, field) for field in self.for_fields} qs = qs.filter(**query) # get the order of the last item last_item = qs.latest(self.attname) value = last_item.order + 1 except ObjectDoesNotExist: value = 0 setattr(model_instance, self.attname, value) return value else: return super(OrderField, self).pre_save(model_instance, add) What's the meaning of the for_fields attribute? What does it contain? -
Django - Register App Model in Custom AdminSite
I have a django project with three apps: website, blog, and customauth. The customauth app implements a custom user and AdminSite. The blog app has a Post model. I am trying to register the Post model with the custom AdminSite and I receive the following error: NoReverseMatch at /my_admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/my_admin/ Django Version: 2.0.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$'] Here is customauth/admin.py: class MyAdminSite(admin.AdminSite): site_title = "Custom Administration Area" site_header = 'Custom Administration Area' def get_urls(self): urls = super(MyAdminSite, self).get_urls() my_urls = [ url(r'^my_view/$', self.my_view, name='my_view'), ] return my_urls + urls def my_view(self,request): value = "You're looking at the new admin view." context = dict( # Include common variables for rendering the admin template. self.each_context(request), # Anything else you want in the context... key=value, ) return TemplateResponse(request, "website/admin.html", context) admin_site = MyAdminSite(name='myadmin') # Now register the new UserAdmin... admin_site.register(MyUser, UserAdmin) And here is blog/admin.py: from django.contrib import admin from customauth.admin import admin_site # Register your models here. from .models import Post class PostAdmin(admin.ModelAdmin): pass admin_site.register(Post,PostAdmin) What am I … -
changing the value of a queryset field after grabbed from the database from FK to FK Object django
I have a view in which I am grabbing the queryset of a model STUser this model has a FK relation to venuepermission venuepermission also has an FK relation to a model Venue I want to get the STUser venuepermission_set then iterate the set and replace the venue field with the fk with the related venue object. I did this, but it has no effect. How would this be done correctly? class VenueUserList(APIView): def get(self, request, *args, **kwargs): objects = STUser.objects.prefetch_related('venuepermissions_set').all() for item in objects: for permission in item.venuepermissions_set.all(): permission.venue = Venue.objects.get(pk=permission.venue_id) serialized = VenueUserListSerializer(objects, many=True) return Response(serialized.data) In my response I still just get the venue FK -
How to access the ‘pk’ created by ‘self.client.post() test
Here’s my test: def test_CreateEmployeeProfileView_redirect_on_success( self): response = self.client.post( reverse('service:create_employee_profile'), { 'first_name': 'Test', # Required 'middile_name': 'Testy', # Optional 'last_name': 'Testman', # Required 'employee_choices': 'E', # Required }) self.assertRedirects(response, expected_url=reverse('service:customer_employee_profile_detail', kwargs={'pk':response.pk}), status_code=302, target_status_code=200, ) I know this works if I change response.pk to 1. Is there a way to get the pk of the post object without querying it? Or does it not get a pk until after it is posted and saved?