Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
2 words queryset request in Django for the same variable
If the user type "word1" in the form field of var1, I would like to do a query in the database considering the word1 + "word99"(as standard search), how can I do that considering my code bellow? I am new in django. Thanks a lot for the help def qrs_table(request): form = MyForm() query = {} if request.GET.get('Var1'): query['Var1'] = request.GET.get('Var1') if request.GET.get('Var2'): query['Var2'] = request.GET.get('Var2') results = Model.objects.filter(**query).distinct() qrs_table = MyTable(results) return render(request, 'app/page.html', {'form': form, 'qrs_table': qrs_table}) -
ValueError: invalid literal for int( ) with base 10: '262,400,000'
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database. But while migrating the app I'm getting this error: ValueError: invalid literal for int() with base 10: '262,400,000' Here's the traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/aggregator/WorldBank/management/commands/fetch_wb.py", line 60, in handle Projects.objects.create(**pdata) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 807, in save force_update=force_update, update_fields=update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 837, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 923, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/python/lib/python3.6/site-packages/django/db/models/base.py", line 962, in _do_insert using=using, raw=raw) File "/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/python/lib/python3.6/site-packages/django/db/models/query.py", line 1076, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1106, in execute_sql for sql, params in self.as_sql(): File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1059, in as_sql for obj in self.query.objs File "/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1059, in <listcomp> for obj in … -
Django can't find my static files
I can't for the life of me figure out why I django can't find my static files. My directory structure is like so: ├── projectname │ ├── appname │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ ├── manage.py │ └── projectname │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ └── settings.cpython-36.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── static ├── templates └── virtualenv My appname/urls.py looks like this from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.home_page, name="home_page") ] The appname/views.py: from django.shortcuts import render def home_page(request): return render(request, 'home_page.html') The home_page view extends the base.html, at ./templates/base.html {% load staticfiles %} <html> <head> <title>Title</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'home_page.css' %}"> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> And the home_page.html at ./templates/home_page.html {% extends 'base.html' %} {% block content %} <p>TEXT</p> {% endblock %} Finally the css file at ./static/styles.css p { … -
How to get image source of a highcharts image in JS/Jquery to open it in new tab?
I would like to obtain the url of a highcharts (container) image by using JS/Jquery. However, I cannot find a solution for this.... Thank you in advance for your help! -
Show Form Only to Specific User on Django
I have a blog part within my project. It's something simple. It has only title and content for now.. Basically, it looks like Facebook post form: on top of the post lists (you can easily visualise) and my problem comes here: with {% if user.is_authenticated %} code line I can allow my form to be seen only by the registered user. That's fine, but as a registered user when I visit other users' pages I can still see the form there. But, no! I want to show it (or I want it to be seen) only to the active user on its own page. So, I shouldn't see the form of other users when I visit their pages. Shortly dear friends, my little post form must be visible only to an authenticated user on his/her own page, not to other users. How can I do it? my codes: My Model: class Posts(models.Model): user = models.ForeignKey('auth.user', verbose_name='Writer', related_name='posts') post_title = models.CharField(max_length=120, verbose_name='Title') post_content = models.CharField(max_length=240,verbose_name='Content') publishing_date = models.DateTimeField(verbose_name='PubDate', auto_now_add=True) My View : class AddPost(CreateView): model = Posts fields = ['post_title', 'post_content' ] success_url = '/directory/dashboard' def form_valid(self, form): form.instance.user = self.request.user return super(AddPost, self).form_valid(form) -
How do I get groups__name on a line in the Django user model query?
I want get groups__name in a line at User.objects.values('id', 'username', 'groups__name) But I get example: {'id': 1, 'groups__name': None, 'username': 'admin'}, {'id': 2, 'groups__name': 'Manager', 'username': 'test'}, {'id': 2, 'groups__name': 'Personal', 'username': 'test'} I want query like this example: {'id': 1, 'groups__name': None, 'username': 'admin'}, {'id': 2, 'groups__name': ('Manager', 'Personal'), 'username': 'test'} I use django 1.11 -
Django add a relation between the user and the selected articles
I have a simple model Article. The model is: class Article(models.Model): title = models.CharField() text = models.TextField() likes = models.IntegerField(default=0) user = models.ForeignKey(User) I have also login, and likes, every user has favorite articles. I make new model: class LikeArticle(models.Model): article = models.IntegerField() user = models.ForeignKey(User) In view we have def articleLike(request): if request.method == 'POST': article_id = request.POST['id'] article_like = LikeArticle( article=article_id, user=request.user ) article_like.save() And when we want to see all favorite articles def favorite(request): favorite_list = LikeArticle.objects.all() return render(request, 'article/favorite.html', {'articleList': favorite_list}) But now its return me id article and username, how I can filter and choose from Article.objects.all() Is my logic correct? Maybe I need to do everything differently? -
Using some Django view data in the <style> tag
In my django view, I am passing a variable called data to the template. This data contains a field called hex_code which I want to use in my css. I am trying to do it the following way: <style> #my-item { background-color: {{ data.hex_code }}; } </style> The hex code is a string in the format '#ffffff'. However, this method does not work. Any way to fix this? Please note the following things: I don't want to use Javascript unless I absolutely have to. I only want to call data.hex_code in the style tag in the Html, not in a separate Css file. Thanks! -
templatetag to display list on individual rows
I'm struggling to get my templatetag to work. I believe it's the syntax or the way i'm calling app_filters. Forgive me i'm learning web application development so if my logic is off please correct me. My goal is to pass a collection of check boxes on one template to a new one filtered at a different level report_id is the collection of each check box. I have an array in my view from my GET.getlist call below checkedlist = request.GET.getlist('report_id') reportlist = QvReportList.objects.filter(report_id__in= checkedlist, active = 1).values_list('report_name_sc',flat = True) print (checkedlist) print (reportlist) args = {'retreivecheckbox': checkedlist} return render(request,'accounts/requestaccess.html', args) When I print my array the console displays it correctly, this example is if there was two check boxes selected: ['88', '89'] <QuerySet ['Common Data Model Reconciliation Load', 'LEJR BPCI IV - ICS Baseline']> I've created the following templatetag called app_filters defined as: from django import template register = template.Library() @register.filter def get_list(querydict, itemToGet ): return querydict.getlist(itemToGet) Now i'm trying to get my template to display what's in my console but as individual rows/indexes dependent upon user selections. I'm told get_list will do that for me. I've also tried get_at_index. I.E. I want to see retreivecheckbox as 88 89 and … -
Ubuntu 17: Can't install mysqlclient
Trying to follow a Django tutorial but I cannot install mysqlclient. The tutorial claims that I can do so with the following command: pip install mysqlclient but this generates this error: Collecting mysqlclient Using cached mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-rrolctwh/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/tmp/pip-build-rrolctwh/mysqlclient/setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "/tmp/pip-build-rrolctwh/mysqlclient/setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) OSError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-rrolctwh/mysqlclient/ I have the most up-to-date pip and virtualenv installed. I would like to be able to install mysqlclient so that I may continue with the tutorial. -
Django not installing in folder where I want
I am new to python/django/pip. I created a virtualenv and I was in the bin dir when I did a pip install django. It created the django files there which is not what I wanted. So I did pip uninstall django. Then I created a folder called web in my virtualenv root and tried pip install again. This time it said loading from cache and installed django in bin folder again. So I deleted it and tried again with --no-cache-dir. This downloaded django fresh, but I am still finding the installation in bin directory! This is driving me crazy, how can I get it to install in the web directory? Any help much appreciated. -
take a get value and make constant variable django python
I am working in a booking engine project with django for hotels. I need when a client select the hotel, arrival date, and departure date (these parameters are passed with get method) a view take them, and generate global variables to all view, until the client change for example the dates. In each view i need to have the hotel, the arrival date, and departure date. i know that i can do this to template with context proccessor, but i dont know wich is the better way to do this for views. I was ridding something with middlewares, but i dont know. Can somebody help me? -
How can I change part of a Django REST Framework JSON response from a list to a dictionary?
More specifically, I need a nested part of my response to be a multi-item dictionary rather than a list of many single-item dictionaries. I am returning all the data I want, but I cannot figure out how to format it more sensibly without what I consider to be an extraneous list Here is the (simplified) response I am currently getting: { "uielements": [ { "home-bg": { "label_text_color": "#123456", "tag_display_text": "young" } }, { "home-speak-btn": { "label_text_color": "", "tag_display_text": null } } ] } I would like the response to be in this format: { "uielements": { "home-bg": { "label_text_color": "#123456", "tag_display_text": "young" }, "home-speak-btn": { "label_text_color": "", "tag_display_text": null } } } Here is my relevant serializer.py code: class UIElementProjectSerializer(serializers.ModelSerializer): class Meta: model = UIElement def to_representation(self, obj): result = super(UIElementProjectSerializer, self).to_representation(obj) uien = UIElementName.objects.filter(id=result['uielementname'])[0] return {uien.name: result} and my relevant views.py code: class ProjectViewSet(viewsets.ViewSet): ... @detail_route(methods=['get']) def uielements(self, request, pk=None): uielements = UIElementFilterSet(params) serializer = serializers.UIElementProjectSerializer(uielements, many=True) return Response({"uielements": serializer.data}) -
Django - create_superuser() got an unexpected keyword argument 'user_type'
I am trying to create a custom user model for my django app. Here is the code for CustomUser and CustomUserManager. class CustomUserManager(BaseUserManager): def _create_user(self, anonymous, first_name, last_name, email, username, password, home_address, user_type, image_path): now = timezone.now() if not email: raise ValueError('The gives email must be set') email = self.normalize_email(email) user = self.model( anonymous=anonymous, first_name=first_name, last_name=last_name, email=email, username=username, home_address=home_address, user_type=user_type, image_path=image_path, created_time=now, last_login=now ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, first_name, last_name, email, username, password, home_address, image_path): return self._create_user(False, first_name, last_name, email, username, password, home_address, 0, image_path) class CustomUser(AbstractBaseUser): anonymous = models.BooleanField() username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) email = models.EmailField(blank=True, unique=True) home_address = models.CharField(max_length=255, blank=True) user_type = models.IntegerField(1) image_path = models.CharField(max_length=500, blank=True) created_time = models.TimeField() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'home_address', 'first_name', 'last_name', 'user_type'] Then I get the error about unexpected argument user_type Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 363, in execute_ from_command_line utility.execute() File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_arg v self.execute(*args, **cmd_options) File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py ", line 63, in execute return super(Command, self).execute(*args, **options) File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Nutzer\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py ", … -
Inserting singular items into repeating grids
I am building a 2-column grid layout for a Q&A page. I'm using Django and each question is looped over. I'm trying to place an Ask Question button in the top2 class. I only want one Ask Question button, and right now there is a button for every question. My question is, how do I insert a singular item into a repeating grid like this? Is there a way for a grid layout to not take up the entire horizontal screen? .top { display: grid; grid-template-columns: 3fr 1fr; grid-gap: 10px; grid-row-gap: 30px; } <div class="top"> <div class="top1"> # Stuff here... </div> <div class="top2"> <form action="{% url 'question_ask' %}"> <button class="button3"><span>Ask question</span></button> </form> </div> </div> -
OperationalError at /admin/learning_logs/example/
Here is the traceback and the data: OperationalError at /admin/learning_logs/example/ no such column: learning_logs_example.entry_id Request Method: GET Request URL: http://localhost:8000/admin/learning_logs/example/ Django Version: 1.11.7 Exception Type: OperationalError Exception Value: no such column: learning_logs_example.entry_id Exception Location: C:\Users\Bryan\Desktop\LEARNI~1\ll_env\lib\site- packages\django\db\backends\sqlite3\base.py in execute, line 328 Python Executable: C:\Users\Bryan\Desktop\LEARNI~1\ll_env\Scripts\python.exe Python Version: 3.6.2 Python Path: ['C:\\Users\\Bryan\\Desktop\\learning log', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env\\Scripts\\python36.zip', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\Bryan\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env', 'C:\\Users\\Bryan\\Desktop\\LEARNI~1\\ll_env\\lib\\site-packages'] Server time: Sat, 18 Nov 2017 18:36:14 +0000 For some reason, when I click that link that says "Examples" below, ![screenshot][1] it says this ![screenshot][2] I tried migrating but it says (venv) C:...\learning log>python manage.py makemigrations No changes detected (venv) C:...\learning log>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. [1] https://i.imgur.com/KoXafVV.png [2] https://i.imgur.com/Y4uhrHM.png -
Post additional model values to database in views.py not modelform
model class Person(models.Model): first_name = models.CharField(blank=False,max_length=256,default='') last_name = models.CharField(blank=False,max_length=256,default='') plan = models.CharField(blank=False,max_length=256,default='') plan_price = models.CharField(blank=False,max_length=256,default='') Views.py if request.method == 'POST': if form.is_valid(): form.save(commit=True) return index(request) In my modelForm I accept 3 values from the user: first_name, last_name, and plan. I dont have any problem with posting to the database from the form, what i am trying to find out is how I can say something like this if plan = 'plan1': #set plan_price to '$399' else #set plan_price to '$699' #then post first_name, last_name, plan, plan_price to database -
How to avoid additional random number in datatable ajax request
Hi my datatables ajax call is as below, $(document).ready(function () { $('#example').DataTable({ "ajax": '/api/get_requests' }); So I am expecting the call my backend django server as below, http://localhost:8080/api/get_requests/ But instead it generates an additional random numbers in the end and call is sent as below and my django server says wrong url and gives 404 error http://localhost:8080/api/get_requests/?_=1511021359038 How can I force the datatables ajax call to not send the additional random numbers -
"The path python3 (from --python=python3) does not exist" error
PS C:\Users\Sonalika\dev\trydjango1-11> virtualenv -p python3 . The path python3 (from --python=python3) does not exist i added python36/Scripts in the path file and python36 also but it still shows the error -
Django-autocomplete-light - how to autocomplete CharField choices?
Can't figure out how to autocomplete CharField choices. I have a field nationality where I use list of countries. Normal select looks like this: <select name="nationality" class="form-control" id="id_nationality"> <option value="" selected="">---------</option> <option value="AF">Afghanistan</option> <option value="AX">Åland Islands</option> <option value="AL">Albania</option> where values are shortcuts I couldn't find autocomplete view for such situation: Select2ListView returns list of values which is not sufficient. I need to set shortcuts as values and verbose names as texts. There are only ListViews and QuerySetViews. -
POST 405 on Django admin auth
[18/Nov/2017 18:50:58] "GET /admin/login/ HTTP/1.1" 200 1637 Method Not Allowed (POST): /admin/login/ [18/Nov/2017 18:51:01] "POST /admin/login/ HTTP/1.1" 405 0 this used to work but now it doesn't. I tried to get another POST method working but couldn't. now I can't even log in. didn't change settings or anything. urls also look good. Django version 1.11.6 -
Cannot append extra data to jquery-fileupload call
I am trying to integrate file uploading functionality to my Django app using jQuery File Upload Plugin which can be found here. Now, I am already attaching csrf token with the input tag in the template like that: <input id="fileupload" type="file" name="document" multiple style="display: none;" data-url="{% url 'upload' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> However, later in JS file I would like to append some extra information to this form. The proposed way is to do that by using formData as shown: $("#fileupload").fileupload({ dataType: 'json', formData: {employee_id: get_selected_employee()}, done: function (e, data) { } } }); However, this new data does not get appended to formData, which is already created in the template and contains csrf_token. If I try to append the csrf token and employee_id in .fileupload call I get 403 (CSRF token missing or incorrect) even though the csrf token seems to be valid. I cannot append employee_id in the template as it's dynamically changing. Does anyone have any thoughts? -
Suppress a Static file missing ValueError
I currently have a Django site and in one particular view, an image is displayed based on user input. With WhiteNoise, Django will report a 500 error if that image doesn't exist. However I would just rather serve a broken image reference than kill the whole page. Is there a way to suppress the error in some cases? Or perhaps some views? The error looks like this: Missing staticfiles manifest entry for '291.png' I assume you'd need to use a middleware but I'm not 100% sure how. Thanks -
What is the best way to achive realtime info on my website currently using php yii framework and django-rest for api with mysql
Here i have no idea, what to exactly use to get the real-time information on the web page on my already developed application. The real-time feature will be based on online Auction feature, as a bidder bids low/high amount all the concerned user should reflect the newer price on their window immediately without refreshing the web page. Please suggest me the best way possible, my application based on: PHP 5 frontend with yii 1.1.15 framework Python django-rest framework for the rest api to fetch data from mysql database. for this i have heard about the node js, but will it be possible using only node js without using mongodb/rethinkdb angular or express js or socket.io. -
Django - Update information accessible from a view every hour
I am creating an app which fetches data from an API every time a view is loaded. As I am expecting a big user base, I fear exceeding the rate limit. I thought about scheduling the API calls every hour and storing them in an object. Which would be a convenient way of designing this, or do you have a better idea in mind of approaching this problem? Thanks in Advance