Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to add placeholder and change form field label simultaneously in django?
I'm trying to change the field label in django form and also want to add a place holder but when I set a placeholder attribute, field label doesn't work and shows the default field label "work_or_study" instead of "Bio". here is the code: class ProfileEditForm(forms.ModelForm): date_of_birth=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'y-m-d'})) work_or_study=forms.CharField(widget=forms.TextInput(attrs={'placeholder':'something interesting about you'})) class Meta: model= Profile labels = {"work_or_study":"Bio"} fields = ('date_of_birth','work_or_study') -
Django - Heroku - You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
I try to use Heroku Scheduler to run it in my Django app on Heroku. When I run this code: from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): print('This job is run every minute.') sched.start() Everything is working properly however when I want to import my own function or model like this: from backend.models import myModel from apscheduler.schedulers.blocking import BlockingScheduler sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=1) def timed_job(): print('This job is run every minute.') sched.start() I get error shown below. Any ideas how can I solve it? 2017-11-18T16:41:00.928495+00:00 app[clock.1]: Traceback (most recent call last): 2017-11-18T16:41:00.928513+00:00 app[clock.1]: File "backend/update.py", line 4, in <module> 2017-11-18T16:41:00.928701+00:00 app[clock.1]: from backend.models import myModel 2017-11-18T16:41:00.928720+00:00 app[clock.1]: File "/app/backend/models.py", line 3, in <module> 2017-11-18T16:41:00.928857+00:00 app[clock.1]: from django.contrib.auth.models import User 2017-11-18T16:41:00.928875+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> 2017-11-18T16:41:00.929018+00:00 app[clock.1]: from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager 2017-11-18T16:41:00.929022+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 52, in <module> 2017-11-18T16:41:00.929180+00:00 app[clock.1]: class AbstractBaseUser(models.Model): 2017-11-18T16:41:00.929202+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 53, in AbstractBaseUser 2017-11-18T16:41:00.929360+00:00 app[clock.1]: password = models.CharField(_('password'), max_length=128) 2017-11-18T16:41:00.929363+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1057, in __init__ 2017-11-18T16:41:00.930036+00:00 app[clock.1]: super(CharField, self).__init__(*args, **kwargs) 2017-11-18T16:41:00.930039+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 172, in __init__ 2017-11-18T16:41:00.930243+00:00 app[clock.1]: self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE 2017-11-18T16:41:00.930246+00:00 app[clock.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in … -
Django how get user(author) of article and transfer it to template
I have simple article model, and I want get user who is author some article. But I can't. I make next: from django.db import models from django.contrib.auth.models import User class Article(models.Model): class Meta(): db_table = 'article' title = models.CharField(max_length=50) text = models.TextField() user = models.ForeignKey(User) in my view we have def articleSingle(request, article_id=1): article = Article.objects.get(id=article_id) return render(request, 'article.html', {'article': article}) and template <h1>{{ article.title }}</h1> <p>{{ article.text }}</p> <p>{{ article.user.username }}</p> But article.user.username or article.user is empty -
cannot access user profile in template from user object
i've created a UserProfile method, which i would like to access with the user, however it does not seem to return anything even though i have set related_name. what am i missing? models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile_user") avatar = models.ImageField(upload_to = 'static/img/avatars', default = 'static/imgs/avatars/avatar.jpeg') def __str__(self): return self.user.username def __unicode__(self): return self.user.username template so far in template i have tried {{ user.profile_user.avatar }}, {{ request.user.profile_user.avatar }} -
Django Social Auth pipline redirect and create
I have implemented Django Social Auth to signup and login using Facebook and Twitter. I was wondering how can I use piplines to specify an action to be done. For example, after creating the profile, I want to check if a field is empty and then redirect the user to another page to complete the profile as Facebook and Twitter don't give you the email address for example. Thank you -
How to prevent FactoryBoy from reusing object of a SubFactory?
I have the following factories: class UserFactory(factory.DjangoModelFactory): class Meta: model = get_user_model() class ProProfileFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) class Meta: model = ProfessionalProfile class UserProfileFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) class Meta: model = UserProfile When I inject both pro and user profiles they are associated with the same user: def test_should_create_project(pro_profile, user_profile): assert user_profile.user != pro_profile.user This test fail. How can I make factory boy create a new user for each profile? I'm using Django 1.11, pytest 3.2.2, pytest-django 3.1.2, pytest-factoryboy 1.3.1 -
last activity feature in Django not updating properly
I am trying to implement a lastActive feature but I don't know what values should the null and blank property have for the lastActive field in the User model. With this version of the code, the lastActive fields get a similar time as the created field, but after every login+logout the lastActive field doesn't get updated. Other than that, I am also getting the following error if I try python manage.py migrate, although makemigrations works fine: File "/Library/Python/2.7/site-packages/django/utils/dateparse.py", line 94, in parse_datetime match = datetime_re.match(value) TypeError: expected string or buffer Here's my models.py: class User(models.Model): userID = models.AutoField(primary_key = True) username = models.CharField(max_length = 30, unique = True) first_name = models.CharField(max_length = 30, blank = False) last_name = models.CharField(max_length = 30, blank = False) email = models.EmailField(blank = False, unique = True) password = models.CharField(max_length = 30) class_year = models.IntegerField(validators=[MinValueValidator(4),MaxValueValidator(4),]) created = models.DateTimeField(auto_now = True, editable = False) #this field actually doesn't get updated yet, please debug lastActive = models.DateTimeField(auto_now = True, editable = True) Here's my middleware.py: class LastActiveMiddleware(MiddlewareMixin): def process_response(self, request, response): if request.user.is_authenticated(): User.objects.filter(pk = request.user.pk).update(lastActive=timezone.now()) return response Here's my view.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.signup(form, request) username = form.cleaned_data.get('email') … -
AWS broken pipe error when uploading files bigger than 1 MG
I am a django newbie, and I inherited a django back-end with little documentation. I am making a request to said server, which is hosted on AWS. To store the files in the request we use S3. I have found nothing on the django code that limits the size of the file uploads, and I suspect it may be AWS closing the connection because of file size. This is the code I use, and below the error I get whenever the total size of the files is over 1 MG: import requests json_dict = {'key_1':'value_1','video':video,'image':,image} requests.post('https://api.test.whatever.io/v1/register', json=dict_reg) video is a video file ('.mov','.avi','.mp4',etc) with base64 encoding, and image is an image file ('.jpg','.png') with base64 encoding. And this is the trace I get, ONLY when the total size is over 1 MG: /usr/local/lib/python2.7/dist- packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatfo rmWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarningTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 110, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/local/lib/python2.7/dist-packages/requests/api.py", … -
Why the javascript fetch API changes the request from POST to OPTIONS?
I just want to post the data to the API whenever the User clicks on the link or opens a link. Below is the JSON format of the data i'm trying to post, { "username": "somename", "email": "someone@gmail.com", "mobile": "xxxxxxxxxx", "url": "https://www.atatus.com/blog/fetch-api/" } The manifest.json file is below, { "manifest_version": 2, "name": "UserData save to Chrome", "description": "Save the data to the API", "version": "1.0", "browser_action": { "default_icon": "icon.png", "default_popup": "login.html", "defult_title": "UserData save to Chrome" }, "background": { "scripts": ["url.js", "popup.js"] }, "permissions": [ "activeTab", "storage", "history" ] } Below is the HTML file that's used to pop up the form, <form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data"> <input class="form-control" autofocus="autofocus" placeholder="Username" id="id_username" type="text" name="username" required/><br> <input class="form-control" autofocus="autofocus" placeholder="Email Address" id="id_email" type="email" name="email" required/><br> <input class="form-control" autofocus="autofocus" placeholder="Mobile" id="id_mobile" type="text" name="mobile" required/><br> <button id="save" type="submit" class="btn btn-success">SAVE</button> </form> <script src="popup.js"></script> The popup.js is the javascript file which i'm using to store the data locally to the chrome storage, function saveChanges() { var user = document.getElementById("id_username").value; var email_id = document.getElementById("id_email").value; var mobile_no = document.getElementById("id_mobile").value; chrome.storage.local.set({ 'username': user, 'email': email_id, 'mobile': mobile_no }, function() { alert("Data Saved Successfully " + user + " - " + email_id + " - " …