Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting module 'adminprofile.views' has no attribute 'index' error with Django
I have a submodule developccsettingsin a DJango project. In this sub-module are 4 DJango apps adminprofile, discounts, singleitems, services. When attempting to run the project, I get the error below: File "C:\WORK\TESTEVAL\TESTING\editingtheproject\developccsettings\adminprofile\urls.py", line 10, in url(r'^$', views.index, name='index'), AttributeError: module 'adminprofile.views' has no attribute 'index' Below is a picture of how things are set up: what is in urls.py from django.conf.urls import url from adminprofile import views app_name = 'adminprofile' urlpatterns = [ url(r'^$', views.index, name='index'), ] what is in views.py from django.shortcuts import render # Create your views here. def index(request): return render(request, 'adminprofile/index.html') The full Console display is below. Why am I getting this error? How can I fix it? TIA Full Console Display C:\WORK\Software\Python64bitv3.6\python.exe manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000021048F0CEA0> Traceback (most recent call last): File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\urls\resolvers.py", line 254, in check for pattern … -
django function based api not recognized in url.py - NameError
I am trying to implement function based view for rest api on Django. It produces this error, how can I solve this. url(r'^api/get_employee', get_employee, name='get_employee'), NameError: name 'get_employee' is not defined Below are some of my code excerps relating to this problem https://gitlab.com/firdausmah/railercom/blob/master/railercom/urls.py from railercomapp import views urlpatterns = [ url(r'^doc/', SwaggerSchemaView.as_view()), url(r'^api/get_employee', get_employee, name='get_employee'), https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/views.py @api_view(['GET']) def get_employee(request): return Response(Employee.objects.all().values(), status=status.HTTP_200_OK) -
Advice on Django model inheritance
I'm working on a financial app to track personal transactions. My TransactionModel has 6 different states: Buy Sell Deposit Withdrawl Interest This generic model has different fields that may be utilized depending upon the state of the transaction. I am thinking I should break that class down into a Parent Class > Children structure where there is: class Transaction(models.Model): class Meta: abstract = False .. class Buy(Transaction): The problem I'm running into is in my TransactionsListView, I'm trying to load different HTML depending upon the state of the Transaction. {% for obj in object_list %} {% if obj.status == "buy" %} {{ obj.buy_model.price }} {% elif obj.status == "sell" %} {% elif obj.status == "deposit" %} {% endif %} {% endfor %} Two part question: How do you access the child model from the parent? Is this the right way I should structure these classes? -
restricting image upload exceeding a specific dimension in django
I am working with an image-field in django and i was wondering if i can limit the dimensions of an image uploaded by the user?. Example, user should not be able to upload image exceeding the dimension of 100 by 100. Thanks in advance. -
Django form validation don't function
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution. This is my code: (The variables of class are iddented) class QuestionForm(forms.Form): subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'}, choices=SUBJECTS_SELE), label='Materia') question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}), label='Pregunta', max_length=5000) answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}), label='Respuesta correcta', max_length=1000) answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}), label='Respuesta incorrecta', max_length=1000, required=True) def clean_question(self): question = self.cleaned_data.get('question') a = "0" if not a in question: raise forms.ValidationError("Es obligatorio llenar este campo") return question def clean_answer(self): answer = self.cleaned_data.get('answer') a = "0" if not a in answer: raise forms.ValidationError("Es obligatorio llenar este campo") return answer Also I have try this way: def clean(self, *args, **kwargs): question = self.cleaned_data.get('question') answer = self.cleaned_data.get('answer') if question != "0": raise forms.ValidationError("Es obligatorio llenar este campo") if answer != "0": raise forms.ValidationError("Es obligatorio llenar este campo") return super(QuestionForm, self).clean(*args, **kwargs) Can you help me, thanks. -
Django create instance from views.py not working
I have a Django app that is basically a list app for tracking jobs that the user is applying for. Users have applications and applications have questions that the user wants to ask to the interviewers should they get an interview. So I have created a many to many relationship between the models 'Application' and 'Question' called 'Ask'. Models.py: class Application(models.Model): status_choices = ( ('NS','Not Started'), ('IP','In Progress'), ('OH','On Hold'), ('CO','Complete'), ) app_status = models.CharField(max_length=2,choices=status_choices) position = models.CharField(max_length=255) company = models.ForeignKey(Company) applied_date = models.DateField(null=True) isDeleted = models.BooleanField(default=False, blank=True) user = models.ForeignKey(User) def __str__(self): return self.position class Questions(models.Model): question = models.CharField(max_length=255) category = models.CharField(max_length=25) isDeleted = models.BooleanField(default=False, blank=True) class Ask(models.Model): #joining table question = models.ForeignKey(Questions) app = models.ForeignKey(Application) isDeleted = models.BooleanField(default=False, blank=True) So the idea is that the user creates a list of questions and then when they get an interview, they prepare for it by looking at their list of questions and assigning them to the application through a template. Questions.html: {% extends 'base.html' %} {% block body %} <h1> Questions </h1> <div class="table-responsive" align="center"> <table class="table-hover" width="75%"> <tr> <th> Category </th> <th> Question </th> <th> <a href="{% url 'JQ:create_question' %}" class="btn btn-success"> Create Question</a></th> <form method="POST"> {% csrf_token %} … -
docker image is runnign but webpage error - Docker
I have a basic django project and I am trying to get it running locally through docker. I have the docker file. I build the docker image. I ran the docker image. It is running, but my webpage shows an error on the screen like it is not connecting to the docker server... Here is what I have: docker file: FROM python:3 WORKDIR general COPY requirements.txt ./ EXPOSE 8000 RUN pip install -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Here is how I am buiding and running this project: omars-mbp:split omarjandali$ docker build -t splitbeta/testing2 . Sending build context to Docker daemon 223.7kB Step 1/7 : FROM python:3 ---> 79e1dc9af1c1 Step 2/7 : WORKDIR general ---> 04a6f8a7f92a Removing intermediate container b2ffb485e485 Step 3/7 : COPY requirements.txt ./ ---> 649d77ec499e Step 4/7 : EXPOSE 8000 ---> Running in 7d8d6fe8de1d ---> c328d885a5f1 Removing intermediate container 7d8d6fe8de1d Step 5/7 : RUN pip install -r requirements.txt ---> Running in 1c9aca43dc14 Collecting Django==1.11.5 (from -r requirements.txt (line 1)) Downloading Django-1.11.5-py2.py3-none-any.whl (6.9MB) Collecting gunicorn==19.6.0 (from -r requirements.txt (line 2)) Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB) Collecting pytz (from Django==1.11.5->-r requirements.txt (line 1)) Downloading pytz-2017.3-py2.py3-none-any.whl (511kB) Installing collected packages: pytz, Django, gunicorn Successfully installed Django-1.11.5 gunicorn-19.6.0 pytz-2017.3 … -
Django ajax jQuery autocomplete only works on one page
I've added a working search field to a navigation bar that use jQuery autocomplete. The problem is it only works on the main page. On the other pages it tries to add the source url to the end of the page url. For instance, on the home page it points to ajax_call/search, but on a company page (it's app that gathers internal data on companies) it points to company/847/ajax_call/search and obviously fails. What do I need to do so the jQuery autocomplete functionality works across the entire site (without rewriting it in every template)? Template $(function() { $("#tags").autocomplete({ minLength:2, source: "ajax_call/search/", select: function(event, ui){ window.location.href = ui.item.href; } }); }); URL url(r'^ajax_call/search/$', views.ajax_company_search, name='search-field'), View def ajax_company_search(request): if request.is_ajax(): query = request.GET.get('term', '') company_names = Company.objects.filter(company_name__icontains=query).values('company_name', 'pk') results = [] for name in company_names: name_json = dict() name_json['label'] = name['company_name'] name_json['value'] = name['company_name'] name_json['href'] = "company/" + str(name['pk']) + "/" results.append(name_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) -
Django 1.10 seed database without using fixtures
So I've looked at the documentation, as well as this SO question, and the django-seed package, but none of these seem to fit what I'm trying to do. Basically, I want to programmatically seed my Games model from an external API, but all the information I can find seems to be reliant on generating a fixture first, which seems like an unnecessary step. For example, in Ruby/Rails you can write directly to seed.rb and seed the database in anyway that's desired. If a similar functionality available in Django, or do I need to generate the fixture first from the API, and then import it? -
How to debug an AppRegistryNotReady exception in Django 1.9?
I am migrating a large project from Django 1.8 to Django 1.9, and when I try to run the project, I get a AppRegistryNotReady exception. The traceback for this problem seems completely unhelpful. Traceback (most recent call last): File "/opt/project/myproject/manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 176, in fetch_command commands = get_commands() File "/usr/local/lib/python2.7/dist-packages/django/utils/lru_cache.py", line 100, in wrapper result = user_function(*args, **kwds) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 71, in get_commands for app_config in reversed(list(apps.get_app_configs())): File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 137, in get_app_configs self.check_apps_ready() File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Since nothing in the backtrace is my project's code, how can I go about tracking down the source of this problem? -
Django tastypie error json field
how are you. I have a problem with Django Tastypie since I am returning a single field called description but I would like this field when I do a get to return an object to me. I attach the image of how I currently have it since I am consuming the api with a front and it arrives to me as a string. Thank you Imagen -
Python - Django query using auth.User model as OneToOneField
I am using the auth.User model for login info, and a custom UserProfile model for all of a user's profile data. The auth.User.username is a random string. and the UserProfile.user is the same string. When attempting to query the database table "UserProfile" I get the following error: ValueError: invalid literal for int() with base 10: '3df69698-c97d-11e7-a924-b0c0905e8512' models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=256, default=None) last_name = models.CharField(max_length=256, default=None) ... def __str__(self): return str(self.user) views.py from .models import UserProfile from django.contrib.auth.models import User def get_users(request): data = json.loads(request.body.decode('utf-8')) user_id = escape(data['id']) # error occurs here user_pref = UserProfile.objects.get(user=user_id) -
Python: How to push an entire folder tree to a git repo
How can I push all files under a certain path to a git repo (Github,Gitlab,etc.) ? Basically, I have a Django project which is remoted using Git. I would need to push files created by the application online. There are other threads but they are all getting really old and deprecated. Also, I've heard of Gitpython library but the doc seems so vague and fuzzy for me. Are there better solutions ? If not how can I implement this ? -
Django 1.11 Image Gallery with Django Filer
Problem I need to display a gallery of images on a product page. This worked when we were at Django 1.6, but have since upgraded to Django 1.11 (Big Process). I am now stuck at how to get this to work within the new environment. Right now clicking Add Image brings up a pop up where I can select the image, and the regions associated with it (US, Canada, Spain, Etc..), but after clicking "Save" The popup title changes to Popup closing... and never closes - also the image is not added to the gallery. The image I upload itself IS added to the rest of the Images within filer, however it is not added to the ProductGallery Model. What I've Got Django: 1.11.7 Django-Filer: 1.2.7 Django-Suit: 0.2.25 Vanilla-Views: 1.0.4 I have Product models, these products have a many to many relationship to a ProductGallery model like so: class Product(models.Model): gallery = models.ManyToManyField('products.ProductGallery') The ProductGallery is supposed to house Images and Videos allowing for upload of either, and providing one list to iterate through on the front end for display purposes. The ProductGallery is defined as: class ProductGallery(models.Model): limit = models.Q(app_label='media', model='image') | models.Q(app_label='media', model='video') order = models.PositiveIntegerField(default=0) content_type = … -
Why Jinja2 MemcachedBytecodeCache incompatible with django cache interface?
I'm trying to figure out this part of the doc. It says that jinja's memcached bytecode cache incompatible with django's cache interface. Unfortunately the django cache interface is not compatible because it does not support storing binary data, only unicode. You can however pass the underlying cache client to the bytecode cache which is available as django.core.cache.cache._client. But what does it mean precisely? E.g. if I use django's memcache backend with python-memcached, logic for saving data proxied to python-memcached, jinja2 doc says it supports this library. I tried to compare werkzeug and django's cache client get/set methods implementation, but didn't find a big difference. Django also officially supports pylibmc as werkzeug does. -
404, url not found when registering with router.urls
I have declared a viewset like this: class SchoolViewSet(viewsets.ViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() I used routers to register urls, like this: router = DefaultRouter() router.register(r'schools', SchoolViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), ] urlpatterns += router.urls I expected this url http://127.0.0.1:8000/schools/1/ with GET, but surprisingly is giving me 404, the same example works in docs, but not for me, please tell me whats wrong with the code. -
ValueError at /image/ Tensor Tensor("activation_5/Softmax:0", shape=(?, 4), dtype=float32) is not an element of this graph
hi I am building a image processing classifier and this code is an api to predict the image class of the image the whole code is running except this line (pred = model.predict_classes(test_image)) this api is made in django framework and m using python 2.7 def classify_image(request): if request.method == 'POST' and request.FILES['test_image']: fs = FileSystemStorage() fs.save(request.FILES['test_image'].name, request.FILES['test_image']) test_image = cv2.imread('media/'+request.FILES['test_image'].name) if test_image is not None: test_image = cv2.resize(test_image, (128, 128)) test_image = np.array(test_image) test_image = test_image.astype('float32') test_image /= 255 print(test_image.shape) else: print('image didnt load') test_image = np.expand_dims(test_image, axis=0) print(test_image) print(test_image.shape) pred = model.predict_classes(test_image) print(pred) return JsonResponse(pred, safe=False) -
Possibility of connecting two django apps within a django project
I am about to build a django project for a web app I am developing. For structural purposes, I want to know if it is possible to have two different apps within a project that communicate with each other like two different things in a single app within a django project. For example: have two different parts of a django project. users and groups. I currently have a testing project that has both within the general app of the django project. within the general project I included all parts of project in a single app. I want to know if i can break apart different parts of this project into seperate apps that can communicate with each other (templates, redirects, renders), and how I can connect them or what I need to do to connect them together. example -example -__init__.py -settings.py -urls.py -wsgi.py -general -__init__.py -admin.py -apps.py -models.py -test.py -urls.py -views.p THis is what I am thinking of doing example -example -__init__.py -settings.py -urls.py -wsgi.py -users -__init__.py -admin.py -apps.py -models.py -test.py -urls.py -views.p -groups -__init__.py -admin.py -apps.py -models.py -test.py -urls.py -views.p How can i connect the two different projects inthe urls file so I can redirect url's between the two. … -
Unexpected latency in response time at Node server
Problem statement- We are using router between internet client and downstream service. Router(service) is written in Node.js. Its responsiiblty is to pass internet client's request to corresponding downstream service, and return back the response to internet client. We are facing some delay at router level. Example- Explaining with sample example. We are facing issue in 99 percentile case - We did load/performance testing with 100 concurrency. As per result, till 95 percentile, response time looks great to internet client. But, in 99 percentile, Downstream service responds in expected time (~250ms). But router is taking 10 times more time than expected(~2500 ms). Service information- Both router, and downstream service are in same region, and same subnet. So, this delay is not because of network. Possibilities of this delay- Some threads are blocked at node service level. Thats why, not able to listen downstream service responses. Taking more time in dns lookup. Node level thread counts are less, thats why, not able to listen for all incoming response from downstream service side. To analyse this- We twicked below configurations - keepAlive, maxSockets, maxFreeSockets, keepAliveMsecs, log level. PLease check Node configurations for http/https agent - http agent configuration Code snippet of node service … -
Access Django Website from another computer on same network
As the title says I want to access my django website on a different computer on the same network. Both are running windows 10 connected to the same network. The host is connect through wifi and the other through ethernet cable. I've changed the allowed host to my ip address. ALLOWED_HOSTS = ['71.89.113.52', 'localhost', '127.0.0.1'] And ran the the server. (VIRTEN) C:\Users\HP\Desktop\BBTennis\VIRTEN\src>python manage.py 0.0.0.0:8000 But I still can't access it on the other computer. When I go to 71.89.113.52:8000 or 0.0.0.0:8000, I get the message, This site can't be reached. If possible, please present an answer with every direction I should take such as how to configure my network settings or django changes I must make. -
using websockets for user specific notifications django channels, socket.io, angular4
I am fresh to websockets, and I need to use them. current resources I am using: https://www.youtube.com/watch?v=HzC_pUhoW0I I am trying to create two things. One a messaging app and two a notification feature. Example, someone somewhere on the app does something that concerns you and you get notified about it. Example: facebook notifications As well I am trying to get a messenger app going But the messenger app will be restricted. Meaning there will be several instances of the messenger app, with different users allowed to talk on each app instance. Example. Facebook messenger group messages. (not every user on facebook is in the chat, just the ones invited) Now this has been done many, many times, so im not reinventing the wheel, I however am unsure how to proceed. I am using django, and angular 4. I am going to use socket.io on the angular side (not sure how yet) and django channels on the django side (again not sure how, but getting there) My main question is channels, How would one set up channels for each user that logs on? so user A has a channel that all user A specific info gets sent to and user B … -
django responsive rows with images
Suppose you have a bunch of images that you want to display using Django and Bootstrap/MaterializeCSS. The rule goes like this: Mobile: 2 images per row Tablets: 3 images per row Desktop: 4 images per row How would you design a loop that chooses at which point to create a new row (given a device type) and puts images into their corresponding rows? -
Caching a pandas dataframe in Heroku
I use pandas in my Django app running on Heroku using Heroku Postgres. I have a reporting page, where I create a dataframe by reading a number of db tables and performing calculations on it. The resulting dataframe has about 100000 rows and 70 columns. I then run a pivot on the dataframe to summarise the data based on user input. If the user wants to summarise (pivot) the data by another field, I then have to recalculate the entire dataframe which can take up to 10 seconds. To solve this I want to cache the dataframe so that I can quickly run the updated pivot on it and was wondering what my best options are here? Create a temp table in the database to store the results (unsure how to do this with Django - will probably have to drop down to raw sql) Save the results using redis Cache (I think this is the way to go but also unsure how to do this) Save data in a S3 bucket (I know how to do this, but I'm sure there are better ways) Something else? Feather/HDF store -
django rest framework: prefetch an initial data in serializer
I know that django has select_related and prefetch_related that can be used when querying items from database to increase its performance, and it can be used in pair with django rest framework's nested serializer. However, the problem come when I want to use the serializer to create my model for example: class CompanySerializer(serializer.serializers): employee_set = serializers.JSONField() class Meta: model = Company fields = ('id', 'employee_set') def create(self, validated_data): employee_set = validated_data.pop('employee_set') for employee in employee_set: serializer = EmployeeSerializer(data=employee) serializer.is_valid(raise_exception=True) serializer.save() class EmployeeSerializer(serializer.serializers): card = serializers.PrimaryKeyRelatedField(queryset=Card.objects.all()) class Meta: model = Employee fields = ('id', 'name', 'card') def validate(self, obj): if card.employee_set.all().count() > 3: raise serializers.ValidationError({'_error': 'invalid}) return data For example, I want to create a company with multiple employee like: request.POST: { employee_set: [ { name: 'tim', card: 1 }, { name: 'bob', card: 1 }, { name: 'jimmy', card: 2}, ] } then I can use CompanySerializer(request.POST), right? However, when I am saving this serializer, the EmployeeSerializer will iterate over each employee and query employee.card_set, which result in a lot of sql queries. Is there any way to do it similar like prefetch_related? thanks -
How to create django forms custom field
I'm trying to create custom field for arrays of strings for Django Forms but got exception I can't handle. So, according to documentation: Creating custom fields If the built-in Field classes don’t meet your needs, you can easily create custom Field classes. To do this, just create a subclass of django.forms.Field. Its only requirements are that it implement a clean() method and that its init() method accept the core arguments mentioned above (required, label, initial, widget, help_text). I've created class: class ArrayField(forms.Field): def __init__(self, required=False, initial=[], widget=None, help_text='', label=''): self.validators = [check_if_array, check_if_array_contains_str] super().__init__(required=required, initial=initial, widget=widget, help_text=help_text, label=label) def clean(self, value): return super().clean(value) Created form using created class: class MyForm(forms.Form): my_field = forms.ArrayField() And when I'm trying to use it f = MyForm({['str1', 'str2']}) f.is_valid() I've got an exception: File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 179, in is_valid return self.is_bound and not self.errors File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 174, in errors self.full_clean() File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 376, in full_clean self._clean_fields() File "C:\Dev\env\lib\site-packages\django\forms\forms.py", line 394, in _clean_fields value = field.clean(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 148, in clean value = self.to_python(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 432, in to_python return super().to_python(value) File "C:\Dev\env\lib\site-packages\django\forms\fields.py", line 379, in to_python value = value.strip() AttributeError: 'int' object has no attribute 'strip' I suppose answer is …