Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django tests pass on local environment and fail on Travis CI
I have the following project structure when I run ./manage.py test the result is: ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .. ---------------------------------------------------------------------- Ran 2 tests in 0.056s OK Destroying test database for alias 'default'... But when i push to github, the build of Travis CI get the foollowing error: $ python manage.py test .E ====================================================================== ERROR: test_import (core.tests.test_iodb.ImportTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/travis/build/Sidon/work-at-olist/core/tests/test_iodb.py", line 14, in test_import channel = Channel.objects.get(name='Test1') File "/home/travis/virtualenv/python3.6.2/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/travis/virtualenv/python3.6.2/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name core.models.DoesNotExist: Channel matching query does not exist. In /home/travis/build/Sidon/work-at-olist/core/tests/test_iodb.py: from core.models import Category, Channel from core.utils import iocsv class ImportTestCase(TestCase): categs1 = .... def test_import(self): iocsv.imp_categories('test1.csv', 'Test1') ===> channel = Channel.objects.get(name='Test1') # Here the error -
Coroutines in Django
Context: I am writing a Django script as shown below. To my knowledge, the loop below will block the Django app and prevent other processes from running(ex. request handlers). Problem: What should I do so Django will run the following loop and yield to run other scripts when they are triggered. When said scripts are completed, the loop will resume on the same index. # ./app.py while True: items = queryItems() for item in items: process(item) Constraint: The answer should work in Python 2.7 and only uses libraries supporting Python 2.7. -
Create GCP project using resourcemanager API in python
I'm trying to create Google cloud project using ResourceManager API python client but not success. Here's what I have tried: Setup gcloud RUN gcloud beta auth application-default login to setup credentials also setup service account Enable resource manager api from GCP console. Here's my python code: From views.py from google.cloud import resource_manager ... # GCP Client client = resource_manager.Client() # List down all gcp projects for project in client.list_projects(): print(project) # Create a new project client.new_project(project_id='test-123', name='api') it list down all of my gap projects but new project doesn't created on my gcp console. Also it doesn't return any error. Help me, please! Thanks in advance! -
How can I implement Django-Kronos automatically?
I'm using Django to make a website. models.py class Member(models.Model): ... end_date = models.DateField(blank=True, verbose_name='end_date') Membership_status = models.IntegerField(blank=True, null=True, default=1)#1= active, 0=deactive, 2=refund status I want to compare the end date to today, and if today is more recent, I would like to automatically make the membership status zero(0) (It is currently 1). So, I used the Django-Kronos. cron.py from staff.models import Member from datetime import timedelta import datetime import kronos import random @kronos.register('* 1 * * *') def the_task(): today = datetime.date.today() Member.objects.filter(end_date__lte=today).update(Membership_status=0) I installed Django-Kronos and wrote the kronos in installed apps. But, I have no idea how I implement the cron.py automatically every 1.a.m. ('* 1 * * *') means 1 a.m. But it doesn't work. Any help will be very helpful to me, thanks! -
namespacing will not work unless I include urls at the root url
I have a django project called cooking with two apps in it, usermanage and recipes. I am namespacing the urls, but I do not understand why I have to include the urls in the cooking/urls.py for them to work. cooking/urls.py: urlpatterns = [ url(r'^cooking/$', index, name='index'), url(r'^user/', include('usermanage.urls')), url(r'^whatever/', include('recipes.urls')), .. etc I then namespace my urls/apps in each urls file, ex: app_name = 'usermanage' urlpatterns = [ url(r'^dashboard/$', dashboard, name='dashboard'), ..etc And my templates are namespaced 'usermanage:dashboard' etc. Why is it that I need to do the include in the cooking/urls.py for my namespacing to work? Why does the namespacing not just live within each app, does it have something to do with the root url? -
Django Hidden menu on dashboard
Now I want to hidden menu on Django by user 's role . I have three role is_shop is_customer is_brocker Any one have any solution to do that? -
Boolean Checks Inside Settings.py of Django Always Processed as True
I am trying to introduce some checks into the settings.py file of my Django 1.10 project as part of adopting django-environ package and complying with the 12-Factor type of configuration. While doing so, I noticed that whenever I introduce Boolean checks inside the settings.py, the block inside the if statement is processed irrespective of whether the operand is True or False. Example: import environ root = environ.Path(__file__) - 2 # three folder back (/a/b/c/ - 3 = /) env = environ.Env(DEBUG=(bool, False),) # set default values and casting environ.Env.read_env() # reading .env file DEBUG = env('DEBUG') # False if not in os.environ TEMPLATE_DEBUG = DEBUG CLOUD = env('CLOUD', default=False) ALLOWED_HOSTS = [] if env('CLOUD') and env('ALLOWED_HOST'): ALLOWED_HOSTS.append(env('ALLOWED_HOST', default='')) ALLOWED_HOSTS.append(env('ALLOWED_HOST_ALIAS', default='')) The code inside the last if statement is processed at all times. My question is whether such behavior is typical of Django's settings file? Why would it do this? Also, what is the best way to achieve some conditional checks based on the values (or absence thereof) loaded from the configuration file? -
How to test connect the MySQL in Django?
In the Django project's settings.py, there is the DATABASES config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'csvt', 'USER':'root', 'PASSWORD':'123456', 'HOST':'127.0.0.1', 'PORT':'3306', } } Now, I even don't know the password if is correct, how can I test the connect with my MySQL on my Mac? -
Naming `django-admin.py' vs 'django_admin.py'
In Django's bin folder, names django-admin.pywhich is separated by -, while others such as easy_install are isolated by underscore '_'. Django does not follow the PEP in naming, what is the particular advantage for this setting, or what kinds of unexpected problems will happen if Django's author names it as 'django_admin.py' instead of 'django-admin.py' -
Django: Building user Models with multiple relations. User -> Seller -> Buyer and User -> Buyer
I'm trying to create the following structure: I have Sellers and Buyers, both of which are Users of my website. I would like a person to be able to search for Sellers and based on user location, I show the closest Sellers. I'm using the default Django User auth, and I can only see username and password fields. I would also like to save Seller name. Should I add it to the Seller model, or somehow incorporate in into User model? I've looked at a few apps such as Django Profiles and I'd like to figure out if it's the best way to go about it. For this, I created a new app users and created a model for the Sellers in the /users/models.py class Seller(models.Model): user = models.ForeignKey(User, unique=True) price = models.IntegerField(default=0) availability = models.BooleanField(default=False) verified = models.BooleanField(default=False) class Buyer(models.Model): user = models.ForeignKey(User, unique=True) seller = models.ForeignKey(Seller) Currently I can display the Sellers, but I don't have access to their name or their user id. Should I simply store their name and last name in the Seller model or should I use an Authentication app? Also, there is no __str__(self) method, since I don't have a sensible identifier such … -
pip install language-check not working
I get this error when I do pip install language-check: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/setup.py", line 595, in <module> sys.exit(main()) File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/setup.py", line 590, in main run_setup_hooks(config) File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/setup.py", line 561, in run_setup_hooks language_tool_hook(config) File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/setup.py", line 584, in language_tool_hook download_lt() File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/download_lt.py", line 117, in download_lt version = get_newest_possible_languagetool_version() File "/private/var/folders/j6/yr6zgb4d1w308jkpc27p2t9w0000gn/T/pip-build-ymwzmypp/language-check/download_lt.py", line 81, in get_newest_possible_languagetool_version universal_newlines=True) File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 336, in check_output **kwargs).stdout File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 418, in run output=stdout, stderr=stderr) subprocess.CalledProcessError: Command '['/usr/bin/java', '-version']' returned non-zero exit status 1. I've looked at this question python pip install error language_check and followed the instructions to install python setup.py install and I get this: Traceback (most recent call last): File "setup.py", line 595, in <module> sys.exit(main()) File "setup.py", line 590, in main run_setup_hooks(config) File "setup.py", line 561, in run_setup_hooks language_tool_hook(config) File "setup.py", line 584, in language_tool_hook download_lt() File "/Users/allyzamarquez/ben/language_check/language-check/download_lt.py", line 117, in download_lt version = get_newest_possible_languagetool_version() File "/Users/allyzamarquez/ben/language_check/language-check/download_lt.py", line 81, in get_newest_possible_languagetool_version universal_newlines=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 573, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['/usr/bin/java', '-version']' returned non-zero exit status 1 -
Error invalid literal for int() with base 10: 'a' in Django admin?
I am having this Error invalid literal for int() with base 10: 'a' in Django admin? The code causing it is below. Does anybody know what is the issue? def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "filenames": kwargs["queryset"] = MyFile.objects.filter(file='a') return super().formfield_for_manytomany(db_field, request, **kwargs) -
Having trouble with SQLite3 table in Django
I am learning Django and have created a table in Django using PyCharm. I entered some values in the table and after that, I added another column to the table. Now, when I attempted to makekigrations, it happened successfully but when I tried to migrate, a lot of errors appeared which mainly said that an Empty Column is being attached and so on. After that I made a lot of tries, first by allowing Null values in that column then by commenting out the column but unsuccessfully. Now, even if I maintain the same code in the models.py file, the same errors keep appearing. Here is the code of models.py file: from django.db import models class Albums(models.Model): # name = models.CharField(max_length=250, default=None) artist = models.CharField(max_length=250) duration = models.CharField(max_length=20) # def __str__(self): # return self.artist class Songs(models.Model): album = models.ForeignKey(Albums, on_delete=models.CASCADE) name = models.CharField(max_length=250) PS: I have tried restarting PyCharm as well. -
Django: My views will not render a template
I have the first view, index() that renders index.html The second vies, success() that renders success.html. When the form is submitted that points to the url running the view success(), nothing happens- it just takes in the form data and refreshes the index.html Why is it doing this? What should I change? The code for it reads: def success(request): #the rest of the code here return render(request, 'success.html') The url reads: url(r'^success', views.success) Both of these perfectly mirror the index() view and default route, but for some reason this one isn't working. The form tag says: <form action="/success" method="post"> I tried without the slash too. Nothing in the console (message should appear if it has run the view) -
Language switcher switches back when link is clicked in django
I want to add a language switcher, just like on the django docs page. My myproject/app/app/urls.py: urlpatterns = i18n_patterns ( url(r'^', include('cars.urls'),name='car_app'), url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include(router.urls)), ) myproject/app/app/settings.py: LANGUAGE_CODE = 'en-us' LANGUAGE_CODE = 'de' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('zh', 'Chinese'), ('en', 'English'), ] myproject/app/cars/urls.py: urlpatterns = [ url(r'^$', views.CarView, name='index'), url(r'^(?P<name>[a-zA-Z0-9_]+)/$', DetailView.as_view(), name='detail'), url(r'^(?P<name>[a-zA-Z0-9_]+)/add_car/$', AddCarView, name='add_car') ] I want this language switcher to appear on all pages I have. So I thought I include this in myproject/app/templates/base.html. I defined this block: {% block language %} {% get_available_languages as languages %} <div class="language-switcher"> <ul id="doc-languages" title={% trans "Click on the links on the left to switch to another language." %}> {% for lang_code, lang_name in languages %} {% language lang_code %} <li> <a href={% block lang_href %}{% endblock lang_href %}>{{ lang_name }}</a> </li> {% endlanguage %} {% endfor %} </ul> </div> {% endblock language %} And then overwrite the {% block lang_href %} on the three pages of the car app with {% block lang_href %}"{% url 'index' %}"{% endblock lang_href %} {% block lang_href %}"{% url 'detail' car.name %}"{% endblock lang_href %} {% block lang_href %}"{% … -
Why won't my .html file connect to .js file?
I want to connect my .html to .js. I'm trying to run this simple program but it's not working. Below is the screenshot of my file path and files I'm working with. Here's map.html: <!DOCTYPE html> <html lang="en"> <head> </head> <body> </body> <script type="javascript" src="map.js"></script> </html> Here's map.js: document.write("testing"); -
Getting a field value from a field via a ForeignKey widget in reverse with django-import-export
I have it almost working. Models: class Child(models.Model): parent = models.ForeignKey('project.Parent') name = models.CharField(max_length=100) class Parent(models.Model): text = models.CharField(max_length=100) Resource: class ParentResource(resources.ModelResource): children = fields.Field(widget=widgets.ForeignKeyWidget(Parent)) class Meta: model = Parent use_transactions = True fields = ('text', 'children__child__name') Then the view calls the resource and downloads it. The issue is, name is blank. So, everything else works just fine, but I can't get child.name to show up. What am I missing? -
Issue with extending django model
I have a site where you can sign up to be either someone who uses the service(customer) or someone who provides the service(worker). I have created two profiles in models.py to represent each. They are both extremely similar for the most part as of right now. Both forms display properly when you go to them, and if you are signing up as a customer and press submit everything goes smoothly and a new user under will show up in "Customer profiles" at http://127.0.0.1:8000/admin/ . But if you try to sign up as a worker, the following error appears: Exception Type: RelatedObjectDoesNotExist Exception Value: User has no workerprofile. I do not understand this because as you will see in the code below i use customerprofile and it works fine, if I use workerprofile it crashes. Views.py: def signup_as_worker(request): if request.method == 'POST': form = WorkerSignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.workerprofile.birth_date = form.cleaned_data.get('birth_date') user.workerprofile.university = form.cleaned_data.get('university') user.save() # explicitly save custom fields not in User model raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) # login user after signup return redirect('home') else: form = WorkerSignUpForm() return render(request, 'core/signup_as_worker.html', {'form': form}) … -
Can not fetch data using Alamofire?
I am trying to fetch data in my iOS app from my Django backend. In postman if I perform a GET request on the following URL http://127.0.0.1:8000/api/places/categories with the params being Key:"Authorization" Value: "Bearer access_token".I get a JSON response. Inside my app I am doing something like this with the help of Alamofire: let access_token = "123" let headers = ["Authorization": "Bearer" + access_token] Alamofire.request(self.categoriesUrl, method: .get, parameters:nil,encoding: JSONEncoding.default,headers: headers).response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } I get an error saying Authorization Credentials were not provided. I understand this and it asks me to pass in the parameters but the parameters just need a token. So I do something like this: let access_token = "123" let params = ["Authorization": "Bearer" + access_token] Alamofire.request(self.categoriesUrl, method: .get, parameters:params,encoding: JSONEncoding.default,headers: nil).response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } It waits for a while but fails to fetch the data with the following error: Response: nil Error: Optional(Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x61800004b0d0 … -
Does Django's Field.unique creates a primary key?
Does Django's Field.unique creates a primary key. If not it will de normalize a table where it is declared? -
Need to store more vehicles per single user_id in django api
I had customized the inbuilt user model by using abstract user . I made another model vehicle with a one to one relation with user model, which resembles vehicles of each user . But it is storing a single vehicle per user_id. I need it to store multiple vehicles per user. My code is given below - Models.py class User(AbstractUser): phone_number = models.IntegerField(null=True) otp = models.IntegerField(null=True) class Vehicle(models.Model): user = models.OneToOneField(User) maker = models.CharField(max_length=500, blank=True) car_model = models.CharField(max_length=30, blank=True) Serializer.py class VehicleSerializer(serializers.ModelSerializer): user_id = serializers.IntegerField() class Meta: model = Vehicle fields = ('maker', 'car_model', 'user_id') def create(self, validated_data): maker = validated_data.pop('make', None) car_model = validated_data.get('car_model', None) user_id = validated_data.get('user_id', None) instance = self.Meta.model(**validated_data) if user_id is not None: instance.user_id = user_id instance.save() if car_model is not None: instance.car_model = car_model instance.save() return instance Views.py @api_view(['POST']) def vehicle_add(request): car_model = request.data.get('car_model') user_id = request.user.id serializer = VehicleSerializer(data={'user_id': user_id, 'car_model': car_model}) if serializer.is_valid(): serializer.save() message = "i suceeded" return Response(message, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I just need to know how to store multiple vehicles under single user_id. Thanks -
reloading django admin inline form updating data from the back end
I have a ModelForm for a parent model and and an InlineForm for a foreign key related model. The Inline form data is read only and can only be updated via a file upload. I have this working on the intial creation and save, but if you replace the students by uploading a new file, while the data updates properly after the upload and save, the inline form doesn't reload properly right after this save and displays an error. However, if you navigate away and return everything looks good. Models.py class Room(models.Model): room_id = models.AutoField(primary_key=True) name = models.TextField(blank=False, verbose_name = "Room Name ") code = models.TextField(blank=False) file = models.TextField(blank=False) class Meta(object): managed = False db_table = 'public\".\"room' class Student(models.Model): room = models.ForeignKey(Room, related_name="students, to_field="room_id", db_column="room_id") student_id = models.TextField(blank=False, primary_key=False) @property def grade(self): return util.get_grade(self.student_id) class Meta(object): managed = False db_table = 'public\".\"student’ admin.py class StudentsInline(admin.TabularInline): model = Student form = StudentInlineForm formset = StudentFormSet readonly_fields = ('student_id', 'grade') extra = 0 def get_actions(self, request): ''' Removes the delete action ''' actions = super(StudentsInline, self).get_actions(request) del actions['delete_selected'] return actions def has_delete_permission(self, request, obj=None): return False def has_add_permission(self, request, obj=None): return False def save_model(self, request, obj, form, change): super(StudentsInline, self).save_model(request, obj, form, … -
how do i get the hostname of a django application
I have a django application running using gunicorn and frontended by nginx. I am trying to get the full hostname of the application because I need to redirect out of the application and need to pass the external application my url so it can pass control back to me. How do I find my hostname/application name. I tried request.get_host(), but it gave me 127.0.0.1:8000 -
Django - Reverse for '' not found. '' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to sell products through paypal and the paypal return/cancel pages are not rendering properly. I've followed the examples in my lessons and checked the code a hundred times but obviously there is something I'm missing. I'm getting an error when I go to products, click buy now, login to paypal and then either cancel the purchase or buy the product and return to merchant's page. paypal_return.html and paypal_cancel.html are 2 templates saved under templates/paypal/ Can anybody see what I'm missing? Thank you! This is my app's urls.py from django.conf.urls import url, include from django.contrib import admin from paypal.standard.ipn import urls as paypal_urls from paypal_store import views as paypal_views from home import views from accounts import views as accounts_views from products import views as product_views urlpatterns = [ url(r'^admin/', admin.site.urls), # Menu url(r'^$', views.get_index, name='index'), url(r'^register/$', accounts_views.register, name='register'), url(r'^profile/$', accounts_views.profile, name='profile'), url(r'^login/$', accounts_views.login, name='login'), url(r'^logout/$', accounts_views.logout, name='logout'), url(r'^products/$', product_views.all_products), # Paypal url(r'^a-very-hard-to-guess-url/', include(paypal_urls)), url(r'^paypal-return', paypal_views.paypal_return), url(r'^paypal-cancel', paypal_views.paypal_cancel), ] This is my paypal_store/views.py from __future__ import unicode_literals from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render @csrf_exempt def paypal_return(request): args = {'post': request.POST, 'get': request.GET} … -
How can I measure execution time of each test in large (500+) test suite for Django project
I'm working with a Django project that has quite large test suite based on builtin unittest. I wonder if there is a smart way to get execution time of each test (to spot long lasting ones). I found two projects on github that are adding such functionality but at the cost of adding additional inheritance for the test class - I would like to avoid modifying each test class in order to add execution time measurements. To clarify I'm not interested in detailed profiling such as provided by e.g. pytest-profiling.