Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When using ajax with django views, when should I use a method of GET and when should it be POST?
I'm able to accomplish the same task with either--I only need to make sure that if the ajax method is get, then my view needs to handle the get and if a POST, that the view handles a post. Given this, when do I use a GET and when do I use a POST? $.ajax({ method: "????", url: $endpoint, data: $buttonData, success: handleSuccess, error: handleError, }) class MyAjaxView(View): def ???(self, request, *args, **kwargs): -
SyntaxError: Generator expression must be parenthezised / python manage.py migrate
I'm really new in programming and I wanted to follow the Djangogirls tutorial, but I'm stucked now. In the tutorial, I am here: To create a database for our blog, let's run the following in the console: python manage.py migrate (we need to be in the djangogirls directory that contains the manage.py file). If that goes well, you should see something like this: ... There is no option to fail in the tutorial but I have an error message: (myvenv) C:\Users\Julcsi\djangogirls> python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Julcsi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 723, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_remove File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\contrib\admin\__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\contrib\admin\filters.py", line … -
Floatformat don`t work
I`m getting started using template built in Django. I want to show variable with 3 value after dot but it doestn work. Code: {% assign zmienna = 9.7567 %} {{zmienna|floatformat:2}} Effect: 9.7567 What I do wrong? -
Django-cms: How to add side navigation
I am using latest django-cms(3.5.0), i have installed it through djangocms-installer. And now i want to add extra navigation tree, since i don't want it being nested inside Main navigation. I want to add it like this: https://imgur.com/2IXwgnY How can i add it? The following apps are installed: INSTALLED_APPS = ( 'djangocms_admin_style', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.staticfiles', 'django.contrib.messages', 'cms', 'menus', 'sekizai', 'treebeard', 'djangocms_text_ckeditor', 'filer', 'easy_thumbnails', 'djangocms_column', 'djangocms_file', 'djangocms_link', 'djangocms_picture', 'djangocms_style', 'djangocms_snippet', 'djangocms_googlemap', 'djangocms_video', 'dslendavasite', ) -
Value error in Django because the view request.GET or request.POST can't catch values from javascript
I have a quiz app and there are lots of interactions between JavaScript in templates and django views. Normally, on decent enough internet connection and less traffic the code works as it is supposed to. But as soon as the internet is slow and traffic is high (ie. 20 or so people are taking a quiz at the same time) . Django views stop catching values sent from forms in template Here is an example: Template code <form action='{% url "QuestionsAndPapers:EvaluateTest" %}' method='post' id ='finishForm'> {%csrf_token%} <input type="text" name="timeTaken" value="" class='hidden' /> <button type="submit" id='testsub' value="{{te_id}}" class="btn btn-default text-center" name="testSub" onclick="formClick()" >Submit Test</button> </form> Django View: def evaluate_test(request): user = request.user me = Studs(user) if 'testSub' in request.POST: # get values of test id and total test time try: test_id = request.POST['testSub'] test_id = int(test_id) Now the problem is majority of times the template successfully returns {{te_id}} variable but when traffic is high and internet is slow evaluate_test function can't catch the {{te_id}} variable and it throws an error ValueError: invalid literal for int() with base 10: The problem is this error is not reproducible. -
select backward associated in django
I'm wrinting a Django project. In courses/models.py class Category(models.Model): title = models.CharField(max_length=50) class Language(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=50) I want to get list of all Category and then loop through each Language of specified category. class Courses(ListView): template_name = 'courses/index.html' model = Course context_object_name = 'courses' def get_context_data(self, **kwargs): context = super(Courses, self).get_context_data(**kwargs) categories = Category.objects.all() context['categories'] = categories return context in template courses/index.html I want to show the list of languages based on category {% for category in categories %} {{ category.title }} <li>lis of languages in this category</li> {% endfor %} How to loop on backward associated data? -
Where should a Django homepage template and view exist in a large-scale project?
On a large-scale Django project, where should the homepage template and view exist within the project structure? In its own app (ex: homepage app)? Some other app (ex: accounts)? At the project-level putting the template in a "templates" directory and the view somewhere? Somewhere else? Is there a most frequent answer to this question? Definitions: Large-scale is defined as let's say 15 apps The homepage content is mostly static now, with plans to get more dynamic as the project evolves Assumption: project structure strategy is dependent on the size of the project. -
Django Axes Does not block Custom Login Page
I succesfully installed Django Axes in my app and can block my admin page after a certain amount of logins INFO:axes.watch_login:AXES: Repeated login failure by {user: 'admin', ip: '127.0.0.1', user-agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5', path: '/en/login/'}. Count = 10 of 10 WARNING:axes.watch_login:AXES: locked out {user: 'admin', ip: '127.0.0.1', user-agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5', path: '/en/login/'} after repeated login attempts. Unfortunately the Custom Login Page does not get blocked. It counts up the login attempts, too, but when it says, it gets blocked, I still can access the site. Do I need another trigger to block that, too? I didn't find anything like "is_blocked()" or sth. views.py class LoginView(FormView): template_name = "account/login.html" template_name_ajax = "account/ajax/login.html" form_class = LoginUsernameForm form_kwargs = {} redirect_field_name = "next" @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(LoginView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): if is_authenticated(self.request.user): return redirect(self.get_success_url()) return super(LoginView, self).get(*args, **kwargs) def get_template_names(self): if self.request.is_ajax(): return [self.template_name_ajax] else: return [self.template_name] def get_context_data(self, **kwargs): ctx = super(LoginView, self).get_context_data(**kwargs) redirect_field_name = self.get_redirect_field_name() ctx.update({ "redirect_field_name": redirect_field_name, "redirect_field_value": self.request.POST.get(redirect_field_name, self.request.GET.get(redirect_field_name, "")), }) return ctx def get_form_kwargs(self): kwargs = super(LoginView, self).get_form_kwargs() kwargs.update(self.form_kwargs) … -
django and bootstrap modal ajax get data not working
Good day everyone. I'm trying to implement bootstrap modal for the first time in Django 1.11.6 under python 3. I'm using postgresql too. My Model class DentalProcedures(models.Model): id = models.AutoField(primary_key=True) patient = models.ForeignKey(PatientInfo, on_delete=models.CASCADE, null=True, blank=True) proc_date = models.DateField(null=True, blank=True) proc_tooth_no = models.CharField('Tooth No./s', max_length=10, null=True, blank=True) procedure = models.CharField('Procedure', max_length=200, null=True, blank=True) My Modal Form <form id="procedureForm"> {{form.as_p}} {% csrf_token %} <h2>{{ mypk }}</h2> <input type="hidden" name="patient" value="{{ mypk }}" id="id_patient"> <div id="modalTreatment" class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input id="saveProcedure" type="submit" value="Save" class="btn btn-primary" /> </div> </form> My JS $(document).ready(function(){ $('#saveProcedure').click(function(e){ // e.preventDefault(); $.ajax({ headers: {'X-Requested-With': 'XMLHttpRequest'}, type:"GET", url: "/", cache: false, data: { tooth: $('input[name="proc_tooth_no"]').val(), date: $('input[name="proc_date"]').val(), proc: $('input[name="procedure"]').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken').val() }, success : function(data) { alert("congrats!"); }, error: function(jqXHR, exception){ var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Parse error.'; msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') … -
Multi-database routing with multiple custom database admins
I am trying to use multiple database with custom admin for database. I am using routing for this. When i leave my default database empty. It shows error settings.DATABASES is improperly configured. Please supply the ENGINE value. But on filling details in default database it works fine as it uses default settings for both the urls. Project settings.py 'default': { }, 'users': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'users', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', }, 'rsa': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rsa', 'USER': '****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', }, DATABASE_ROUTERS = ['antef.router.DBRouter'] DATABASE_APPS_MAPPING = { 'login': 'users', 'rsa': 'rsa' } Project urls.py from django.contrib import admin from django.urls import path, include admin.autodiscover() urlpatterns = [ path('login/', include('login.urls')), path('rsa/', include('rsa.urls')), ] Project routers.py from django.conf import settings class DBRouter: def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label, None) def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label, None) def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label) db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_migrate(self, db, app_label, … -
What is '_get_val_from_obj' mechanic does?
I am new to tooling job. Currently my favorite package in Django is outdated and seems on one care by now. Therefore I would like to study it. Problem: https://github.com/philippbosch/django-geoposition/issues/100 Traceback (most recent call last): File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/mixins.py", line 22, in create headers = self.get_success_headers(serializer.data) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 537, in data ret = super(Serializer, self).data File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/serializers.py", line 504, in to_representation ret[field.field_name] = field.to_representation(attribute) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/lib/python3.6/site-packages/rest_framework/fields.py", line 1858, in to_representation return self.model_field.value_to_string(obj) File "/Users/sarit/.pyenv/versions/3.6.4/envs/poink/src/django-geoposition/geoposition/fields.py", line 50, in value_to_string value = self._get_val_from_obj(obj) AttributeError: 'GeopositionField' object has no attribute '_get_val_from_obj' Official Docs: https://docs.djangoproject.com/en/2.0/releases/2.0/ Field._get_val_from_obj() is removed. Question: How to solve this error? def value_to_string(self, obj): value = self._get_val_from_obj(obj) return … -
When posting to a Django form, are all fields posted?
I'm trying to write a test for a form to simulate the situation in which I'd like to update just one field. Here is the test: from django.test import TestCase from django.forms.models import model_to_dict class FamilyDemographicsUpdateTest(TestCase): def test_update_phone_types_with_fields_from_family_factory(self): # Create a family for which the employee uses an iPhone family = FamilyFactory(employee_phone_type=Family.IPHONE) url = reverse('dashboard:family', kwargs={'pk': family.id, 'tab': 'family-demographics'}) # TODO: This doesn't work because the FamilyFactory generates invalid form data. Fix that. data = model_to_dict(instance=family, fields=FamilyDemographicsForm.base_fields) form = FamilyDemographicsForm(data=data) after which I drop into the debugger with import ipdb; ipdb.set_trace(). It is here that I notice that the form has errors: ipdb> form.errors {'employee_email': ['This email is already taken.']} This can be traced back to the Family model on which the form is based. The form is a ModelForm: class FamilyDemographicsForm(forms.ModelForm): class Meta: model = Family The view is based on Django's generic UpdateView: class FamilyUpdate(SuccessMessageMixin, DashboardAccessMixin, UpdateView): template_name = 'families/edit.html' model = Family success_message = "Family was updated successfully." def get_form_class(self, **kwargs): tab = self.kwargs['tab'] if tab == 'family-demographics': return FamilyDemographicsForm and the corresponding Family object has a clean() method which is triggering this error (in class Family(models.Model)): def clean(self): if self.employee_email: db_user = User.objects.filter(username=self.employee_email).first() if db_user and … -
Chrome Mobile does not display checkbox
My website's register page has two checkbox inputs located at the bottom. On every browser I have tested on, there has been no issue. However, a user recently brought to my attention that these checkbox inputs are not displayed at all from their mobile device. I checked this on my Samsung Galaxy S7, and confirmed this finding. They do appear on my iPad and other Apple devices. Why are no checkbox inputs showing up on certain mobile devices? -
Django Messages not working when I try display error about existing user/email
In my Django project I want to use Django Message ( from django.contrib import messages) to display error when user or email exist. Unfortunately my views not working. HTML: {% for message in messages %} <p>{{ message }}</p> {% endfor %} views.py def account_signup(request): if request.method == 'POST': nick = request.POST['nick'] email = request.POST['email'] password = request.POST['password'] user_model = get_user_model() if user_model.objects.filter(username__iexact=nick).exists(): data = {'is_taken_nick': nick} messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", data) if user_model.objects.filter(email__iexact=email).exists(): messages.warning(request, 'Please correct the error below.') data = {'is_taken_email': email} return render(request, "account/account_signup.html", data) user = User.objects.create_user(username=nick, email=email, password=password) user.save() return HttpResponse(status=202) else: """Return template with sign up page.""" return render(request, "account/account_signup.html") Thanks in advance! -
Linking up CSS (and static files in general) to html in Django
My html file isn't reading my css file - I've tried searching for all related questions on this issue, but still can't get the css file to be read. Here's what I have: settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) Beginning of index.html {% load staticfiles %} <!DOCTYPE html> <html leng="en"> <head> <title>Test</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap- theme.min.css"> <link rel="stylesheet" href="{% static 'css/main.css' %}" /> </head> My "static" and "templates" folder are on the same level, and main.css is at static/css/main.css -
NoReverseMatch at /app/index I already URL
I got an error,NoReverseMatch at /app/index. I wrote in views.py def index(request): return render(request, 'index.html') def test1(request): return render(request, 'test1.html') def test2(request): return render(request, 'test2.html') in urls.py app_name = "app" urlpatterns = [ path('index', views.index,name='index), path('test1', views.test1,name='test1'), path('test2', views.test2,name='test2'), ] in index.html <tr> <td align="center "> <a class="test1" href="{% url 'test1' %} ">test1</a> </td> <td align="center "> <a class="test2" href="{% url 'test2' %} ">test2</a> </td> </tr> When I access index method, NoReverseMatch at /app/index Reverse for 'test1' not found. 'test1' is not a valid view function or pattern name. error happens. I really cannot understand why I got this error.I already test1&test2 url.How should I fix this? -
Django - .delete() command gives 'Killed' message
I'm trying to delete 85k records from a database of about 300k records, in the shell opened with python manage.py shell When I use MyModel.objects.filter(status='Ter').delete(), it would run for about 15 seconds before giving a message - Killed, and exit me out of the shell. Why is this happening? Is it because I am trying to delete too many records at once? If this deletion method is not possible, what is the best alternative way of deleting those records? -
Is Amazon Route 53 the solution for the Django All-Auth Google clash with AWS in production?
Hello fellow coding ninjas! So I just have one question. As you may know, Google Authorized redirect URIs require a .com or org domain. The AWS EC2 IPv4 Public IP option (with just numbers) does not work in production for Google Django All-auth sign-in. Is the Amazon Route 53 Domain the best way to solve the Google Django All-auth redirect issue in production? I tried using a redirect .org and .com from a dynamic DNS company but that didn't work out. Thanks! -
Django getting right return value for post.request
I am trying to get the product id using request.post in Django. I am currently testing using the console, but the only product_id value I am returned is 1. This is the particular function in the view: def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) products = Product.objects.all() if request.POST: product_id = request.POST.get('product_id') entry_quantity = request.POST.get('entry_quantity') product_obj = Product.objects.get(id=product_id) print(product_id) # print(entry_quantity) # Entry.objects.create(cart=cart_obj, product=product_obj, quantity=product_quantity) return render(request, 'carts/test.html', {'cart_obj': cart_obj, 'my_carts_current_entries': my_carts_current_entries, 'products': products}) This is the html on the template. <form method="POST"> <br> {% csrf_token %} {% for product in products %} {{ product.name }} <br> <button>Add to Basket</button> {{ product.id }} <input type="hidden" name='product_id' value='{{ product.id }}'> <br> {% endfor %} </form> -
Access the form that caused a post_save [Django]
Is there a way I can access the form that caused a post_save? The use case is that I have a field (a checkbox) that isn't attached to a particular model, but it's an extra field in the form itself. I want to know whether the field was checked or unchecked when the form got saved and the model stored, and imho the post_save signal is a good place to put the logic that should process that extra field. I'm also open to suggestions where else I could put that piece of code. -
Stripe: When customer adds card I'm able to receive and store 'source' token in customer model. But Not able to charge customer
def book_now(request): """Schedule Appointment""" if request.method == 'POST': customer = Customer.objects.get(user_id=request.user.id) token = request.POST.get('stripeToken') customer.default_source = token customer.save() charges.create( amount=decimal.Decimal("119.99"), customer=request.user.customer.stripe_id, ) return render(request, 'appointment/book_now.html') Here you can see that I save the token to a Customer. This works successfully. Then When I try to charge customer I get the error that they do not have a card. When I log in to stripe.com, the user does not have a card. And I understand this part because token was never sent to stripe. But my thinking is that it would be sent during the charge. -
suspiscious dependencies in my requirements.txt
asn1crypto==0.22.0 cryptography==1.9 enum34==1.1.6 gyp==0.1 idna==2.5 ipaddress==1.0.17 keyring==10.4.0 keyrings.alt==2.2 pycrypto==2.6.1 pygobject==3.24.1 pyxdg==0.25 SecretStorage==2.3.1 six==1.10.0 virtualenv==15.1.0 These are the dependencies in my requirements.txt in which I never installed while i was setting up a django project, and yet they appeared. Anyone have a clue what these dependencies are? -
Python/Django: Add Data To Localhost DB in PostgreSQL
I'm new to python and Django, currently learning Django REST FW. I've managed to connect to my local postgreSQL db, and have migrated a table as well with the below model from djan go.db import models # Create your models here. class Publisher(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) models.CharField(max_length=30) I'd like to make a post request to /name, take the input values and insert into my db. For now i'll just be happy with hard coding the values per post request. Any ideas how to accomplish this? -
django-import-export :ForeignKey with many fields
I need just export data from my admin. My code now looks like: models.py from django.db import models from services.models import Services,PromoCodes,CauseOfReservedPromocodes # Create your models here. class User(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) email=models.EmailField() password=models.CharField(max_length=200) telephone=models.PositiveIntegerField(max_length=12,blank=True,null=True) userRequest=models.ForeignKey('UsersRequests', blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name + " " + self.surname class UsersRequests(models.Model): date = models.DateField() requestChannel = models.CharField(max_length=30) problem = models.CharField(max_length=200) solution = models.CharField(max_length=200) def __unicode__(self): return str(self.date) + " " + str(self.requestChannel) + " " + str(self.problem) + " " + str(self.solution) And my admin.py is: from django.contrib import admin from .models import User,UsersRequests from import_export import resources, widgets, fields from import_export.admin import ImportExportModelAdmin,ExportMixin class UsersResource(resources.ModelResource): class Meta: model = User fields = ('id', 'name', 'email', 'telephone', 'userRequest') class UserAdmin(ImportExportModelAdmin): resource_class = UsersResource @admin.register(User) class UserAdmin(ImportExportModelAdmin): search_fields = ('name', 'surname', 'email', 'telephone') I try everything to get userRequest work, but it send just integer - id for userRequest. How to get full data from class UsersRequests(models.Model)? -
PostgreSQL/PostGIS Stack builder missing dlls (GeoDjango)
I've installed GeoDjango Spatial Database libraries using Enterprise DB Stack for Postgres 10 and it includes following packages. I am using Windows 10 OS and needed to setup GeoDjango. Please assist PostGIS 2.4.3 bundle includes PostGIS 2.4.3 w GDAL 2.2.3, GEOS 3.6.2, Proj 4.9.3, pgRouting 2.5.2, osm2pgrouting 2.3.3, ogr_fdw 1.0.5 But now on Python I get this error below and I tried many posted answers but couldn't make it work. Quick hint will be great help. Below is the error: (gigfinder) C:\Users\dell\gigfinder\gigfinder>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Users\dell\gigfinder\lib\site-packages\django\core\management\__init__.py", line 324, in execute django.setup() File "C:\Users\dell\gigfinder\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\dell\gigfinder\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "c:\python27\Lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\dell\gigfinder\lib\site-packages\django\contrib\auth\base_user.py", line 49, in <module> class AbstractBaseUser(models.Model): File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\base.py", line 299, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\dell\gigfinder\lib\site-packages\django\db\utils.py", line 212, in …