Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i installed python3.6 and django2.0.1 but python manage.py runserver does nothing.Why?
enter image description here the python and django is installed but python manage.py runserver does nothing -
Multiple file upload in Python Flask
I am trying to upload multiple files through the below snippet in a Flask app: @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': file = request.files['file_ref'] for x in file: if x and allowed_file(x.filename): fileX = secure_filename(x.filename) x.save(os.path.join(app.config['UPLOAD_FOLDER'], fileX)) return redirect(url_for('index')) return render_template('index.html') Here, allowed_file(args) checks for allowed file extensions. My template is: <form action="" method=POST enctype=multipart/form-data> <p><input type=file name=file_ref multiple> <input type=submit value=Upload></p> But I get the following error: AttributeError: 'bytes' object has no attribute 'filename' According to this solution: I tried using getlist() of werkzeug, but then I get this error: AttributeError: '_io.BufferedRandom' object has no attribute 'getlist' But without the for loop, single file upload works. -
python mock Django settings variable
settings.py IMAGE_LIMIT = 256 thumbnail_utils.py from settings import IMAGE_LIMIT def thumbnail(): image_memory = 10 if image_memory > IMAGE_LIMIT: return Ture else: pass test.py @patch('thumbnail.IMAGE_LIMIT', '0') def test_thumbnail(self, mock_IMAGE_LIMIT): status = thumbnail() assert status == False The above is the wrong test.I urgently want to know how I should do it. -
insert in database that is not the default DJANGO
I know django works with multiple database connections, I need to insert in a database that is not the default, but I get the following error. ProgrammingError at /api-jde/f59presapi/2279/ (1146, 'Table \'dblocal."oracle"."FPRES"\' doesn\'t exist') this is the configuration of my settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dblocal', 'USER': 'root', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'bd2': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'XXXX', 'USER': 'oracle', 'PASSWORD': 'xxxxx', }, } the bd in which I need to insert is the db2 (I'm not putting all the data here but if I have them full), in the created model I have the METa configuration with the following: class Meta: managed = False db_table = u'"oracle"."FPRES"' -
Django ManyToMany Validation Constraint
I have a ManyToMany link, and a Foreign key which links three objects. [A]>--<[B]>---[C] A can belong to many of B, and vice versa. However, A can only belong to B objects with the same parent C. I'm trying to do something in the clean() method of the model. I'm using Django Rest Framework and no ModelForms or anything like that. I haven't been able to figure it out yet -
Do i need to update AUTH_USER_MODEL in my settings.py?
I am creating my own users, Restaurant and Customer. I have extended the AbstractUser class and then created a OneToOneField field for each user. I am wondering if I need to add the AUTH_USER_MODEL in my settings.py. And also wondering what that does exactly... What I was planning on doing was adding to my settings.py: AUTH_USER_MODEL = 'myapp.Customer','myapp.Restaurant' Do I have the right idea here? My models.py: class User(AbstractUser): is_restaurant = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class Restaurant(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) restaurant_name = models.CharField(max_length=50) def __str__(self): return self.restaurant_name class Customer(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) address = models.CharField(max_length=200) def __str__(self): return self.user.get_full_name() -
ImportError: No module named 'django.core.urlresolvers' : but innate
I have a problem with Django version conflicting. when I run my Django project, I got message. ImportError Traceback (most recent call last) /usr/local/lib/python3.5/dist-packages/rest_framework/compat.py in <module>() 21 try: ---> 22 from django.urls import ( 23 NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve ImportError: cannot import name 'RegexURLPattern' During handling of the above exception, another exception occurred: ImportError Traceback (most recent call last) <ipython-input-1-0639a9fdda0c> in <module>() 1 from urllib.parse import urlencode, quote_plus 2 from urllib.request import Request, urlopen ----> 3 from hospital.serializers import HospitalSerializer ~/earlierdoctorserver/hospital/serializers.py in <module>() ----> 1 from rest_framework.serializers import ModelSerializer 2 from .models import Hospital 3 4 class HospitalSerializer(ModelSerializer): 5 class Meta: /usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py in <module>() 28 from django.utils.translation import ugettext_lazy as _ 29 ---> 30 from rest_framework.compat import JSONField as ModelJSONField 31 from rest_framework.compat import postgres_fields, set_many, unicode_to_repr 32 from rest_framework.exceptions import ErrorDetail, ValidationError /usr/local/lib/python3.5/dist-packages/rest_framework/compat.py in <module>() 24 ) 25 except ImportError: ---> 26 from django.core.urlresolvers import ( # Will be removed in Django 2.0 27 NoReverseMatch, RegexURLPattern, RegexURLResolver, ResolverMatch, Resolver404, get_script_prefix, reverse, reverse_lazy, resolve 28 ) ImportError: No module named 'django.core.urlresolvers' Looking straight at the lines of code, my project does not have that statement, and there seems to be a problem with the package … -
How to change DJango default admin login page
a beginner here in Django programming. followed several tutorials and kinda thinking how do i change the default admin page of Django? this is where the user will type http://something/admin, then it direct you to a default admin page by Django. I would like to make my own admin page. Is this an html file Django is using? if so, where can i find it so i can modify it. or where do i start? i browsed several topics here but answers are kinda vague and no beginner friendly. I hope someone could help me on this. Some snippets of my working codes(basic & default): **from urls.py:** urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('website.urls')), ] **from setting.py:** INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', ] when i hit https://localhost/admin, it takes me to this: enter image description here -
Links that I have in 'navbar' overlaps each other:/
Hello everyone:) Links that I have in 'navbar' overlaps each other when I make a transition into another link. For instance, I have a navbar menu with four different links (home, catalog, distributors and contacts) and 'home' is a base webpage. I.e when I make a transition from the base webpage 'http://127.0.0.1:8000/' to catalog I get this http://127.0.0.1:8000/catalog (all right) but then I make a transition into section 'distributors' and then I get this 'http://127.0.0.1:8000/catalog/distributors (and it's not normal) How to rectify this? My url patterns seems right :/ urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^catalog/$', views.catalog, name='catalog'), url(r'^distributors/$', views.distributors, name='distributors'), url(r'^contacts/$', views.contacts, name='Contacts'), ] Can someone help me with this problem? Django version 1.11.2 -
Django Authenticate with Remote User IIS vs. django-python3-ldap
I have a Django project, and it will be hosted on IIS from the same server. Therefore, I have two options for authentication with active directory. IIS windows authentication coupled with Django's Remote User Backend django-python3-ldap coupled with no authentication on IIS (i.e. allowing anonymous logins) What are the advantages and disadvantages of these approaches? Is security inherently more dangerous/difficult with one vs. the other? -
Django project deployed to two environments, TypeError in one environment but not the other
I have the exact same django project deployed to a staging and test environment. I'm struggling to understand why I only get this error in the test environment but not staging. <ExecutionEnvSet: JobExec job=ANDR_master_CI build_id=31 id=5980_app_branch_master> is not JSON serializable Here is a snippet of the views.py class execution(APIView): def get(self, request, platform, tool_name, job_name, build_id, format=None): this_job_execution = Execution.objects.filter(job__tool__platform__name=platform).filter(job__name=job_name).filter(job__tool__url__icontains=tool_name).filter(build_id=build_id) stage_executions = StageExecution.objects.filter(job_execution__build_id=build_id).filter(job_execution__job__tool__platform__name=platform) build_user_id = VariableName.objects.filter(name='userId') jobexec_env_set = ExecutionEnvSet.objects.filter(execution__id=this_job_execution[0].id).exclude(name_id__id=build_user_id).order_by('id') build_user = ExecutionEnvSet.objects.filter(job_execution__id=this_job_execution[0].id).filter(name_id__id=build_user_id) My question (unless you are able to determine the issue from this post) is how can I print the ExecutionEnvSet that I am querying in the environment that's working so that I can compare the results of the queries from both environments. Both environments are identical except they both have different data in the db, I'm wondering if the issue is related to this. -
Django-el-pagination for template variables inside for loop
I am having issues with django-el-pagination here is my code: includes.html {% load el_pagination_tags %} {% paginate post.comments.all using "comment_page" as comments%} {% for comment in comments %} <div class="row"> <p class="text-left mb-0 ml-4"> {{comment.message}} </p> </div> {% endfor %} {% show_more %} base.html {% for post in posts %} . # posts is a context variable display posts {% include 'includes.html' %} {% endfor %} How can I pass my template variable in the views. thank you -
Is a self-join on a model in a django app an acceptable pattern?
Apologies if this question is too subjective. If you are planning to close this question: please comment with a suggestion for a more appropriate place to post. I'm super new to django and python, and I'm building a test app that keeps track of employees and who their managers are. I would like to set up the domain model so that there there is only one list of employees, any of which can be managers, and all of which can be managed by any other employee who is designated a manager. To achieve this, I did a self-join on the Employee model and have an "is_manager" flag to keep track of who is a manager and who isn't (see model below). Is an acceptable pattern? I'm worried it violates a design principle I'm not considering and there's some hairy trap that I'm walking into as a noob. Thank you very much for your time. models.py for the app: class OrganizationTitle(models.Model): def __str__(self): return "{}".format(self.organization_title_name) organization_title_name = models.CharField(max_length=150, unique=True) class ClassificationTitle(models.Model): def __str__(self): return "{}".format(self.classification_title_name) classification_title_name = models.CharField(max_length=150, unique=True) class WorkingTitle(models.Model): def __str__(self): return "{}".format(self.working_title_name) working_title_name = models.CharField(max_length=150, unique=True) class Category(models.Model): def __str__(self): return "{}".format(self.category_name) category_name = models.CharField(max_length=150, unique=True) class Department(models.Model): … -
does galera setup cause db down and slower db read?
recently I realized after I setup master to master replication using galera, my db seems to be loading slower than usual. Also, sometimes it cannot be connected. I am currently using django and I have it setup that if main DB cannot be connected while making a request, then use the second db until the main DB is back online. I will receive an email if the DB cannot be connected while making a request. This would happen randomly and sometimes when I get the email, then right away I login into mariadb to check its status...it's actually actively running. As for db seems to be loading slower than usual is because, when I go into the django admin dashboard, usually it just boom when I check any records or go into any model but now it'll LOAD...........then show. I can barely find out any reason for this, does any one have any idea or which / where log I can setup for a more thorough check? Thanks in advance for any advices. -
'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)
i know there is a few questions related to this, but i cant seem to find a specific answer or solution i need my python django on an aws instance gives me this 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128) error but in my local it is working perfectly fine, i installed the same requirements needed to run it, it has the same virtual environment, the same version of everything. and i cant seem to find where is the error specially since it is working 100% fine and not on the server im using. the whole thing error it gives is this: error (appearently im not allowed to post images) i realize its a country with a weird name -
Generate PDF using Reportlab with custom size page and best image resolution
I have a generated Image (with PIL) and I have to create a PDF with specific size that it will contains this (full size) image. I start from size= 150mm x 105mm I generated the corresponding image 1818px x 1287px (with small border) (mm to px with 300dpi) I use this code pp = 25.4 # 1 pp = 25,4mm return int((dpi * mm_value) / pp) Now I have to create the PDF file with size page = 150mm x 105mm I use reportlab and I would a pdf with the best image quality (to print). Is possible to specify this? Is correct to create the PDF page size with this: W = ? // inch value?? H = ? // inch value?? buffer = BytesIO() p = canvas.Canvas(buffer) p.setPageSize(size=(W, H)) and to draw the image: p.drawImage(img, 0, 0, width=img.width, preserveAspectRatio=True, mask='auto', anchor='c') -
Differences between django version
Currently i am php developer, but i want to learn django and i want to go even deeper in it. I like to watch video tutorials when learning, Current version of django is 2.0.1 and most of video courses about django is 1.9 and earlier. Is there any difference between version ? if yes which one must i use ? and finally if you have any suggestions about video courses of django 2 please share with us. -
How to save to two models in one django form?
I currently have a working form for job tickets using django 2.0. I want to add the ability for multiple file uploads as supporting docs and assets. I can easily add this into the admin side of things using inlines, but how would I accomplish something similar on the front end of the site? I'm not sure how to have a form submit to two models when a key/id has yet to be set. I'm using primary keys to associate the files with the entries... models.py: class Job(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) ... class File(models.model) file = models.FileField(upload_to='uploads/%Y/%m') job = models.ForeignKey(Job, models.set_NULL, blank=True, null=True) admin.py class FileInline(admin.TabularInline): model = File extra = 0 @admin.register(Job) class JobAdmin(admin.ModelAdmin): exclude = ['ticket_number'] inlines = [FileInline] This system is great in my admin and in my templates, but I just can't figure out how to get these two to live in one form together. Is there a better way to be doing this? -
django can't reverse project level view?
I'm trying to redirect to a view after a successful POST. Not sure why it isn't working if I try to add a kwargs on it. I tried to reverse it without the extra parameters and it worked. but then when I add the additional variable which I need for some conditional statment, it cause an error. I already checked the docs, some of the issues that was raised here and namespace is the solution but as far as I understand, it's for the app level. I created the view under the project. project urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.Index_With_Email_Subscription, name="index"), path('humongousdata/', admin.site.urls), path('termsofservices/', views.Terms_Of_Services, name="termsofservices"), path('me/', include('me.urls')), path('thankyou/', views.ThankYou, name="givethanks"), ] project views.py from django.shortcuts import render, redirect from django.urls import reverse def index(request): return redirect(reverse('givethanks', kwargs={'thanks_for':'registered'})) def ThankYou(request, **kwargs): print(thanks_for) error message error screenshot -
Ajax search form django
Trying to create a search form similar to the one facebook and twitter use. Currently using ajax autocomplete function for this purpose. <div class="ui-widget"> <label for="search">Search for friends: </label> <input id="search"> </div> $(function() { $("#search").autocomplete({ source: "/accounts/ajax/search/", minLength: 2, select: function( event, ui ) }); }); Below is my view that processes my ajax request. def get_ajax_search(request): query = request.GET.get('term', '') print(query) if request.is_ajax(): qs1 = BasicUser.objects.filter(Q(first_name__icontains=query) | Q(last_name__icontains=query)) qs2 = MediaUser.objects.filter(Q(media_name__icontains=query)) results = [] for user in qs1: basic_user_json = {} basic_user_json['id'] = user.pk basic_user_json['label'] = user.first_name+" "+ user.last_name basic_user_json['value'] = user.first_name+" "+ user.last_name results.append(basic_user_json) for user in qs2: media_user_json = {} media_user_json['pk'] = user.pk media_user_json['label'] = user.media_name media_user_json['value'] = user.media_name results.append(media_user_json) data = json.dumps(results) print(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) Appreciate your help with a couple of questions: How can I redirect to a different page when selecting results. How can I display a user profile picture next to every search result Most importantly is there a better way of retrieving data from the database and sending it to the ajax function, assuming it's going to be a high load website. Any ideas or insights would be appreciated. -
How to write test for django FileBrowser - python
I used FileBrowser in my django project in one of models. class Person(models.Model): name = models.CharField(max_length=50) avatar = FileBrowseField( max_length=200, directory='avatars/', extensions=['.jpg', '.jpeg', '.png', '.gif'], ) I'm going to write test for it. but I don't know how to write. in it's documentation, it just said python manage.py test filebrowser I give it file path (str) and it raised following error: AttributeError: 'str' object has no attribute 'path' How can I write test for it? -
In Django tests, why do I need to use <Model>.objects.get() instead of what was returned by <Model>.objects.create()?
Although this is perhaps not a minimal example, I'm building on How to test an API endpoint with Django-rest-framework using Django-oauth-toolkit for authentication. I have a model Session which I'd like to be able to update using the Django REST framework. To this end I wrote the following view: from rest_framework import generics from oauth2_provider.contrib.rest_framework import OAuth2Authentication from ..models import Session from ..serializers import SessionSerializer class SessionDetail(generics.UpdateAPIView): authentication_classes = [OAuth2Authentication] queryset = Session.objects.all() serializer_class = SessionSerializer where the default permission_classes are set in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } I've written the following test case: import json from django.contrib.auth.models import User from datetime import timedelta from django.urls import reverse from django.test import TestCase, Client from django.utils import timezone from rest_framework import status from ..models import Family, Session, SessionType, SessionCategory from oauth2_provider.models import get_application_model, get_access_token_model Application = get_application_model() AccessToken = get_access_token_model() class OAuth2TestCase(TestCase): def setUp(self): self.username = "test_user" self.password = "123456" self.user = User.objects.create_user(username=self.username, password=self.password) self.application = Application( name="Test Application", redirect_uris="http://localhost", user=self.user, client_type=Application.CLIENT_CONFIDENTIAL, authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, ) self.application.save() self.TOKEN = '1234567890' self.token = AccessToken.objects.create( user=self.user, token=self.TOKEN, application=self.application, scope='read write', expires=timezone.now() + timedelta(days=1) ) self._create_session() def _create_session(self): self.session_category = SessionCategory.objects.create( name='Birth Prep') self.session_type = SessionType.objects.create( title='Initial Postpartum Lactation', category=self.session_category) self.family = … -
How do I display only the non empty or non null fields from a django a model?
I have a model called Address and it has about 7 different fields. The corresponding form for this model is completely optional and the user may fill in either all 7 fields or just 1 field or none of the fields. There are no required fields here. Now, if the user has filled only the city and country field, how would I in my class method fetch only those fields and then display it properly in the template? This is the closest I've come to achieving what I want: class Address(models.Model): address_name = models.CharField(...) line1 = models.CharField(...) line2 = models.CharField(...) line3 = models.CharField(...) city = models.CharField(...) state = models.CharField(...) zipcode = models.CharField(...) country = models.CharField(...) def get_fields(self): values = [] for field in Address._meta.fields: if field.name in ('line1', 'line2', 'line3', 'city', 'state', 'postcode', 'country'): if field.value_to_string(self): values.append(field.value_to_string(self)) return values In my template: {% for field in address.get_fields %} {{field}}{% if not forloop.last %}, {% else %}.{% endif %} {% endfor %} Now this achieves almost what I want, but in one of the test cases, if only one field has been filled out (for ex: only country was filled), it prints: , US. How do I make it say only … -
Generate url for Django Simple History historical object
Given an model called Stuff, I want the url to a HistoricalStuff object. In other words, how does one implement get_historical_url in the below code snippet? stuff = Stuff.objects.first() stuff.pk -> 100 historical_stuff = stuff.history.first() # we want to get url for this historical_stuff.pk -> 1 get_historical_url(historical_stuff) -> /path/to/admin/stuff/100/history/1 Obviously the dumb solution would be to use a format string but I'd rather use urlresolvers -
How to use serializer in Rest Frame work
I'm really new at django rest framework .It's a very noob question but i'm not able to understand how does serializer work ? How do we send data to serializer and how do we get data from it. I'm trying to serialize my queryset as it is a list of dictionaries here is my views.py def get(self,request): z= int(request.GET.get('q','')) queryset=[] queryset.append(models.Cart.objects.filter(UserId=z).values('id')) k=[] for values in queryset: k.append(models.ProductsDiscription.objects.filter(id=values).values()) abc = serializers.NewSerializer(k,many=True) return JsonResponse({'pcartlist':((abc))}) if i dont use a serializer i get an error "k:queryset is not json serializable. so i tried to create a serializer for this error and still im getting the same error.i dont have any idea how to work with serializer serializers.py class NewSerializer(serializers.Serializer): product_id= serializers.IntegerField() k is the list of dictionries and i also dont know which field to use for that. i have tried reading and understanding from evry possible place but im unable to.so,please help me understand how serializers work ,if possible by giving a very simple example.it will be very helpful.Thank you