Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to install Microsoft Visual C++ 10.0?
error: Microsoft Visual C++ 10.0 is required. Get it with "Microsoft Windows SDK 7.1": www.microsoft.com/download/details.aspx?id=8279 How to properly install Microsoft Visual C++ 10.0 step by step and get out of this erroe? OS: Windows 10 64bit -
Django Multitenancy
how to check for multitenancy on localhost ? Is it ok to add prefix abc like "abc.localhost:8080" or def like "def.localhost:8080",I had referred [django documentation][1] [1]: https://django-tenant-schemas.readthedocs.io/en/latest/use.html to create tenant schema, however, confused over how to check multitenancy on localhost ? -
ERROR Exception in class GetFeedbackArea:The response content must be rendered before it can be iterated over
when i hit that API , it is showing me error,The response content must be rendered before it can be iterated over. class GetFeedbackArea(APIView): parser_classes = [ReadJSONParser] authentication_classes = [OAuth2Authentication] permission_classes = [IsAuthenticated] def post(self, request, format=None): """ Creation of feedback with respect to jobcard_id :param request: :return: """ try: logger.info("GetFeedbackArea") data, stat = get_feedback_area(request) new_data = generic_feedback_area_translator(data) return Response({"data":new_data},status=status.HTTP_200_OK) except Exception as ex: logger.exception("Exception in class GetFeedbackArea:" + str(ex)) excp_logger.exception("Exception in class GetFeedbackArea:" + str(ex)) return Response(sa_error_conf.SOMETHING_WENT_WRONG, status=status.HTTP_412_PRECONDITION_FAILED) -
Passing email to path in django
I have code like this:- path(something/regex_email/, views.func, name="something"), and if user enters any email in url like something/anyemail/ then the user should be redirected to some page.... -
Post to Django view using JQuery AJAX
I'm slightly confused trying to post to a Django view with a JQuery / AJAX function on the client-side. I want to post to the radius view when a user presses a filter button which filters local users in a given radius of 10 or 20 km. The queryset in the radius view should take the request.user lat lon coordinates along with a pre-defined radius_km of 10 or 20km. How can I post these requests (lat, lon, radius) to the view? urls.py urlpatterns = [ path('', connect_views.connect_home_view, name='connect_home'), path('insert', connect_views.insert, name='insert'), path('radius', connect_views.radius, name='radius'), views.py def connect_home_view(request): return render(request, 'connect/home.html', context) def insert(request): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) def radius(request): radius_km = request.data.get('radius', 0) queryset = User.objects.annotate( radius_sqr=pow(models.F('loc__latitude') - request.user.loc.latitude, 2) + pow(models.F('loc__longitude') - request.user.loc.longitude, 2) ).filter( radius_sqr__lte=pow(radius_km / 9, 2) ) context = dict(location=queryset) return render_to_response('connect/home.html', context) models.py class Location(models.Model): latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='loc') connect.html <!-- request.user lat / lon and save to Location model --> <script> var pos; var $demo; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { $demo.text("Geolocation is not supported by this browser."); } } function showPosition(position) { pos … -
django identation error in Except UserDoesNotExist
THis is views.py file which show error please help if u know django i m also uploading the image which show what is the error and please help me as soon as possible -
Django Deserialization Error Problem installing Fixture
Traceback (most recent call last): File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/serializers/json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/serializers/python.py", line 91, in Deserializer Model = _get_model(d["model"]) KeyError: 'model' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 168, in load_label for obj in objects: File "/Users/sparshkedia/Desktop/task/venv/lib/python3.6/site-packages/django/core/serializers/json.py", line 73, in Deserializer raise DeserializationError() from exc django.core.serializers.base.DeserializationError: Problem installing fixture '/Users/sparshkedia/Desktop/task/movie_rs/movies.json' This is the above error showing when I am trying to deserialize my json file into the database. My json file looks like this: [ { "description": "A cowboy doll is profoundly threatened and jealous when a new spaceman figure supplants him as top toy in a boy's room.", "genre": "Animation,Adventure,Comedy,Family,Fantasy", "imdb_url": "https://www.imdb.com/title/tt0114709/", "img_url": "https://m.media-amazon.com/images/M/MV5BMDU2ZWJlMjktMTRhMy00ZTA5LWEzNDgtYmNmZTEwZTViZWJkXkEyXkFqcGdeQXVyNDQ2OTk4MzI@._V1_UX182_CR0,0,182,268_AL__QL50.jpg", "movie_id": 114709, "title": "Toy Story", "users_rating": 8.3, "year": 1995 }, { "description": "George Banks must deal not only with the pregnancy of his daughter, but also … -
Cannot run deployed django app on heroku (Application error)
Python version: 3.5, Django version: 2.1, Django project title: main, Heroku add-on: Heroku Postgres When I run git push heroku master Project is deployed on heroku but produces error when url is accessed. heroku logs Settings.py import django_heroku ALLOWED_HOSTS = ['0.0.0.0', 'localhost', 'crowdsocial.herokuapp.com'] WSGI_APPLICATION = 'main.wsgi.application' django_heroku.settings(locals()) Procfile web: gunicorn main.wsgi --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") application = get_wsgi_application() runtime.txt python-3.5.2 Django project tree I also ran heroku ps:scale web=1 Need help! -
Change to PostgreSQL raise django.db.utils.OperationalError: no such table Error
I was developing with default DB SQLite for a Django project but now I need to deploy to Heroku so I switched to PostgreSQL. However, during the deployment, I kept getting django.db.utils.OperationalError: no such table: error: full error in heroku logs --tail: 2019-02-09T02:00:32.984061+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ 2019-02-09T02:00:32.984063+00:00 app[web.1]: raise dj_exc_value.with_traceback(traceback) from exc_value 2019-02-09T02:00:32.984064+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute 2019-02-09T02:00:32.984066+00:00 app[web.1]: return self.cursor.execute(sql, params) 2019-02-09T02:00:32.984068+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute 2019-02-09T02:00:32.984069+00:00 app[web.1]: return Database.Cursor.execute(self, query, params) 2019-02-09T02:00:32.984071+00:00 app[web.1]: django.db.utils.OperationalError: no such table: product_floor 2019-02-09T02:00:32.995728+00:00 app[web.1] As you can see, there should be a table called product_floor in SQLite. But the problem is, I have already updated my db configuration to PostgreSQL and deleted SQLite3 file in my project folder. I also deleted all migration files and cached files and ran python manage.py makemigrations and python manage.py migrate again. When I turned DEBUF to true and access pages in local browser, there's no problem. But when I access certain pages servered in url *.herokuapp.com/product/*(pages that use data from database), I got Server Error 500. My models.py from django.db import models from django.conf import settings from django.utils import timezone class Floor(models.Model): name = models.CharField(max_length=20, verbose_name='floor … -
How do I order the import fields in admin using django import-export?
I am using django import-export and ImportExportModelAdmin to import data from a file to the database from the admin interface. Below is the model resource i use: class ImportedBetResource(resources.ModelResource): date = fields.Field(column_name='Date', attribute='date', widget=DateWidget(format="%d/%m/%Y")) time = fields.Field(column_name='Time', attribute='time', widget=TimeWidget(format="%H:%M")) sport = fields.Field(column_name='Sport', attribute='sport', widget=ForeignKeyWidget(Sport, 'name')) country = fields.Field(column_name='Country', attribute='country', widget=ForeignKeyWidget(Country, 'name')) bookie = fields.Field(column_name='Bookie', attribute='bookie', widget=ForeignKeyWidget(Bookie, 'name')) currency = fields.Field(column_name='Currency', attribute='stake_currency', widget=ForeignKeyWidget(Currency, 'name')) odds = fields.Field(column_name="Odds", attribute="odds", widget=DecimalWidget()) status = fields.Field(column_name='Status', attribute='status', widget=ForeignKeyWidget(Status, 'name')) class Meta: model = Bet fields = ("id", "date", "time", "sport", "country", "competition", "home", "visitor", "bookie", "bet", "stake", "currency", "odds", "status") clean_model_instances = True @classmethod def field_from_django_field(self, field_name, django_field, readonly): """ Returns a Resource Field instance for the given Django model field. """ FieldWidget = self.widget_from_django_field(django_field) widget_kwargs = self.widget_kwargs_for_field(field_name) field = fields.Field(attribute=field_name, column_name=field_name.replace("__name", "").title(), widget=FieldWidget(**widget_kwargs), readonly=readonly) return field This is a screenshot of the import view from the documentation: You can see the text "This importer will import the following fields" followed by the fields names. In my case, the explicitly defined fields appear first, ex.: country = fields.Field(column_name='Country', attribute='country', widget=ForeignKeyWidget(Country, 'name')) and then the remaining fields defined in class Meta fields: This importer will import the following fields: Date, Time, Sport, Country, Bookie, Currency, Odds, … -
i am facing problem nesteded serilizer django in attribute error AddressSerilizer
class AddressSerilizer(serializers.ModelSerializer): class Meta: model = Address fields = ( 'id', 'address_line1', ) class UserRegisterSerilizer(serializers.ModelSerializer): address_data = AddressSerilizer(many=True, read_only=True, required=False) class Meta: model = User fields = ('id', 'mobile_number', 'email', 'password', 'address_data') def create(self, validated_data): address_get = validated_data.pop('address_data') user = User.objects.create(**validated_data) for add in address_get: Address.objects.create(**add, user=user) return user -
How to get Company names in Product filter function in Django?
I would like to get a JSON dict that contains all product names including corresponding company names (see 'Output I want' section). My search/filter function returns numbers as companies, which is wrong (see 'Output I have' section). Thanks! Product model class Product(models.Model): name = models.CharField(max_length=150) company = models.ForeignKey(Company, on_delete=models.CASCADE) Company model class Company(models.Model): name = models.CharField(max_length=150) Search/Filter function product_names = Product.objects.filter(name__startswith=request.GET.get('query')).values('name', 'company') Output I have {"products": [{"name": "bla 2", "company": 3}, {"name": "bla 1", "company": 10}]} Output I want {"products": [{"name": "bla 2", "company": "apple"}, {"name": "bla 1", "company": "samsung"}]} -
How to show progress for CSV import in Django?
I am trying to show progress for a CSV copy function in a Django web app. The relevant part of the function is: from django.db import connection cursor = connection.cursor() cursor.copy_expert(''' COPY employee_employee (name, slug, title) FROM STDIN WITH (FORMAT csv, HEADER true, FORCE_NOT_NULL (status)); ''', open(csv_fname), ) rowcount = cursor.rowcount My database is postgresql. From looking at the docs postgresql does not provide a way to show progress for queries like this. Has anybody found a way? Or should I adjust the query to use Django's ORM? I am afraid that would be slower. -
Django-Vue Routing Integration
I've been trying to integrate django with Vue via webpack bundle and I want to use both django urls and vue-router. I have been following this tutorial and it's almost working. Here's webpack-loader settings TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') FRONTEND_DIR = os.path.join(BASE_DIR, 'frontend') WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': DEBUG, 'BUNDLE_DIR_NAME': '/bundles/', # must end with slash 'STATS_FILE': os.path.join(FRONTEND_DIR, 'webpack-stats.json'), } } and urls.py urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^accounts/', include('django.contrib.auth.urls')), re_path(r'^openid/', include('oidc_provider.urls', namespace='oidc_provider')), re_path(r'^client/', include(('rp.urls', 'rp'), namespace='clients')), re_path(r'^api/', include(('testapp.urls', 'testapp'), namespace='api')), ] urlpatterns += [ re_path(r'(?P<path>.*)', TemplateView.as_view(template_name="application.html"), name="app", ), ] and here's the vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { baseUrl: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config.optimization .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.resolve.alias .set('__STATIC__', 'static') config.devServer .public('http://0.0.0.0:8080') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({"Access-Control-Allow-Origin": ["\*"]}) } }; However, I get a weird url in the address bar http://localhost:8000/http:/0.0.0.0:8080/ http://localhost:8000/http:/0.0.0.0:8080/about So how to get rid of that ? and is there a way to serve both the django and vue via apache ? -
how to fix 'failed with exit status 2' during installation of mysqlclient
i am getting such error and my goal was to install mysqlclient in django project in order to be connected to the mysql database pip install mysqlclient pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/73/79/67ddf24ac31b05d741f0ac87fa612c7a11bab1b39b8270ed7344d149f8af/mysqlclie nt-1.4.2.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command c:\users\grey-space\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;file='C:\Users\GREY-S~1\AppData\Local\Temp\pip-install-07aotna9\mysqlclient\setup.py';f=getattr(tokenize, 'op en', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record C:\Users \GREY-S~1\AppData\Local\Temp\pip-record-f6xsvf5v\install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe /c /nologo /Ox / W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,'final',0) -D__version__=1.4.2 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\incl ude\mariadb" -Ic:\users\grey-space\appdata\local\programs\python\python37-32\include -Ic:\users\grey-space\appdata\local\programs\p ython\python37-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\include " "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Win dows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86) \Windows Kits\10\include\10.0.17763.0\shared" … -
Django Manytomany add
I have 2 models in my Project with Many to Many relationship. On saving model Event, I read from the event_attendees file and add it to the attendees field in the Event. No errors/exceptions shown but attendee is not added to the attendees field. Do I need to save the model again after altering with the attendees field? If so, how to do that (calling save method from add_attendees will cause the program into infinite loop)? class Attendee(models.Model): name = models.CharField(max_length=100) class Event(models.Model): name = models.CharField(max_length=100) event_attendees = models.FileField(upload_to='documents/', blank=True) attendees = models.ManyToManyField(Attendee, blank=True) def save(self, *args, **kwargs): super().save() self.add_attendees() def add_attendees(self): with open(self.event_attendees.url[1:]) as csv_file: # Some code here for row in csv_reader: # Some code here attendee = Attendee(name=name) try: self.attendees.add(attendee) except Exception as e: print("Unknown Error") print(e) -
Django Oscar user verification email
I have a simple installation of Django Oscar project. I would like to know how to send user verification email so that all new users registered email IDs can be verified? By default Oscar registers new users and sends registration email to users. -
ChoiceField set in view not being rendered
I have previously accomplished the task I'm seeking help for: using AJAX to submit a string to the view that will filter objects with that string and return the results to field.choices. However, I've recently come back to this section of my app only to find that I do grab results from the database, I can't seem to get them into the choice field anymore. When I view the XHR response, I can see that it's working perfectly. In the image below, the right-hand-side has a dropdown list of all the schools that matched the filter (what I want): index.html <form id="School-Search-Form" action='' method="POST"> <label for="search-charfield-id"></label> {{ Search_Form }} {% csrf_token %} <input type="submit" value="Search" name="search-button" id="search-button"/></form> <label for="dropdown-choicefield-id">Select your school</label> {{ Select_Form.school_options }} {% csrf_token %} <input type="submit" value="Confirm" name="select-button" id="select-button"/></form> main.js $('#School-Search-Form').on('submit', function(event) { event.preventDefault(); var searchFormData = $('#School-Search-Form').serializeArray(); { type: "POST", // Defaults to current url data: searchFormData, dataType: 'html', success: function(response) { $('#school-search-name').val(''); console.log(response); }, error: function() { console.log("I got errors on my mind."); } }); }); forms.py class SchoolSearchForm(forms.Form): search_name = forms.CharField(max_length=100, min_length=5) class SchoolSelectForm(forms.Form): school_options = forms.ChoiceField(choices = [], required=False) views.py def AffiliateSchool(request): selectForm = SchoolSelectForm() searchForm = SchoolSearchForm() if request.method == 'POST': # … -
How can I override user.groups in a custom account model in Django to implement a "virtual" group?
I have a custom account class in a Django app using PermissionsMixin: class Account(AbstractBaseUser, PermissionsMixin): Our CMS calls various .groups methods on this class in order to ascertain permissions. We essentially want to override the queryset that is returned from .groups in this custom Account class and to inject an additional group under specific conditions. (I.e. the user has an active subscription and we then want to return "member" as one of the groups for that user, despite them not actually being in the group.) How should we handle this override? We need to get the original groups, so that basic group functionality isn't broken, then inject our "virtual" group into the queryset. -
How to fix " TypeError: post_details() got an unexpected keyword argument 'slug' "
I'm creating my blog with django, and trying to make posts urls in slug way, after I crated it's models and call it in views it show me this error: [TypeError at /posts/post/why-i-love-python-django/, post_details() got an unexpected keyword argument 'slug'] My files are in these links: [1]: https://pastebin.com/VuiPn7Vf => posts/views.py, [2]: https://pastebin.com/HjTK5Ugz => posts/models.py, [3]: https://pastebin.com/03gn3mbK => posts/urls.py, [4]: https://pastebin.com/xAVc3ppe => templates/post.html, [5]: https://pastebin.com/AzMQPxrv => templates/base.html I tried to change "id" in [posts/views.py line:102] and made it "slug", also edited it in [line:104] in [posts/view.py line: 102]: def post_details(request, id): post_list = Post.objects.active() post = get_object_or_404(Post, id=id) if post.publish > timezone.now().date() or post.draft: if not request.user.is_authenticated or not request.user.is_superuser: raise Http404 share_string = quote_plus(post.content) initial_data = { "content_type": post.get_content_type, "object_id": post.id, } # post read time read_time = get_read_time(post.content) # print(type(read_time)) form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid(): c_type = form.cleaned_data.get('content_type') content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get('content') parent_obj = None try: parent_id = int(request.POST.get('parent_id')) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type = content_type, object_id = obj_id, content = content_data, parent = parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = … -
Redirect after pdf generation PDFTemplateView django
I am using wkhtmltopdf, PDFTemplateView to generate a pdf file and I want to render to another view when the generation is finished: class MyModelView(PDFTemplateView): model = MyModel template_name = 'admin/my_template.html' cmd_options = { 'page-size': 'A4', 'margin-top': 0, 'margin-left': 0, 'margin-bottom': 0, 'margin-right': 0, } def get_context_data(self, **kwargs): context = super(MyModelPdfView, self).get_context_data(**kwargs) context['object'] = MyModel.objects.get(id=self.kwargs.get('pk')) return context -
How to fix "error path not found" in django rest framework
I am trying to build an API of my blogging website using Django rest framework, but my URL is not matching. I am trying Django Rest framework for the first time so I am not quite able to fix this. But I think I mess this up in url_patterns. Here is my URL code from the main directory(the directory which contains settings.py) . ` from django.conf.urls import url,include from django.contrib import admin from django.urls import path, include from blog import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'apipost',views.PostViewSet) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('blog.urls')), path('api-auth/',include('rest_framework.urls',namespace='rest_framework')), ] ` I am trying url http://127.0.0.1:8000/apipost and expect to get value in json format. -
I am getting the error that the local variable cruty referenced before assignment
Getting the error local variable 'cruty' referenced before assignment def index(request): if request.method =="POST": fname= request.POST.get("fname",None) if fname is not None: dname= Students.objects.get(USN=fname) print(dname) cruty= Marks.objects.filter(students=dname) print(cruty) return render(request, "index.html", {"cruty": cruty}) -
how to decode gzip string in JS
I have one Django app and in the view of that I am using gzip_str(str) method to compress data and send back to the browser. Now I want to get the original string back in the browser. How can I decode the sting in JS. P.S. I have found few questions here related to the js decode of gzip string but I could not figure out how to use those. Please tell me how can I decode and get the original string. -
Logic for upload more than 1 images at a time and then submit one by one later
In shutterstock, we can upload and keep more than one image at a time. Then at our convenience we can submit those uploaded images for review. What is the best way to handle the back-end logic for this? Table design is what i mean by back-end logic. I'm coding in Django with SQLite for now.