Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Simple search engine in my Django Web is not working
I'm trying to make my search go over my query my Database in Django. The lines in form.is_valid() is other forms I added to my website of adding data and it works perfect. The only thing is that query thing.. I just don't understand why after I click search I still see the all posts and not the posts I search for.. views.py- class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() query = request.GET.get("q") if query: posts = serverlist.filter(Project__icontains=query) if form.is_valid(): # Checks if validation passed post = form.save(commit=False) post.save() text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text': text} return render(request, self.template_name,args) index.html - <div class="container"> <br> <center><h1>DevOps Server List</h1></center> <br> <form method='GET' action=''> <input type='text' name='q' placeholder='Search Item'/> <input type='submit' value='Search' /> </form> <table class="table table-hover"> <thread> <tr> <th> Server Name </th> <th> Owner </th> <th> Project </th> <th> Description </th> <th> IP Address </th> <th> ILO </th> <th> Rack </th> <th> Status </th> <th> </th> </tr> </thread> <tbody> {% for server in posts %} … -
Django Raw Query with params on Table Column (SQL Injection)
I have a kinda unusual scenario but in addition to my sql parameters, I need to let the user / API define the table column too. My problem with the params here is that the query results in: SELECT device_id, time, 's0' ... instead of SELECT device_id, time, s0 ... Is there another way to do that through raw or would I need to escape the column by myself? queryset = Measurement.objects.raw("\ SELECT device_id, time, %(sensor)s FROM measurements \ WHERE device_id=%(device_id)s AND time >= to_timestamp(%(start)s) AND time <= to_timestamp(%(end)s) \ ORDER BY time ASC;", {'device_id': device_id, 'sensor': sensor, 'start': start, 'end': end}) -
How to link two tables in django?
I use build in User model in django, but i want use some custom fields, i was create new model class Profile(models.Model): user = models.OneToOneField(User) profile_img = models.ImageField(null=True) def __str__(self): return self.user.username this is my custom model. But when i create new user it doesn't display in admin(in profile table), i need to add user from admin panel, after adding it works fine. what i should to do to display Profile info of all users? p.s. When i was create table profile and was try to select info from joined tabels, sql query wasn't return anything, but after adding existed user to Profile table sql query return all what i want -
Django accessing a JSONResponse from another views file
I have two files within views directory, /views/api.py and /views/pages.py /views/api.py has methods which return JSONResponses objects Example: @api_view(['GET']) def foos(request): foos = get_list_or_404(Foo) data = [{'id': foo.id, 'name': foo.name, 'description': foo.description, 'tag': foo.tag} for foo in foos] return JsonResponse({'foos': data}) /views/pages.py will have methods that will access some of the methods from /views/api.py and add them to context and render a page. Example: def home(request): foos = api.foos(request) print foos return HttpResponse(status=200) On the line print stacks, I can see the JSONResponse object with the correct data. How do I access individual values within foos so I can create a list or a dictionary or something that is custom for each view? -
Django Doesn't Serialize id of the model
I have a simple class : class Item(models.Model): name = models.CharField(max_length=250) I need to serialize it to JSON with the ID as part of the JSON, but the ID never gets serialized when called in the view: items_json = serializers.serialize('json', item_list) The item_list json as received by the browser contains only name, not the ID. I need the ID for the processing on the client side which returns to the server later. 1) I'd like to avoid creating another ID if possible 2) I haven't created a Serializer Class. I am not sure where and how to do that. -
Django - updating application after adding rows to database?
I have a Django web application which is synced to a PostgreSQL database. After adding some rows to a couple of tables (using pgAdmin, not the Django application itself) i started experiencing some problems with the application. For example, i would get the following error in some tables: Duplicate key value violates unique constraint "some_key_pkey" DETAIL: Key (id)=736284 already exists. My assumption is that i had to let the Django application know somehow that i have added new rows to the database. Could that really be the case? If so, how can i solve it? -
Django-Postgres: how to group by DATE a datetime field with timezone enabled
I am having this problem with prostgresql and django: I have a lot of events that were created on a certain date at a certain time which is stored in a datetime field created . I want to have aggregations based on the date part of the created field. The simplest examples is: how many event are in each day of this month?. The created field is timezone aware. So the result should change depending on the timezone the user is in. For example if you created 2 events at 23:30 UTC time on 2017-10-02 if you view them from UTC-1 you should see them on 3rd of October at 00:30 and the totals should add for the 3rd. I am struggling to find a solution to this problem that works with a lot of data. So doing for each day and SQL statement is not an option. I want something that translates into: SELECT count(*) from table GROUP BY date Now I found a solution for the first part of the problem: from django.db import connection truncate_date = connection.ops.date_trunc_sql('day', 'created') queryset = queryset.extra({'day': truncate_date}) total_list = list(queryset.values('day').annotate(amount=Count('id')).order_by('day')) Is there a way to add to this the timezone that should … -
Cant' serv static css file with Django, Heroku and whiteNoice
I'm trying to serv static files with Django and Heroku. Right now there is only a single .css file. I followed the Heroku example settings, but it doesn't work. I'm in production, so DEBUG is set to False and I'm trying to use whitenoise. If I comment out this line in my settings.py (please find the whole thing below): STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' The page is loaded bug no css is loaded. If it's not commented out I get a 500 error : raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'styles.css' Statics are in a folder named static in the same folder as settings.py index.html {% load staticfiles %} ... <link rel="stylesheet" href="{% static 'styles.css' %}"> settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') SECRET_KEY = 'my_secret' SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True DEBUG = False ALLOWED_HOSTS = ['myapp.herokuapp.com'] INSTALLED_APPS = [ 'my_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app.urls' 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', … -
How do I manually assign values to a Django Serializers fields?
I am writing a Django REST API server that will return token/credentials information from Yelp. I have URL mapped this to an endpoint for testing purposes but I don't know how to fill my serializer's fields with the information returned from the call to Yelp. When I connect to the endpoint I get the response below - there is no information... I assume this is because I need to set the values in the serializer's fields. { "client_id": "", "client_secret": "", "token_path": "", "grant_type": "", "token_type": "", "expires_in": null, "access_token": "" } My view is... from rest_framework import generics from .serializers import YelpAuthenticationSerializer from .models import YelpAuthentication # Create your views here. class AuthView(generics.ListCreateAPIView): queryset = YelpAuthentication.objects.all() serializer_class = YelpAuthenticationSerializer def perform_create(self,serializer): pass And the YelpAuthentication class is #yelp.com/developers/documentation/v3/authentication class YelpAuthentication(models.Model): #fields necessary to authenticate url = models.CharField(max_length=200, blank=False, default='https://api.yelp.com/oauth2/token') api_host = models.CharField(max_length=100, blank=False, default='https://api.yelp.com') token_path = models.CharField(max_length=100, blank=False, default='/oauth2/token') grant_type = models.CharField(max_length=200, blank=False, default='client_credential') client_id = models.CharField(max_length=200, blank=True,default='N/A') client_secret = models.CharField(max_length=300, blank=True, default='N/A') #respone body elements after authentication access_token = models.CharField(max_length=200, blank=False, default='N/A') token_type = models.CharField(max_length=7, blank=False, default='bearer') expires_in = models.BigIntegerField() def authenticate(self): #some code that works ... return token What I would like to do is...when my Serializer … -
Testing applications with dotted path name in django
All custom apps in my django project are in apps folder and I want to run tests on all the apps folder. myproject apps/ app1/ apps2/ custom_app/ settings/ manage.py When I run python manage.py test --settings=myproject.settings.test it only runs the tests in custom_app. Here is my base_settings.py INSTALLED_APPS = [ ** list of all the django default apps ** ] USER_APPS = [ 'cutoms_app', 'apps.app1', 'apps.app2'] INSTALLED_APPS = INSTALLED_APPS + USER_APPS Any help is much appreciated. Thanks -
Django - custom file uploads based on criteria
I am currently struggling to find the best way to approach the following problem: I have user registration implemented using django-registration and I want each user to be able to upload different set of documents. Each user will have an "agency", that require some extra documents, however those documents might be different. So my User base class will have a one-to-one relation with all those base documents required for each user, however I am not sure how to let each agency define their own set of documents and how to tie it to the User. Thanks. -
How to use google fusion tables as my Django project database?
Ive just started using google fusion tables to handle our data. And I'm just wondering if it's possible to use web database (google fusion tables here, ofcourse) as my Django project backend. And if so, what's the script to configure DATABASE on settings.py ? Your help greatly appreciated. -
Django order approval flow
Hello guys i'm new to django,i have tried a lot but didn't get any solution.My task is 'order approval form' .There are 'N' no.of users and user has to fill form with requirements,after filling and submitting its that form data/notification should sent to manager/admin,he can check/delete /approve,if he approves it should go to next state/stage of flow how to do this workflow ? -
Passing multiple parameters to Django URL - unexpected keyword argument
I wanted to document this question as much as possible in order to be able to detail the origin of the problem. I have the following model named LodgingOffer, to create a lodging offer and detail their information class LodgingOffer(models.Model): # Foreign Key to my User model created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') slug = models.SlugField(max_length=100, blank=True) # ... Another fields ... def __str__(self): return "%s" % self.ad_title def get_absolute_url(self): return reverse('host:detail', kwargs = {'slug' : self.slug }) # I assign slug to offer based in ad_title field,checking if slug exist def create_slug(instance, new_slug=None): slug = slugify(instance.ad_title) if new_slug is not None: slug = new_slug qs = LodgingOffer.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug # Brefore to save, assign slug to offer created above. def pre_save_article_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=LodgingOffer) For this model, I have a DetailView named HostingOfferDetailView . An important objective I want to pursue and for which I ask this question is that in the detail view of an LodgingOffer object, I should be able to contact the owner of that offer (object … -
Django shell plus invalid arguments in virtualenv
I created a virtualenv to set up for Django upgrade to version 1.8. but when trying to run shell plus I am getting an error about invalid arguments: py manage.py shell_plus Trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments I have no clue why this is happening. I tried installing ipython in the virtualenv because I know shell plus uses ipython, but that didn't seem to help. -
Application not able to access the profile pic and posts using DjangoAllAuth
I am trying to access the profile picture and posts of the user using Django-AllAuth. Here is the template where I am trying to load the profile image: <html> <body> Welcome back {{ user.first_name }} {{ user.age }} <img src={{user.cover.source}} height="60" width="60"> <a href="/">Home</a> </body> </html> Here is the view.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'public_profile', 'user_photos'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'cover', 'posts', 'age', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Here I am not getting the image. See the below result: What I want to achieve? 1) I want to display the profile image on the screen. 2) I want to get the posts of the user loggedin in the view.py and send it on the screen to display on the template. -
Django-storages save images webp as octet-stream
when I try to save pillow images using django-storages to store in S3, webp images save them as octet-stream. You should also save images in JPG. I leave below my configuration of django-storages AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'public, max-age=2592000', } AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='WEBP', optimize=False, ) So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='JPEG', optimize=False, ) Thanks! -
Django different types of user
I want to build a simple website with Django, and so far I have made a sign-up form that everyone can sign up and publish some announcement. For next stage I want to make the user can only view the announcement by default, I also want to have another type of user can view and create an announcement. How should I build my user model and sign up forms? Should I use things like permission or AbstractUser? the current sign up forms.py I am using is like from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model class UserCreateForm(UserCreationForm): class Meta: fields = ("username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" and the views about the announcement is like #show all announcement class AnnouncementListView(ListView): ... #show a specific announcement class PostDetailView(DetailView): ... #create a announcement class CreatePostView(LoginRequiredMixin,CreateView): ... Thanks! -
How to redirect when loading a FormView?
Using the class based view FormView I want to redirect to a different page if a user is already activated. So I've tried overriding the get_form_kwargs function: class UserActivateView(AnonymousRequiredMixin, FormView): ... def get_form_kwargs(self): .... if profile.activated: # User is already activated an can log in messages.info( self.request, 'You are already activated. ' 'Login or click forgot password if you have forgotten' ) redirect(to=reverse_lazy('auth_login')) .... return kwargs Using this method the message is added but the redirect is never done. Am I doing this redirect at the correct place, I've been using ccbv as a reference -
Django migration issue: dynamic_forms missing migration as a dependency
One of my migrations specify a particular dynamic_forms migration as a dependency: dependencies = [ ('dynamic_forms', '0004_auto_20170110_1645'), # other deps ] But that file doesn't exist in the migrations directory under the lib's instalation path. The migrations for the version of dynamic_forms I am using, 0.3.3, are: 0001_initial 0002_auto_20140124_1844 0003_auto_20140916_1433 Since the dependency migration doesn't exist, when running migrate, showmigrations, or any other migration-related task, I am logically getting the following error: django.db.migrations.graph.NodeNotFoundError: Migration some_app.0001_initial dependencies reference nonexistent parent node (u'dynamic_forms', u'0004_auto_20170110_164 5') I tried updating the package to its most recent version, 0.5.3, but it didn't help either because it doesn't have that migration file. I tried faking the migrations for dynamic_forms just to see if it helped somehow: py manage.py migrate dynamic_forms --fake But it didn't even go through because the same missing dependency error occurred. I am not sure how to deal with this and although about I did find some information about missing migrations in the dynamic_forms package I couldn't learn how to solve the issue. -
django-import-export : getting post_export to update models
Please how do i updated exported Company model below using post_export signal. I don't want to export items not exported before. So the best thing is using signals. However, if i print the model in the signal at the end of the code below, I get a type class e.g <class 'app.models.Company'> I know am doing something wrong by saving a model but can't find my way arround. Maybe I'm not understanding the documentation of django-import-export library which is found here. #models.py class Company(models.Model): class Meta: verbose_name_plural = "Companies" company_name = models.CharField(max_length=254, blank=True) website = models.URLField(max_length=254, unique=True) address = models.CharField(max_length=254, blank=True, null=True) imported = models.BooleanField(default=False) exported = models.BooleanField(default=False) user = models.ForeignKey(User) def __str__(self): if self.company_name: return self.company_name return self.domain #admin.py from django.dispatch import receiver from import_export.signals import post_import, post_export class CompanyResource(resources.ModelResource): class Meta: model = Company fields = ('website', 'user', 'country', 'source', 'industry') @admin.register(Company) class CompanyAmin(ImportExportModelAdmin): resource_class = CompanyResource list_display = ('domain', 'website', 'exported', 'added_on') list_filter = ('user', 'country', 'imported', 'exported', 'added_on') import receiver from import_export.signals import post_import, post_export @receiver(post_export, dispatch_uid='ss1') def _post_export(model, **kwargs): print(model) model.exported = True model.save() # This line when included raises Error: "save() missing 1 required positional argument: 'self'" so code breaks here -
How to use model's default value in the serializer?
I have a serializer defined by model's fields in the following way: class MyModel(models.Model): f1 = models.CharField(max_length=10, default='abc') class Serializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ['f1'] Bit, running: Serializer({}).data Return an empty object. So how can I use the default value declared in the model? I know I can repeat the field in serializer, like that: class Serializer(serializers.Serializer): f1 = serializers.CharField(default='abc') Serializer({}).data This will return the expected {'f1' : 'abc'}, but I do not want to repeat myself. -
error while using makemigration in django
i am working on a development server running python3.6 and django 1.11 with virtualenv when I use "python manage.py makemigrations" i get this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/core/management/base.py", line 17, in <module> from django.db.migrations.exceptions import MigrationSchemaMissing File "/opt/hafez_bot/env/lib/python3.5/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named 'django.db.migrations.migration' please help me -
Django annotate Avg on model field
I have these models: class Agency(models.Model): pass class User(models.Model): agency = models.ForeignKey(Agency) class Feedback(models.Model): rating = models.DecimalField() user = models.ForeignKey(User) and I want to annotate a queryset with the average of all ratings. I expected this to work: Feedback.objects.annotate(avg_rating=Avg('rating')).values('rating', 'avg_rating') but it just outputs this: <QuerySet [{'rating': 0.8, 'avg_rating': 0.8}, {'rating': 0.2, 'avg_rating': 0.2}, {'rating': 0.6, 'avg_rating': 0.6}, {'rating': 1.0, 'avg_rating': 1.0}, {'rating': 0.4, 'avg_rating': 0.4}]> As you can see the average should be 3.0. Where am I going wrong? For a bit of clarity, I'm trying to do something like this: agencies = Agency.objects.annotate( avg_rating=Coalesce(Subquery( Feedback.objects.filter(user__agency_id=OuterRef('pk')) .values('rating') .annotate(avg_rating=Avg('rating', output_field=DecimalField())) .values('avg_rating') ), 0) ) where the average rating is per agency. Any ideas? -
Makemigrations error : django.db.utils.OperationalError: no such table
when I makemigrations i get the following error: django.db.utils.OperationalError: no such table: django_site Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Python27\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python27\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Python27\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\campaign\models.py", line 5, in <module> from sinUser.models import sinUser, sinUserCategories File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\sinUser\models.py", line 4, in <module> from functionUtility.sendEmails import sendEmailFunctionIsError File "C:\Users\KwanfahArunrerk\Desktop\Sinwattana_repo\trunk\sinwattana3_0\functionUtility\sendEmails.py", line 12, in <module> HOSTNAME = Site.objects.get_current().domain File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 63, in get_current return self._get_site_by_id(site_id) File "C:\Python27\lib\site-packages\django\contrib\sites\models.py", line 35, in _get_site_by_id site = self.get(pk=site_id) File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 374, in get num = len(clone) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 232, in __len__ self._fetch_all() File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Python27\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 894, in execute_sql raise original_exception django.db.utils.OperationalError: no such table: django_site I am newbies python programming some one can help me thank you