Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload multiple files in django rest framework?
I amm very new to django rest framework so sorry for the bad code.Here I am trying to upload multiple files at once with this code.But it is not uploading .I tested it into the postman but I get the 500 internal server error. What should I done to upload multiple files. models.py class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,related_name='galleries') image = models.ImageField(upload_to='package_gallery') serializers.py class PackageGallerySerializer(serializers.ModelSerializer): image = serializers.ListField(child=serializers.FileField()) class Meta: model = PackageGallery fields = ['package','image','alt_text'] def create(self, validated_data): package= self.context['request'].data.get('package') image = validated_data.pop('image') for img in image: gallery = PackageGallery.objects.create(image=img, package=package, **validated_data) return gallery views.py class CreatePackageGallery(generics.CreateAPIView): serializer_class = PackageGallerySerializer parser_classes = [MultiPartParser,FormParser] queryset = PackageGallery.objects.all() -
in django admin page cannot add object there is error
enter image description here OperationalError at /admin/jobs/job/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/jobs/job/add/ Django Version: 2.0.2 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\codering\Desktop\myenv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Users\codering\Desktop\myenv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\codering\Desktop\portfolio', 'C:\Users\codering\Desktop\myenv\Scripts\python38.zip', 'C:\Users\codering\Desktop\myenv\DLLs', 'C:\Users\codering\Desktop\myenv\lib', 'C:\Users\codering\Desktop\myenv\Scripts', 'c:\users\codering\appdata\local\programs\python\python38\Lib', 'c:\users\codering\appdata\local\programs\python\python38\DLLs', 'C:\Users\codering\Desktop\myenv', 'C:\Users\codering\Desktop\myenv\lib\site-packages'] Server time: Wed, 20 Nov 2019 10:45:27 +0000 this page is opeaning when i am trying to add object plzz need help -
How to create tabs for django admin?
How to create tabs for admin languages. Example like: Change book English Japanese Some models -
When creating models.py ,the row size too large issue is found ,how to solve this problem
** how to solve this issue ,raise errorclass(errno, errval) django.db.utils.InternalError: (1118, u'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs'),can please help to solve this problem** from __future__ import unicode_literals from django.db import models Create your models here. class Newsdeatils(models.Model): news_provider_id = models.CharField(max_length=5000) news_title = models.CharField(max_length=5000) news_details = models.CharField(max_length=5000) news_image = models.CharField(max_length=5000) news_page_url = models.CharField(max_length=5000) next_page = models.CharField(max_length=5000) news_des = models.CharField(max_length=5000) -
Django Rest Framework combine 2 queries
i have machine model, supposing machine has different status such as produce, maintain, pending and etc. I would like to build an api to response the latest machine status by calling: http://127.0.0.1:8000/api/machinestatus/?machines=2,7 this endpoint should response the status for machine ID 2 and 7, I've tried many ways but still cannot make it work, please help model: class MachineStatus(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False) machine = models.ForeignKey( Machine, on_delete=models.CASCADE, blank=False, null=False) upt_time = models.DateTimeField(blank=False, null=False) status = models.CharField( max_length=1, choices=JOB, blank=False, null=False) def __str__(self): return f"{self.machine} {self.upt_time} {self.status}" class Meta: verbose_name_plural = "MachineStatus" serializer: class MachineStatusSerializer(serializers.ModelSerializer): upt_time = serializers.DateTimeField(read_only=True) status = serializers.CharField(read_only=True) user = serializers.SlugRelatedField(read_only=True, slug_field='username') machine = serializers.SlugRelatedField( read_only=True, slug_field='name') class Meta: model = MachineStatus fields = '__all__' view: class MachineStatusView(viewsets.ModelViewSet): ''' Machine Status View ''' queryset = MachineStatus.objects.all() serializer_class = MachineStatusSerializer def get_queryset(self): queryset = MachineStatus.objects.all() machines = self.request.query_params.get('machines') if machines: machines = machines.split(',') for i in machines: queryset = MachineStatus.objects.all() queryset = queryset.filter(machine=i).order_by('-upt_time')[:1] \\ question: how to combine queries' result? return queryset each "i" would call queryset with result of corresponding latest machine status, but the problem is how to combine these queryset in the for loop? thanks alot or is there any better other … -
Django model + Unique column on two tables (inheritance)
How to create constraint (on database to keep integrity) base on columns from child and parent table? Model: class DBMaster(models.Model): col1 = models.CharField() class DBOne(DBMaster): col_own .... col1 - should be this same how in DBMaster class Meta: constraints = [ models.UniqueConstraint(fields=['col_own', 'col1'], name='CON_UNIQUE_1') ] We can use materialized view but we wont. Any sugestions? -
How to get check box value in django
Views.py; def export_selectd_data_to_excel(request): if request.method == 'POST': chk_values = request.POST.getlist('chkselect') print(chk_values) return redirect(user_details) Html: <td> <input type="checkbox" name="chkselect" class="checkboxall" value="{{i.id}}"/> </td> Please help me with this https://i.stack.imgur.com/vzCtL.png -
Django datetime.date.min and Mysql DATE minimum value is different
Actual Question How can i deal with different minimum date in Django DateField and Mysql DATE type. What can be done to deal with the issue? TL:DR datetime.date.min has lower value than minimum supported in Mysql for DATE type. Saving datetime.date.min to Mysql is possible but it is not guaranteed to work. Context I'm working with Django (v1.11) model: class MyModel(model.Model): begin_date = models.DateField(null=True, blank=True) end_date = models.DateField(null=True, blank=True) Currently the fields with NULL value designate the lower and higher date range limits respectively. Example: Date range from beginning of time to today will be: mymodel.begin_date = None mymodel.end_date = datetime.date(2019, 11, 20) mymodel.save() The usage of None/NULL creates a need to convert it to datetime.date.min/datetime.date.max on any sorting operations etc. Simply put: its inconvenient and adds unnecessary complexity. My though was to do necessary migrations and start putting datetime.date.min/datetime.date.max instead of None/`NULL' But there is a problem: Mysql has different min/max date range According to the mysql docs: The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'. According to python docs: The smallest year number allowed in … -
ValueError: Cannot add "": instance is on database "default", value is on database "None"
I am trying to add data from excel into many-to-many relationships, but I have encountered an error like bellow, I have added the save () method to the individual object the way people say that error, but It still does not work, what should I do? ValueError: Cannot add "": instance is on database "default", value is on database "None" max_col = sheet_obj.max_column max_row = sheet_obj.max_row for i in range(2, max_row+1): cell_sv = sheet_obj.cell(row = i, column = 2) if cell_sv.value != None: sv = MyUser.objects.get(msv=cell_sv.value) MaLHP = sheet_obj.cell(row = i, column = 4).value HocPhan = sheet_obj.cell(row = i, column = 5).value TC = sheet_obj.cell(row = i, column = 6).value GiangVien = sheet_obj.cell(row = i, column = 7).value LopMonHoc = sheet_obj.cell(row = i, column = 8).value Thu = sheet_obj.cell(row = i, column = 9).value Tiet = sheet_obj.cell(row = i, column = 10).value GiangDuong = sheet_obj.cell(row = i, column = 11).value mh = MonHoc(MaLHP=MaLHP, HocPhan=HocPhan, TC=TC, GiangVien=GiangVien, LopMonHoc=LopMonHoc, Thu=Thu, Tiet=Tiet, GiangDuong=GiangDuong) svmh = SvMonHoc(Sv=sv) svmh.save() svmh.MonHoc.set([mh]) -
Django design for full and partial views
Title sucks, sorry. Here's what I mean. Our site has a navigation sidebar and I want it to behave like follows: when any of the navigation links is clicked, the corresponding page is loaded with AJAX when browsing to the page's URL, the full page is loaded This means we need to implement two versions of each page. My question is about what's the best way to go about this on Django. Two different views and two different routes There would be a Page1PartialView and a Page1View, each routed differently: url(r'^page1/partial/$', Page1PartialView.as_view(), name='page1_partial'), url(r'^page1/$', Page1View.as_view(), name='page1') The implementation would go something like this: class Page1PartialView(TemplateView): template_name = 'page1_content.html' class Page1View(Page1PartialView): template_name = 'page1.html' def get_context_data(self, **kwargs): context = super(Page1View, self).get_context_data(**kwargs) # build "full page" context on top of "content" context # ... return context Single view with different behavior There would be a unique view Page1View, which would behave differently depending on the type of request. class Page1View(TemplateView): template_name = 'page1.html' content_template_name = 'page1_content.html' def render_to_response(self, context, **response_kwargs): if not self.request.is_ajax(): return super(Page1View, self).render_to_response(context, **response_kwargs) html = render_to_string(self.content_template_name, context, RequestContext(self.request)) return JsonResponse({'html': html}) def get_context_data(self, **kwargs): context = self.get_partial_context_data(**kwargs) if not self.request.is_ajax(): # update "content" context data with extra "full … -
How do I register a custom Django user model to the admin page?
I followed a tutorial on how to allow Django authentication by using email instead of the normal username, however, they didn't mention how to register the new custom user model with the admin page! I am a real beginner to Django so I would appreciate as much detail as possible! Here is my code so far: managers.py from django.contrib.auth.models import BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): if not email: raise ValueError('Email field is required') email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(email, password, **extra_fields) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ''Unselect this instead of deleting accounts.' ), ) USERNAME_FIELD = 'email' objects = CustomUserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): return self.email def get_short_name(self): return self.get_full_name() def __str__(self): return self.email admin.py from … -
Django: Getting a list of meetings starting in a specific year and month when the start date is a Datetime object
I am making a web app in Python/Django and I am trying to make a calendar that displays meetings. I have the following in models.py. class Meeting(models.Model): id = models.AutoField(primary_key=True) admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) location = models.CharField(max_length=200, null=True) start_date = models.DateTimeField(default=None, null=True) end_date = models.DateTimeField(default=None, null=True) description = models.CharField(max_length=2000, null=True) class CustomUser(AbstractUser): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) email = models.EmailField(max_length=70, null=True, unique=True) password = models.CharField(max_length=50, null=True) class Member(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE) Essentially, a user and a meeting are linked in the Member model. I have the following function in database.py, which creates a new Meeting: def createMeeting(name, location, admin, start_date, end_date, description): new = Meeting(name=name, location=location, admin=admin, start_date=start_date, end_date=end_date, description=description) if not duplicate(Meeting, new): new.save() membership = Member(user=admin, meeting=new) if not duplicate(Member, membership): membership.save() I am trying to get a list of all the meetings that a logged in user is in that are in a particular month and year. However, since the a meeting's start_date is a DateTime object, I am not sure what is the best way to do this. Any insights are appreciated. -
How to get the related objects in the Django rest API retrieve view?
Here I have two models and have Many-to-one relation . In the ListPackageGallery class I want to list all the images uploaded to some package. How can I query the images of some particular package here? I am very new to django rest.So am I going the right way by using the generics API view for such cases ? class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,related_name='gallery') image = models.ImageField(upload_to='package_gallery') serializers.py class PackageGallerySerializer(serializers.ModelSerializer): class Meta: model = PackageGallery fields = '__all__' class PackageGalleryDetailSerializer(serializers.ModelSerializer): class Meta: model = Package fields = '__all__' views.py class CreatePackageGallery(generics.CreateAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListAllGallery(generics.ListAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListPackageGallery(generics.RetrieveAPIView): serializer_class = PackageGalleryDetailSerializer lookup_field = 'slug' def get_queryset(self): return self.gallery.all() #i got stuck here urls.py path('create/gallery/',CreatePackageGallery.as_view(),name='create_package_gallery'), path('list/all/gallery/',ListAllGallery.as_view(),name='list_all_gallery'), path('list/<slug>/gallery/',ListPackageGallery.as_view(),name='list_package_gallery'), Django Version: 2.2.7 Exception Type: AttributeError Exception Value: 'ListPackageGallery' object has no attribute 'gallery' -
Programmatically render inclusion tag in Django
Django provides the render(…) shortcut function which essentially takes a template name and a context and returns an instance of HttpResponse containing the rendered template string. Is there an official way to do the same thing with an inclusion tag? That is, instead of supplying a template name I would like to supply the name of an inclusion tag that then gets rendered with its own context (i.e. what the tag function returns) plus an optional additional context. For example, let's consider the following tag: # myapp/templatetags/myapp.py @register.inclusion_tag('myapp/mytemplate.html') def my_inclusion_tag(some_paramter): return { 'some_parameter': some_parameter } Then I would like to be able to do something like http_response = render_tag(request, 'myapp.my_inclusion_tag', {'additional_context': value}) where the entire context would be {'some_parameter': some_parameter, 'additional_context': value}. -
Hooking Django (DRF) to an existing database
I think I am looking for as much advise as possible. I have a project that I have inherited. The codebase is absolutely awful. I have a Django project, within this a React app. There's all manner of proxies between to fetch from the API to deliver up content. However, I want to start to re-write the API, as it is awfully put together. Zero documentation. To re-write the API, I would like take a copy of the exisiting database - and then work with this to write a more consistent API. What would be your advise/steps/method to achieve this, and what should I look out for when doing this? N.B. The database is PostgreSQL. -
Django: Better way to aggregate QuerySet results
I have the following code snippet. I first tried to get the count for male / female directly as annotation but I didn't manage to get these. Therefore I wrote the following for loop. However, it still feels that this solution is not as good as it could be. Do you have any other idea how to write better code here? genders = self.get_answers(self.get_super_guests(), QuestionFocus.GENDER) # >>> <QuerySet [Answer: Male, Answer: Female, Answer: Male]> male = female = 0 for gender in genders: if gender.answer == "Male": male += 1 elif gender.answer == "Female": female += 1 print("Gender distribution is Male", male, "Female: ", female) -
ModuleNotFoundError: No module named 'django_popup_view_field'
you see that all is installed but when i runserver i got this error : ModuleNotFoundError: No module named 'django_popup_view_field' [p-amc-dgps-er@192-168-150-254 Invest_App]$ sudo pip install django-popup-view-field [sudo] Mot de passe de p-amc-dgps-er : DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Requirement already satisfied: django-popup-view-field in /usr/lib/python2.7/site-packages (0.5.0) Requirement already satisfied: Django>=1.8 in /usr/lib/python2.7/site-packages (from django-popup-view-field) (1.11.26) Requirement already satisfied: pytz in /usr/lib/python2.7/site-packages (from Django>=1.8->django-popup-view-field) (2018.9) -
Using cookie cutter to create Django project, running error?
my django version:2.1.7 when i running , it Report errors. Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/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 679, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/compressor/models.py", line 1, in <module> from compressor.conf import CompressorConf # noqa File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/compressor/conf.py", line 7, in <module> from appconf import AppConf File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/appconf/__init__.py", line 2, in <module> from .base import AppConf # noqa File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/appconf/base.py", line 109, in <module> class AppConf(six.with_metaclass(AppConfMetaClass)): File "/home/chrisiven/.local/share/virtualenvs/zanhu-mWVkLVbC/lib/python3.7/site-packages/six.py", line 833, in __new__ resolved_bases = types.resolve_bases(bases) AttributeError: module 'types' has no attribute 'resolve_bases' error tip: AttributeError: module 'types' has no attribute 'resolve_bases so , I guess it's the version,but i don't find error! emmm... Does anyone know why? or Does anyone have a similar … -
How to pass data saved from a POST method to the GET method using REST API Django (without a model)?
I have created an API that allows me to upload an image using the POST method in POSTMAN. After submission, I want to display that image name after making a GET request. I am not using any model and I don't intend to grab the image from the directory it is stored in; since I will be uploading images in a server later. I have looked at multiple sources. A few examples are this, and this. This is my current code so far but not successful: views.py: class API(APIView): parser_classes = (MultiPartParser,) def get(self, request, *args, **kwargs): name = self.request.GET.get('image') return HttpResponse(name) def post(self, request): #key is 'image', value is the file uploaded in my machine file = self.request.data img_file = file['image'] #store the image data in this variable if img_file: uploaded_file = img_file fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT) #saves it to a specific directory name = fs.save(uploaded_file.name, uploaded_file) image = [{"image_name": name}] serializer = ImageSerializer(image, many = True).data return Response(serializer, status = 200) else: return Response("Image isn't uploaded. Please upload", status = 400) serializers.py: from rest_framework import serializers class ImageSerializer(serializers.Serializer): image_name = serializers.CharField() My expected result within GET request should be like this: {'image_name' : 'image_name_from_POST_Request'} But I am getting this … -
Django serverside processing (Sorting, filtering, pagination) the data from backend
I am currently trying to perform serverside processing of table data from django backend before and using it in an angular app. Currently I am only able to fetch all the data from the database but I want to be able to process it and use it the defined datatable rather than doing all this processing from client side Can anyone help with this? -
AttributeError: 'NoneType' object has no attribute 'user' Django
class GeneratePublisherPdf(APIView): #View def get(self, request, *args, **kwargs): reviewer_id = request.GET.get("user") export_date = datetime.date.today() - datetime.timedelta(1) profile = UserProfile.objects.filter(user_id=reviewer_id).first() users = [profile.user.id, ] for up in UserProfile.objects.filter(publisher=profile.user, user__register_type='5'): users.append(up.user.id) if not len(users): result = { "status": False } return Response(data=result) queryset = ProductCertificate.objects.filter(user__id__in=users, created__date=export_date).order_by('-created') users = [profile.user.id, ]...shows error in user here.plz help to solve thiz -
django dict/queryset/list to json
I want to convert this queryset to json. json.dumps() does not work. serialize does not work. json.dumps() + list() does not work how can I convert querset to json? maybe the reason these conversions are not work is in here. I know that Models.objects.all() or Models.objects.all().only() return queryset, Models.objects.all().values() returns list of dict. I want to add a new key-value set to the first queryset, So I use Models.objects.all().values() but when I add a new key-value set, I think, the datatype is twisted. so now the datatype of 'questionRequeestList' is neither 'List' nor 'Queryset' at converting to json. how can I convert this value to json? or how can I add new queryset to another queryset dict? -
Mocking class methods
I have a situation which i could not find on stack-overflow: some_module.py: class SomeModule(): def a(): pass def b(): pass def c(): pass @classmethod def bring_them_altogether(cls): cls.a() cls.b() cls.c() I am writing a unittest and would like to test the method bring_them_altogether() by determining that methods a(), b() & c() are all called once. In my testcase i have this: test.py: @patch('<...>.some_module.SomeModule', autospec=True) def test_bring_them_altogether(self, mock_class): mock_class.bring_them_altogether() self.assertTrue(mock_class.called) # Returns me False I want to know how to write a proper test case for bring_them_altogether() as i seem to be having some issues getting the output i want. On that note, I want to know how to determine that a mocked-method has been called X - number of times. Thank you for pointing me in the right direction -
Django 2.2: regex url match
i need to create a list of urls that one of my middlewares should ignore. i need to ignore /admin/ and any url that comes after it. how can i proceed ? -
Change the color of road in google map
How to change a google map particular road color using django? is this possible? I am side search about it but i don't found any solution for that so any one have good solution for this please post here.