Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't the seeking attribute work on the chrome browser..?? it works on IE however
my model code is like this content_type = models.ForeignKey(contentType, on_delete = models.CASCADE) content_subject = models.ForeignKey(Subject, on_delete = models.CASCADE) content_title = models.CharField(max_length=200) upload_content = models.FileField(upload_to=user_directory_path) this is what i have on my view but bk = Content.objects.get(id=id) how i acquired my video content from database to site then to template list_of_subjects = Subject.objects.filter(grade=grade_id) subject_video = contentType.objects.filter(content_types = 'SubjectVideos') subject_video_list = Content.objects.filter(content_type__in=subject_video) bk = Content.objects.get(id=id) context={ 'list_of_subjects':list_of_subjects, 'subject_video_list':subject_video_list, 'bk': bk } return render(request,'bgcse/bgcse_subject_video_list.html',context) then i have used this video tag on my html template the class video-fluid and etc only takes care of the video sizes and margins etc the video plays and works just fine, the only problem is seeking on chrome <video class="video-fluid z-depth-1" autoplay controlsList="nodownload" controlsList="seeking"> <source src="{{bk.upload_content.url}}"> </video> {% endblock %} ``` -
Using @swagger_auto_schema with recursive serializer in Django
I have a recursive serializer (data is a tree) which is the format of the response of an API. I tried to use it in @swagger_auto_schema like a bunch of other APIs I have implemented but the app collapsed. Can anyone tell me the solution for this, I really need this serializer to be shown on swagger for documenting for my colleagues. Here's my code: class CategoryExtendedSerializer(SkipBlankFieldsSerializer): children = serializers.ListField(source='get_children', child=RecursiveField(allow_null=True)) class Meta: model = Category exclude = ('lft', 'rght', 'tree_id', 'mptt_level') class CategoryListView(APIView): @swagger_auto_schema( operation_description="Get categories list", responses={200: base_page_response(CategoryExtendedSerializer)} ) def get(self, request): # some irrelevant code here pass -
How to mock a method inside another module during unit testing
In one of my test case the flow requires that a customer provision process wherein the call goes to the api.py file where in the response is saved from the function create_t_customer like following: In api.py file it is using the method create_t_customer imported from file customer.py response = create_t_customer(**data) In customer.py file the code for function is def create_t_customer(**kwargs): t_customer_response = Customer().create(**kwargs) return t_customer_response I want to mock the function create_t_customer inside the unittest. Current I have tried the following but it doesn't seem to be working class CustomerTest(APITestCase): @mock.patch("apps.dine.customer.create_t_customer") def setUp(self,mock_customer_id): mock_customer_id.return_value = {"customer":1} But this is not able to mock the function. -
How could I make the modal show up after clicking the Update(submit) button?
This is the footer code: <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button id="employee_update_btn" type="submit" class="btn btn-success btn-round ">Update</button> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> {% if success %} <script> $('#employee.employee_id_{{ employee.employee_id }}').show(); </script> {% endif %} </script> </form> I wanted to open the modal after clicking the Update button. views.py return render(request, 'index.html', context={'success': True}) the Modal i wanted to open: <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" tabindex="-1" role="dialog" style="display: none; overflow: auto;" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="card"> <div class="modal-content"> <div class="modal-header"> <div class="card-header-success" > <h4 align="center" class="card-title">EMPLOYEE PROFILE</h4> </div> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> -
Django: Inconsistent test that depends on other test
I am getting inconsistent tests. For visualization, Let me use examples: tests/test_animals.py tests/test_plants.py I have 2 tests. When I run individual test like: python manage.py test apps.living_things.tests.test_plants it would have no errors. However when I run python manage.py test apps.living_things.tests, to test everything, it would affect the second test: tests/test_plants.py I am using fixtures for them, one is initial and the other is just a test fixtures: fixtures/initial.json # general models fixtures/test_living_things.json # sample input for animals and plants I have been debugging. One class of test in tests/test_animals.py includes the 2 fixtures: class TestAnimals(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass When I commented out the block code above in test/test_animals.py everything works fine. So I am suspecting it has to do with the 2nd fixture: fixtures/test_living_things.json since I also have a Test Class without that fixture but works fine. The error I get when messed up is that Client.get does not respond well in tests/test_plants.py class TestPlants(TestCase): fixtures = ['fixtures/initial', 'fixtures/test_living_things'] def setUp(self): pass def tearDown(self): pass def test_plants(self): c = Client() response = c.post('/admin/login/', {'username': 'admin', 'password': 'animalplants'}) response = c.get("/living_things/plants/1/") # Gets Error here, returns 404 -
Django search query feature like Django admin or Django rest framework
I am trying to figure out a proper way to make a search functionality for my model fields like Django's admin or Django rest framework's search feature. Suppose I have this model, I would like to search through all the fields.: class User(models.Model): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) mobile = models.BigIntegerField(unique=True) First, I tried this way: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) This works fine if I am filtering with only the integer search terms. However, if I pass a string value, this breaks and it gives me an error: ValueError: invalid literal for int() with base 10 So now what I came up is something like this, to catch any Value errors and exclude integer searches from the filter: try: user_list = User.objects.filter( Q(id=int(search_input)) | Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | Q(mobile=int(search_input)) ) except ValueError as e: user_list = User.objects.filter( Q(email=search_input) | Q(first_name=search_input) | Q(last_name=search_input) | ) I am hoping there's a better way then this. Or maybe a field look up feature that I am not aware of? -
How to make a django/vuejs website available offline?
I am working on a online_test application which tests users on mcq, mcc, blanks and code questions. The basic flow of website is: It has courses. Student enrolls in the course watches video lessons Solves questions based on those videos. The first version of the website is live and built entirely in django. The second version I want is the offline version of the course available to the user in which he is enrolled, so that he can study or solve problems without worrying about the internet. Once he completes the test, his responses should be stored in some localstorage (I was thinking IndexedDB) and submitted only when the user comes online. For the second version I am using API written in DRF and for frontend Vue. Vue has helped me reduce number of hits to server and also improved the performance of the website. So I was thinking if there is any way in which I can have a simple Download Course button somewhere inside the course. And when the user click that button, a offline version of the course is available to user. The problem here is even if it is possible to make the course offline, I … -
Lost previous values on overriding change_list.html of django admin
I wanted to add a row in the django admin and for that I customized the django's change_list.html but after doing all the stuff I lost my previous fields. I had this previously: Previous fields image Not I wanted to add total in the footer of the page and I got this: Image after customizing I want the image 1 and image 2 in the same page. @admin.register(Section4, site=admin_site) class Section4Admin(ReadOnlyParamsMixin, admin.ModelAdmin): list_display = ['__str__', 'count_review', 'changelist_view'] def count_review(self, obj): ...... ...... return mark_safe( render_to_string( "section4/count_review.html", {'id': obj.resident.id, 'counts': counts, 'completed': review_completed, 'to_add': review_not_added, }) ) change_list_template = 'section4/total_review_count.html' def get_total(self, user): ........ ....... return total_review_upto_date, total_review_tobe_updated, total_review_tobe_added def changelist_view(self, request, extra_context=None): total_review_upto_date, total_review_tobe_updated, total_review_tobe_added = self.get_total(request.user) my_context = { 'total_review_upto_date': total_review_upto_date, 'total_review_tobe_updated': total_review_tobe_updated, 'total_review_tobe_added': total_review_tobe_added } return super(Section4Admin, self).changelist_view(request, extra_context=my_context) I have templates/admin/section4/section4/change_list.html In section4/templates/section4/total_review_count {% extends "admin/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} <footer> <p>The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> {% endblock %} -
Advantages of django rest_framework over AJAX and JsonResponce
I can get data in JSON format, using a view and url by calling an AJAX function from JQuery. Which only needs to create a view and a url to access it. But is rest_framework to do the same thing I need to create serializer, views and a url to do the same. So is it good to use AJAXX in these cases or I need to use rest_framework every time. Thanks. -
connect() to unix:///tmp/uwsgi_dev.sock failed (111: Connection refused) while connecting to upstream
I'm running django application with uwsgi + Nginx with crontab command given below /usr/local/bin/lockrun --lockfile /path/to/lock_file -- uwsgi --close-on-exec -s /path/to/socket_file --chdir /path/to/project/settings/folder/ --pp .. -w project_name.wsgi -C666 -p 3 -H /path/to/virtualenv/folder/ 1>> /path/to/log_file 2>> /path/to/error_log but nginx error log file shows the error *83 connect() to unix:///path/to/socket_file failed (111: Connection refused) while connecting to upstream, client: xxx.xxx.xx.xxx, server: localhost, request: "GET /auth/status/ HTTP/1.1", upstream: "uwsgi://unix:///path/to/socket_file:", host: "xx.xxx.xx.xxx", referrer: "http://xx.xxx.xx.xxx/" -
What will be the best way to perform the CRUD with DRF?
There are several ways of performing CRUD operation with django-rest-framework.One will be by using the plain API view, another is Generic API view and other is with ViewSets.I want to know which will be the better way to create an API ? -
Segmentation fault (core dumped) with django-storages
I'm using Django 2.x and Django-storages to upload files to the S3 Bucket. While running the sample test from manage.py shell, it gives the following error and terminates the console. Segmentation fault (core dumped) The console log as per the doc. In [1]: from django.core.files.storage import default_storage In [2]: default_storage.exists('storage_test') Out[2]: False In [3]: file = default_storage.open('storage_test', 'w') In [4]: file.write('storage content') Out[4]: 15 In [5]: file.close() In [6]: default_storage.exists('storage_test') Out[6]: True In [7]: file = default_storage.open('storage_test', 'r') In [8]: file.read() Segmentation fault (core dumped) File is uploaded to the S3 Bucket but unable to access or read it. -
PATCH with Django REST framework
I have models, serializers, and viewsets as following. models.py class OrderStatus(models.Model): ORDER_STATUS_CHOICES = ( ('NEW', 'New'), ('PROCESSING', 'Processing'), ('DELIVERING', 'Delivering'), ('DELIVERED', 'Delivered'), ) status = models.CharField( max_length=20, choices=ORDER_STATUS_CHOICES, default=ORDER_STATUS_CHOICES[0][0]) def __str__(self): return self.status class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='order', on_delete=models.CASCADE) order_items = models.ManyToManyField(OrderItem) order_status = models.ForeignKey(OrderStatus, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username serializers.py class OrderItemSerializer(serializers.ModelSerializer): pizza_type = serializers.CharField(source='pizza_type.name') pizza_size = serializers.CharField(source='pizza_size.size') class Meta: model = OrderItem fields = ('pizza_type', 'pizza_size', 'quantity', ) class OrderSerializer(serializers.ModelSerializer): user = UserSerializer() order_items = OrderItemSerializer(many=True) order_status = serializers.CharField(source='order_status.status') class Meta: model = Order fields = '__all__' views.py class OrderViewSet(ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer Listing, retrieving and deleting worked expectedly but how can I execute PATCH correctly to change order_status with the code above? I tried to run http://0.0.0.0:8000/api/orders/3/?order_status=PROCESSING and received "PATCH /api/orders/3/?order_status=PROCESSING HTTP/1.1" 200 313 but the data didn't look like it changed. Any hints? -
how to create dynamic model in django?
How do i create a dynamic model in django? here i am trying to create dynamic model using CreateDynamicModel,but it is not creating model and admin interface. ''' def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None): class Meta: pass if app_label: setattr(Meta, 'app_label', app_label) if options is not None: for key, value in options.iteritems(): setattr(Meta, key, value) # Set up a dictionary to simulate declarations within a class attrs = { '__module__': 'myapp.models' } # Add in any fields that were provided if fields: attrs.update(fields) # Create the class, which automatically triggers ModelBase processing model = type(name, (models.Model,), attrs) from django.core.management import sql, color from django.db import connection # Standard syncdb expects models to be in reliable locations, # so dynamic models need to bypass django.core.management.syncdb. # On the plus side, this allows individual models to be installed # without installing the entire project structure. # On the other hand, this means that things like relationships and # indexes will have to be handled manually. # This installs only the basic table definition. # disable terminal colors in the sql statements style = color.no_style() with connection.schema_editor() as editor: editor.create_model(model) class Admin(admin.ModelAdmin): list_display = ['first_name', 'last_name'] admin.site.register(model, Admin) return model def CreateDynamicModel(request): … -
html page should be updated when mysql table is updated without reloading in django
I have an issue that i want html page should update values which are fetched from mysql database whenever mysql table is updated. I have tried to implement javascript. here is what i have tried. ''' <script type="text/javascript"> $(document).ready(function(){ $.ajax({ type = 'Get', url = '{% url 'index' %}', data = {response.id_data} success : function(response){ $("#user_info ").html(`<tr> <td>${response.id_data || "-"}</td> </tr>`) }, }); }) </script> ''' here is my views.py. ''' def index(request): mycursor.execute("select id from face_counter") data = mycursor.fetchall() id_data = { "id": data } return JsonResponse({'id_data':id_data.get("id"),},status=200) ''' i have tried this but html page gets only json data and displayed it. script doesn't work what should i do. -
Retrieving count of unique Django objects based on multiple fields of another Django model
I have a Django model defined as follows: class Session(models.Model): ... leader = models.ForeignKey(User, related_name='leader') follower = models.ForeignKey(User, related_name='follower') ... Now let's say I have a QuerySet of Session objects: all_sessions = Session.objects.all() How can I get a simple count of unique Users that have been either a leader or follower in any Session in all_sessions? For example, a particular User may have been a leader in some number of Session objects, but a follower in a handful of other Session objects. That particular User should only contribute 1 to the desired unique Users count. There are of course some naive solutions to this, but for performance reasons, I'm wondering if there's a solution that leverages the power of QuerySets a bit more, if possible. -
google auth redirect uri miss match issue
In my django project i want to use google authentication for user login. i followed some articles but now stuck at point, where i'm getting error like: Error: redirect_uri_mismatch. i searched allot but could not resolved this issue. plz help I'm sharing my code here: settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xnph^f^z=wq^(njfp*#40^wran3' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'core', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', # <-- ] ROOT_URLCONF = 'simple.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', # <-- 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) LOGIN_URL = 'login' LOGOUT_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False WSGI_APPLICATION = 'simple.wsgi.application' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'xxxxxx my key xXXXXXX' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'xxx my secrete XXXX' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N … -
Best way to specify dedicated sub domain for authentication views in Django Rest Framework
I'm building and API using DRF and will be using it with a React SPA. I've chosen session authentication for my project because of the following reasons: It's built-in to DRF, so no dependence on 3rd party developers (a lot of auth packages or their dependencies are not maintained) CSRF + Cookie protection Ability to use Secure and HTTPOnly cookies However, I'm aware that it's recommended that we use Django's authentication views for the authentication pages and the single page app for the post authentication API calls. In this scenario, there are some views (i.e. Login, Logout, Password Reset, Register) for which the server responds with HTML and the rest return JSON. I would like to use different subdomain for these views i.e. different subdomain for HTML views and different subdomain for the JSON views. I'm a Django newbie and would really appreciate some suggestions on the best way to handle the separation of subdomains. I have some idea that the few ways I could achieve this are: using django-hosts using django sites (although I'm not sure if the cookie made by one site, would work on the other) point 2 domains to my server and handle the separation bit … -
django project always trying (and failing) to load file in separate app
I'm going back to an old django project and am trying to make a new site in a new app I just made, popularify. I want to load an httpResponse and nothing else when I go to the /popularify path , but it keeps trying and failing to get a favicon.ico file, the 404 error always appears in the chrome web console and django logs. I have it set up correctly so my popularify page loads a basic httpResponse: my main urls.py file in my project folder has a path: path('popularify/', include('popularify.urls')), The popularify app urls.py file looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And the popularify views.py file looks like this from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") All very basic to just load some text, but in console I am getting a unrelated 404 error trying to load a file I never directly specified, and dont want to load: If I click the favicon.ico link it shows the html file _base.html I have in my templates folder, a file I use as a base file in … -
How do I accept the friend request in django after sending a hyperlink in mail which redirects the user to accept/reject page?
models.py : class Friend(models.Model, LoginRequiredMixin): status = models.CharField(max_length=10) from_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name = 'from_user') to_user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="to_user") date_modified = models.DateTimeField(auto_now=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def create(self,request, **kwargs): friend = self.create(from_user_id=request.user.id, status="pending") return friend views.py : This view contains 2 buttons: Accept and reject and based on user response it will be updated in the database def accept_friend_request(request, uidb64, status): """Accept button will lead to entry in database as accepted and reject button will lead to entry in database as rejected based on status flag""" try: uid = urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(id=Friend.to_user.id) & Friend.from_user print(friend_user) f = Friend.objects.filter(friend_id = friend_user) print(f) if f: f.status = "accepted" f.save() return render(request, 'users/friend_list.html', {"uidb64": uid, "status": status}) else: f.status = "rejected" f.save() return render(request, 'users/friend_list.html', {'uidb64':uid, 'status':status}) except(FieldError, AttributeError): return render(request, 'blog/base.html') Thanking you in advance, -
How to work with drf-extension (Django Rest Framework) if the model has lookup_fields assigned
It would be better if I give an example that I was working on. The Models are class Author(models.Model): id = models.IntegerField(db_column='a_id', primary_key=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Book(models.Model): id = models.IntegerField(db_column='b_id', primary_key=True) title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) And the Serializers are, class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = ('id', 'first_name', 'last_name') class BookSerializer(ModelSerializer): class Meta: model = Book fields = ('id', 'author', 'title') And the view sets are, class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() class BookViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() Now The following APIs are working okay, /authors/ /authors/{author_id}/ /authors/{author_id}/books/ However, If I change the Author Views to class AuthorViewSet(NestedViewSetMixin, ModelViewSet): serializer_class = AuthorSerializer queryset = Author.objects.all() lookup_field = 'first_name' Then, the following APIs work /authors/ /authors/{author_first_name}/ But the following doesn't work. /authors/{author_first_name}/books/ I understand that it's because of the Foreign key relations between these two tables. I was just wondering whether there is any workaround if I want to keep the lookup_fields. Thanks -
Unable to customize django-oscar model
I am trying to customize a django-oscar model. ( I am using version 2.0.3 ) I have created a separate folder labeled apps and have created my app in it. I want to customize Product model in catalogue My INSTALLED_APPS look like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # 'oscar.apps.catalogue', # 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'rest_framework', 'apps.catalogue' ] and apps/catalogue/models.py looks like this from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct # from oscar.apps.catalogue.models import * class Product(AbstractProduct): custom_tag_field = models.CharField(default="Pending", max_length=100) from oscar.apps.catalogue.models import * I keep getting this error when I try to migrate and unable to solve it. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/abhijit/e-commerce-wig/oscar/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File … -
How to pass data from Django template (after submission) to DRF API without using a model?
I have a form in my template which allows a user to upload an image. Once the image is uploaded and submitted, it gets stored in a specified directory (not 'media'). Note: The image is not stored in a Django model since I didn't create one (don't need it). After doing so, I need to create an API using the Django Rest Framework. When calling the API URL, I intend to display that stored image name. The result will look like this: {"image_name" : <'stored_image_name_after_form_submission'>} This is what I had done so far: views.py: from rest_framework.views import APIView #code for uploading an image def upload(request): if (request.method == 'POST'): uploaded_file = request.FILES['image'] fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) image_path = fs.save(uploaded_file.name, uploaded_file) #name of the image file messages.success(request, 'Uploaded The Image.') return render(request, "template/upload.html") class API(APIView): def get(self, request): #API code comes here. The thing is, I can't seem to visualize how to create the API since I am fairly new to it. How can I capture the image name after the form submission and present it in my API view? Can someone explain how it works and what I should do to meet the requirement? Million thanks in advance. -
serving Angular build pack from django project
Hi have a django project with multiple apps. My project structure is: apt.yml DCMS_API/ infra/ manage.py* odbc-cfg/ requirements.txt static/ templates/ Authorize/ facility/ manifest.yml Procfile runtime.txt i have got angular6 buildpack from front end team, which i have copied it to static folder: ls: 3rdpartylicenses.txt fontawesome-webfont.af7ae505a9eed503f8b8.woff2 scripts.5bde77e84291ce59c080.js assets/ fontawesome-webfont.b06871f281fee6b241d6.ttf Staticfile devManifest.yml fontawesome-webfont.fee66e712a8a08eef580.woff json-data/ styles.38614f36c93ac671679e.css favicon.ico index.html main.e7b9143f2f482d6d3cc7.js fontawesome-webfont.674f50d287a8c48dc19b.eot polyfills.f3fc5ca24d1323624670.js fontawesome-webfont.912ec66d7572ff821749.svg runtime.a66f828dca56eeb90e02.js in settings.py i have added whitenose to serve the static build pack: middleware:'whitenoise.middleware.WhiteNoiseMiddleware', installed apps: 'whitenoise.runserver_nostatic', from my Authorize app: calling def dcmsApi(request): return render(request, 'index.html', {}) which opens index.html file. it however loads the home page, but if i click on anything it says Not Found The requested resource was not found on this server. is this is the right way to server static angular build pack from django Am i missing something? -
JSON parse error - 'utf-8' codec can't decode byte 0xc9 in position XXX when I try to upload Excel Sheet using Angular+REST
I am trying my hands on File Upload using Django REST and Angular. Following is the angular directory structure: app |-----uploadcomponent |-----uploadcomponent.module.ts |-----uploadcomponent.html |-----app.module.ts |-----app.component.ts |-----app.service.ts uploadcomponent.htl: <div> <form [formGroup]="form" (ngSubmit)="onSubmit()"> <input type="file" name="profile" enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" /> <button type="submit">Upload Template</button> <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> </form> </div> uploadcomponent.ts: import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; .... export class UploadComponent implements OnInit { form: FormGroup; constructor(private formBuilder: FormBuilder, private uploadService: AppService) {} ngOnInit() { this.form = this.formBuilder.group({ profile: [''] }); } onChange(event) { if (event.target.files.length > 0) { const file = event.target.files[0]; this.form.get('profile').setValue(file); console.log(this.form.get('profile').value) } } onSubmit() { const formData = new FormData(); formData.append('file', this.form.get('profile').value); this.uploadService.upload(formData).subscribe( (res) => { this.response = res; console.log(res); }, (err) => { console.log(err); }); } } app.service.ts: upload(formData) { const endpoint = this.service_url+'upload/'; return this.http.post(endpoint, formData, httpOptions); } Now in the backend I am using Django Rest Framework: Following are the required files of code: models.py: from __future__ import unicode_literals from django.db import models from django.db import connection from django_mysql.models import JSONField, Model import uuid import os def change_filename(instance, filename): extension = filename.split('.')[-1] file_name = os.path.splitext(filename)[0] uuid_name = uuid.uuid4() return file_name+"_"+str(uuid_name)+"."+extension class UploadTemplate (Model): id = …