Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can to raise exception in unit test?
I have same code: def foo(self): x = self.a + self.b try: res = self.a / self.b except ZeroDivisionError: res = foo_2() except AttributeError: res = foo_3() except CustomError: res = foo_4() return res def foo_2(): ... def foo_3(): ... def foo_4(): ... How can to raise ZeroDivisionError, AttributeError etc in unittest or mock? -
Rendering PDF template in django in arabic langauge
I have a problem with rendering pdf template in arabic words that i made table contains rows of classes (goods) in store here is the code of Generate pdf def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("iso-8859-6")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None in encode i put iso-8859-6 i searched for arabic encode and try this and it dos not work plaese any help thanks -
angulardart and django_rest. unable to get data from the backend
Exception: Server error; cause: Expected a value of type 'int', but got one of type 'String' advert.dart it is hero.dart class Advert { final int id; String title, owner, description, date; Advert(this.id, this.title, this.owner, this.description, this.date); factory Advert.fromJson(Map<String, dynamic> advert) => Advert(_toInt(advert['id']), advert['title'], advert['owner'], advert['description'], advert['date']); Map toJson() => {'id': id, 'title': title, 'owner': owner, 'description': description, 'date': date}; } int _toInt(id) => id is int ? id : int.parse(id); advert_service.dart it's hero_servise.dart import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart'; import 'advert.dart'; class AdvertService { static final _headers = {'Content-Type': 'application/json'}; static const _advertsUrl = 'http://127.0.0.1:8000/adverts/'; final Client _http; AdvertService(this._http); Future<List<Advert>> getAll() async { try { final response = await _http.get(_advertsUrl); final adverts = (_extractData(response) as List) .map((value) => Advert.fromJson(value)) .toList(); return adverts; } catch (e) { throw _handleError(e); } } Future<Advert> create(String title) async { try { final response = await _http.post(_advertsUrl, headers: _headers, body: json.encode({'title': title})); return Advert.fromJson(_extractData(response)); } catch (e) { throw _handleError(e); } } dynamic _extractData(Response resp) => json.decode(resp.body)['data']; Exception _handleError(dynamic e) { print(e); // for demo purposes only return Exception('Server error; cause: $e'); } } terminal pycharm tell my it is ok [09/Feb/2020 11:45:48] "GET /adverts/ HTTP/1.1" 200 492 api_django_rest_framework This code some changed hero tour … -
Filter django queryset: Query objects with two or more reverse-related objects with a certain identical field value
Suppose we have two models like this: from django.db import models ModelA(models.Model): ... ModelB(models.Model): a = models.ForeignKey(ModelA, ..., related_name='b_models') some_field = models.CharField(...) other_field = ... ... What do I do, if I want to get a ModelA queryset containing only those objects who have two or more b_models pointing to them that have the same value for some_field? Consider this example setup: a1, a2 = ModelA.objects.create(...), ModelA.objects.create(...) b1 = ModelB.objects.create(a=a1, some_field="foo" ...) b2 = ModelB.objects.create(a=a1, some_field="foo" ...) b3 = ModelB.objects.create(a=a1, some_field="bar" ...) b4 = ModelB.objects.create(a=a2, some_field="baz" ...) b5 = ModelB.objects.create(a=a2, some_field="foo" ...) In this example the queryset should contain object a1, because objects b1 and b2 both relate to it and both have the value foo in some_field. I know that I can use .annotate(models.Count('b_models')) and then .filter(b_models__count__gte=2) to get those instances of ModelA with two or more reverse relationships from ModelB. But in this example, this would return both a1 and a2. How do I satisfy the second requirement and filter the queryset further? (Or is there an even better overall approach than my annotate clause?) -
Previous pages display after logout and session deleted
Login code: def login(request): if request.method == 'POST': user = request.POST['uname'] password = request.POST['psw'] log = User.objects.filter(username=user, password=password) if log: request.session['login'] = True return HttpResponseRedirect('/page') else: return render(request, 'login.html') else: return render(request, 'login.html') Logout code: del request.session['login'] request.session.modified = True return HttpResponseRedirect("/") After logout when I move back I am able to see the previous pages but as soon as I refresh the page it redirects me to login page and restricts me to access previous page. def page(request): if not request.session.get('login', False): return HttpResponseRedirect("/tnp_admin/") else: #access page How to not display previous pages after logout and why is session working only after refreshing page? -
How do I combine multiple models into a single serializer?
it was necessary to combine several models(4) in one serializer, but there were problems with the implementation. urls.py from django.urls import path from .views import FiltersView urlpatterns = [ path('filters/' FiltersView.as_view(), name='Filters') ] views.py from rest_framework import views from rest_framework.response import Response from rest_framework.status import HTTP_200_OK from .serializers import FiltersSerializers class FiltersView(views.APIView): def get(self, request, *args, **kwargs): filters = {} filters['model_1'] = Model1.objects.all() filters['model_2'] = Model2.objects.all() filters['model_3'] = Model3.objects.all() serializer = FiltersSerializers(filters, many=True) return Response (serializer.data, status=HTTP_200_OK) serializers.py from rest_framework import serializers class FiltersSerializers(serializers.Serializer): model_1 = Model1Serializers(read_only=True, many=True) model_2 = Model2Serializers(read_only=True) model_3 = Model3Serializers(read_only=True) But on the output I get: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ {}, {}, {} ] What could be the problem? -
Django - model structure
I'm new to Django and I'm having a situation here re my model structure: I've got a model Item representing a lot of items for sale. Some of the items have the tag. Some don't. Whichever has the tag would have the same percentage of discount: five options for the user to choose (5%, 10%, 15%, 20%, 25%); When the administrator/user increases the discount say from 5% to 15%, ALL of the items with the tag would have the same 15% discount. I'm not sure if I should set a boolean tag field and then another field for percentage or even another model hosting the discount percentage choices, or should I just set an IntegerField of tag choices for percentage? But how to keep all the items with the same tag sync? Is there a way which consumes the least resources? -
How to serve raster tiles with GeoDjango and Mapbox
I'm trying to add a tiles as layer on my map based on GeoDjango. I've followed the indication in this example even if is related to the map style. I'm using this: map.on('load', function() { map.addSource('raster_tiles', { 'type': 'raster', 'tiles': [ '/static/tiles/quarto/{z}/{x}/{y}.png' ], 'tileSize': 256, }); map.addLayer({ 'id': 'simple-tiles', 'type': 'raster', 'source': 'raster_tiles', 'minzoom': 0, 'maxzoom': 22 }); }); There are no error in FireFox's console but in Python's console I see this: [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4418/3073.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4418/3075.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4420/3075.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4421/3074.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4421/3073.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4417/3074.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4421/3075.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4417/3073.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4417/3075.png HTTP/1.1" 404 1812 [05/Feb/2020 10:44:37] "GET /static/tiles/quarto/13/4421/3072.png HTTP/1.1" 404 1812 Something is wrong, but what? -
isnull not returning objects with no ForeignKey
I'm need to show all my Lists that have not a Seller assigned. A seller is just a custom User objects, with is_seller set to True. A user is the same custom User object, with is_client set to True. def free_lists(request): free_lists = List.objects.filter(seller__isnull=True) #free_lists = List.objects.filter(seller__isblank=True) #free_lists = None #This works but, obviously returns None but template renders. return render(request, 'scolarte/listas/listas-libres.html', {'free_lists':free_lists}) models.py: class List(models.Model): LISTA_STATUS = ( ('recibida_pagada', 'Recibida y pagada'), ('recibida_no_pagada', 'Recibida pero no pagada'), ('en_revision', 'En revision'), ('en_camino', 'En camino'), ('entregada', 'Entregada'), ('cancelada', 'Cancelada') ) name = models.CharField(max_length=100, default='Lista anónima') user = models.ForeignKey(User, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='vendedor') school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_no_pagada') created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_at'] def __str__(self): return str(self.id) models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_client = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) Error: NoReverseMatch at /listas/listas-libres/ Reverse for 'list_details' with arguments '('',)' not found. 1 pattern(s) tried: ['listas/lista\\-detalles/(?P<lista_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/listas/listas-libres/ Django Version: 3.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'list_details' with arguments '('',)' not found. 1 pattern(s) tried: ['listas/lista\\-detalles/(?P<lista_id>[0-9]+)/$'] Exception Location: D:\virtual_envs\scolarte\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: D:\virtual_envs\scolarte\Scripts\python.exe Python Version: 3.7.3 Python … -
How to fix Heroku Application Error after deploying
I need help with deploying this django app. My app name is fixandflex, Thanks in advance This is in my Procfile web: gunicorn fixandflex.wsgi LOGS: (fixandflex_second) PS C:\python projects\fixandflex_second> **heroku logs --tail --app desolate-woodland-37041** 2020-02-09T15:18:12.160704+00:00 app[web.1]: self.load_wsgi() 2020-02-09T15:18:12.160704+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-02-09T15:18:12.160705+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-02-09T15:18:12.160705+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-02-09T15:18:12.160705+00:00 app[web.1]: self.callable = self.load() 2020-02-09T15:18:12.160705+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-02-09T15:18:12.160706+00:00 app[web.1]: return self.load_wsgiapp() 2020-02-09T15:18:12.160706+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-02-09T15:18:12.160706+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-02-09T15:18:12.160706+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app 2020-02-09T15:18:12.160706+00:00 app[web.1]: mod = importlib.import_module(module) 2020-02-09T15:18:12.160707+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/init.py", line 127, in import_module 2020-02-09T15:18:12.160707+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-02-09T15:18:12.160707+00:00 app[web.1]: File "", line 1006, in _gcd_import 2020-02-09T15:18:12.160707+00:00 app[web.1]: File "", line 983, in _find_and_load 2020-02-09T15:18:12.160708+00:00 app[web.1]: File "", line 965, in _find_and_load_unlocked 2020-02-09T15:18:12.160708+00:00 app[web.1]: ModuleNotFoundError: No module named 'fixandflex.wsgi' 2020-02-09T15:18:12.160804+00:00 app[web.1]: [2020-02-09 15:18:12 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-02-09T15:18:12.193506+00:00 app[web.1]: [2020-02-09 15:18:12 +0000] [4] [INFO] Shutting down: Master 2020-02-09T15:18:12.193607+00:00 app[web.1]: [2020-02-09 15:18:12 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-02-09T15:18:12.262188+00:00 heroku[web.1]: Process exited with status 3 2020-02-09T15:19:06.178902+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-09T15:19:05.740407+00:00 app[api]: Deploy fc360399 by user zameermuhammad92@gmail.com … -
Django rest framework dynamic view class selection
I am looking for a way dynamically selecting (based of feature flag value) a view class for the same endpoint The problem I'm trying to tackle is having different behaviour (permission, serializer, search fields etc..) for certain feature flag value, and I would like to make the selection in a single point, not for every attribute separately Is there a way doing so? -
NoReverseMatch Django 2 Python
NoReverseMatch Reverse for 'Edit_Product' with no arguments not found. 1 pattern(s) tried: ['shop/product/Edit_Product/(?P[0-9]+)$'] I could not understand the reason behind this error I tried looking for answers for around the web but nothing worked for me so far, I am new to django and trying to develop my skills if anyone can help please Models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.id, self.slug]) forms.py class EditProduct(forms.ModelForm): class Meta: model = Product fields = ["category", "name", "image", "description", "price", "available"] views.py @staff_member_required def Edit_Product(request, id=None): product = get_object_or_404(Product, id=id) if request.method == "POST": form = EditProduct(request.POST, instance=product) if form.is_valid(): form = form.save(commit=False) form.save() return render(request, 'shop/product/Edit_Product.html', {'product': product, 'form':form}) else: form = EditProduct(instance=product) return render(request,'shop/product/Edit_Product.html', {'form': form}) urls.py urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='product_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), path('shop/Create_Product/', views.Create_Product, name='Create_Product'), path('shop/product/Edit_Product/<int:id>', views.Edit_Product, name='Edit_Product'), ] I would be really grateful for any help I have been having for days now and when modifying … -
django-allauth: NoReverseMatch at /signup/ Reverse for 'google_login' not found
I am using django-allauth library to integrate Facebook and Google login into my website (on localhost). I have been unable to implement the Facebook login function (here is my unanswered question, so I've tried to do the same for Google. I am getting this error: NoReverseMatch at /signup/ Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name. I have the following code. In settings.py: ALLOWED_HOSTS = [ '127.0.0.1', 'localhost', ] INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] ... ... ... AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "accounts.backends.EmailAuthenticationBackend", "allauth.account.auth_backends.AuthenticationBackend", ] SITE_ID=1 SOCIALACCOUNT_PROVIDERS = \ {'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'kr_KR', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}} In urls.py (general project urls, however I tried to set this for accounts.urls separately, to no avail either): urlpatterns = [ ... path('', include('accounts.urls')), path('accounts/', include('allauth.urls')), path('admin/', admin.site.urls), ] In signup.html: {% load socialaccount %} {% providers_media_js %} ... <a class="facebook-login" href="{% provider_login_url "facebook" method="js_sdk" %}"> <i class="ion-logo-facebook"></i> <div>Sign up with Facebook</div> ... <a class="google-login" href="{% provider_login_url "google" %}"> <i class="ion-logo-google"></i> <div>Sign up with Google</div> ... I … -
How to Add custom manager to third-party app's model
I have added is_active field in all my models for adding soft-deleting functionality and added a custom manager for fetching active objects class SoftDeleteManager(models.Manager): def get_queryset(self): return super(SoftDeleteManager, self).get_queryset().filter(is_active=True) class Student(models.Model): is_active = models.BooleanField(default=True) active_objects = SoftDeleteManager() objects = models.Manager() Further, I want to add the same active_objects manager on auth.User model too but as this model is not defined in my code-base I am not sure how to proceed. -
(django port problem)django webserver only didn' apply css port 8000.Another port is working well. I don't know cause
django webserver only didn' apply css port 8000 port 8200 8400 apply css well. only port 8000 didn't apply css 1)this is port 8000 2)this is port 8200 3)this is port 7400 what is the cause in this situation? -
Why Docker Django admin crash with code 245
I am running Django version 3.0.3 with runserver on OSX 10.15.3. With my app no problem but when I try to access http://localhost:8000/admin/ the container crash with "exited with code 245" I have nothing more in Docker logs, looks like a python problem, any idea how to debug. Thanks -
Django URL mapping scenario help required
How can I perform these url mappings in Django: urlpatterns=[ url(r'^.*', include('Authenticate.urls')), url(r'^.*', TemplateView.as_view(template_name="index.html"), name="home") ] With first mapping I want to make sure any url should go through authenticate view first to get authentication done. From first views when authentiaction is done then I want to redirect to the same URL. But this time I don't want it to get mapped with first mapping but I want it to get mapped with second URL so that index.html file can be loaded. I know, I cant map same url to two times and even if I do so, it will always match with first mapping and because of that the process of authentication will go in a loop. But when the initial url can be anything and after redirection I want to go on that same URL, I need to map both with url(r'^.*') How can I overcome this scenario? -
Django DateTimeField incorrect value
I'm trying to update my DateTimeField to datetime.now() but it always updates it to the same time, what do I do with that? Just to be clear, I know about auto_now and datetime.now without parentheses, those solutions don't work for me. In my case I want my field to be equal to null by default and then I want it to be only updated directly, not when any other field is updated. -
How do I return the search term within a Django's Generic Class Based ListView
I would like to return the search term along with the search results. I did try to add the search term within the context dictionary and tried to return the context object, but that doesn't work. When I just return the search results without the search term, it works perfectly. Could anyone please help me on how I could return the search term, along with the search results. Thank you so much for your help in advance. Below is my code for your kind reference. class JobSearchView(ListView): model = Job template_name = 'jobs/job_search_results.html' ordering = ['-published_date'] context_object_name = 'search_results' paginate_by = 10 def get_queryset(self): search_results = [] distinct_search_results = [] query = self.request.GET.get('search_term') keyword_list = query.split(" ") print(keyword_list) for keyword in keyword_list: print(keyword) posts = Job.objects.filter( Q(title__icontains=keyword) | Q(organization__name__icontains=keyword) | Q(type__icontains=keyword) | Q(address__icontains=keyword) | Q(city__icontains=keyword) | Q(state__name__icontains=keyword) | Q(pincode__icontains=keyword) | Q(min_qualification__icontains=keyword) | Q(desired_qualification__icontains=keyword) | Q(profession__name__icontains=keyword) | Q(department__name__icontains=keyword) ).distinct() for post in posts: search_results.append(post) context = { 'search_query': query, 'search_results': search_results } return context -
why gunicorn saying FATAL Exited too quickly (process log may have details)?
this is my gunicorn.conf file [program:gunicorn] directory=/home/ubuntu/js/ command=/home/ubuntu/.local/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/js/app.sock main_jntu.wsgi:application autostart=true autorestart=true stderr_logfile=/var/log/gunicorn/gunicorn.err.log stdout_logfile=/var/log/gunicorn/gunicorn.out.log [group:guni] programs:gunicorn after checking the status it shows guni:gunicorn FATAL Exited too quickly (process log may have details) help me this out -
Change mime-type of uploaded file in Django
I working with docx using python-docx libary, which does not support docm. Macros needed only for validating data when human enters text in that file. When uploading file i need just a content. python-docx is throwing that is not a Word file, content type is 'application/vnd.ms-word.document.macroEnabled.main+xml' How can i change mime-time of uploaded document to trick the python-docx -
Django how to pass basic authorization headers in requests?
I'm totally beginner at Django (from a Node/Express background). I need to to make a call to an API that uses basic authorization. To make requests i'm using the requests module but I don't know where to pass the auth headers. In Axios I normally set the default headers like this: import axios from 'axios' const token = `Basic ${Buffer.from(`${process.env.API_USERNAME}:${process.env.API_PASSWORD}`).toString('base64')}`; axios.defaults.baseURL = process.env.API_URL; axios.defaults.headers.common['Authorization'] = token; My service in Django: from base64 import b64encode import requests import environ environ.Env.read_env() endpoint = 'some url' credentials = f"{env('API_USERNAME')}:{env('API_PASSWORD')}" encodedCredentials = str(b64encode(credentials.encode("utf-8")), "utf-8") auth = f'"Authorization": "Basic {encodedCredentials}"' def get_api_data(): return requests.get(endpoint).json() How should I pass the headers? -
How to exclude "hidden" type fields while updating the form field values using jQuery
In my Django application, I am trying to update input fields using jQuery. The fields being updated are formset fields and one of the fields is related to a parent model for enforcing foreign key relationship. As is designed in Django, the foreign key fields are also cloned during dynamic formsets addition and have type "hidden" as against other visible fields as defined (in models/form widgets). This is what I am doing to update a value in a text type field (during form addition): $('#'+tempNumTag + ' input').val(tempNum); where: tempNumTag : Hash tag constructed for each row of formset tempNum: Value being updated in the field (with id "tempNumTag") Doing so my text type inputs get updated with the value ("tempNum") but the "hidden" field's "value" also gets updated at the same time, with the same value as that of the variable "tempNum". What I would like to do instead is: // if field type is not hidden { // Something on the line: "input:hidden" $('#'+tempNumTag + ' input').val(tempNum); // } so that the hidden field is excluded from the above update. How may I do a conditional update excluding hidden field? -
'csv' file does not import data if any instance already exists (django-import-export)
I am using django-import-export to export and import my model's data to csv and xls format. Export is working just fine but while importing if there is any instance in the file that already exists, import fails. Moreover, I have same mechanism for 2 models (Route and Stops). It is working fine for Stops, but not for Route. Can someone please help? models.py class Route(models.Model): DIRECTION_CHOICES = [ ("UP", "UP"), ("Down", "Down") ] STATUS_CHOICES = [ ("Active", "Active"), ("Inactive", "Inactive") ] TYPE_CHOICES = [ ("AC", "AC"), ("General", "General") ] name = models.CharField(verbose_name="Route Name", unique=True, blank=False, null=False, max_length=50) direction = models.CharField(verbose_name="Direction", null=False, blank=False, choices=DIRECTION_CHOICES, max_length=10) status = models.CharField(verbose_name="Status", null=False, blank=False, choices=STATUS_CHOICES, max_length=10) list_of_stops = models.TextField(verbose_name="Stops", null=False, blank=False) type = models.CharField(verbose_name="Type", null=False, blank=False, choices=TYPE_CHOICES, max_length=10) class Stop(models.Model): name = models.CharField(verbose_name="Name", unique=True, blank=False, null=False, max_length=50) latitudes = models.DecimalField(verbose_name="Latitudes", max_digits=9, decimal_places=6) longitudes = models.DecimalField(verbose_name="Longitudes", max_digits=9, decimal_places=6) def __str__(self): return self.name My save function for routes It doesn't work well, (route_file is request.POST['filename']) def import_routes(cls, route_file, file_type): route_resource = RouteResource() dataset = Dataset() if file_type == 'csv': imported_routes = dataset.load(route_file.read().decode('utf-8')[1:], format='csv') result = route_resource.import_data(dataset, dry_run=True) # Test the data import elif file_type == 'xls': imported_routes = dataset.load(route_file.read()) result = route_resource.import_data(dataset, dry_run=True) # Test the data … -
OperationalError Exception Value: no such column: registration_employeeregistration.Site_id
I have two models one is configration. The code of first model is as follow enter code here from django.db import models # Create your models here. class AddSite(models.Model): site = models.CharField(blank = False, max_length=150, verbose_name = 'Site') def __str__(self): return '{site}'.format(site=self.site) class AddDepartment(models.Model): Department = models.CharField(blank = False, max_length=150, verbose_name = 'Department') def __str__(self): return '{Depart}'.format(Depart=self.Department) class AddDesignation(models.Model): Designation = models.CharField(blank = False, max_length=150, verbose_name = 'Designation') def __str__(self): return '{Desig}'.format(Desig=self.Designation) class AddCategory(models.Model): Category = models.CharField(blank = False, max_length=150, verbose_name = 'Category') def __str__(self): return '{Category}'.format(Category=self.Category) class Rate(models.Model): site = models.ForeignKey(AddSite,on_delete=models.CASCADE) category = models.ForeignKey(AddCategory,on_delete=models.CASCADE,default=False) rate = models.IntegerField(blank=True,default=False) def __str__(self): return '{site}'.format(site =self.site) second models is employee registration from django.db import models from datetime import date from configration.models import AddSite, AddDepartment, AddCategory, AddDesignation # Create your models here. class EmployeeRegistration(models.Model): #Departmental Details EmpId = models.IntegerField(verbose_name='EmpId') Site = models.ForeignKey(AddSite,on_delete=models.CASCADE,max_length=150,verbose_name='Site') Department = models.CharField(max_length=150,verbose_name='Department') Category = models.CharField(max_length=150,verbose_name='Category') Designation = models.CharField(max_length=150,verbose_name='Designation') PfAllowance = models.BooleanField(default = True) EsiAllowance = models.BooleanField(default = True) Uan = models.PositiveIntegerField(null = False,verbose_name='Uan') Pf = models.PositiveIntegerField(null = False,verbose_name='Pf') AttendenceAward = models.BooleanField(default = True) AttendenceAllowance = models.BooleanField(default = True) ProfesionalTax = models.BooleanField(default = False) Rate = models.PositiveIntegerField(null = False) # Personal Details Name = models.CharField(max_length=150,verbose_name='Name') Father = models.CharField(max_length=150,verbose_name='Father') Dob = models.DateField() Gender …