Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display DB blob(image) column on html page
I need a help to display photo from oracle DB on html page in django webapp, I have django webapp, and it has Employee model which has image column as blob to save the employee photo in the DB, when I try to display the image column on the HTML page it doesn't display. and it displays it as the following: ** (b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x03\xbc\x00\x00\x010\x08\x02\x00\x00\x00\x1b\xcc\xea\xea\x00\x00\x12\IDATx\x9c\xed\xdd\x7flU\xf5\xf9\xc0\xf1\x16\nTj\x11\x8ct\x1bC@\x87\xd3\rA\xd0\xa1h\x1d2\x17\'\x04\xa63\xea\xe6/\xd4\x99\x918\xb3\x98-\xea\x96\x91\xb8\xcdE\xd9\x92mYt\x89f\xfa\x07\x81\x98,Q\xb6e\xfe\xc2\x88\xc4P (3\xc2\xa0\xa6\xc8\xc2\x06,\xfc\xa8h\xb5\x08\xa3\xed\xfd\xfe\xe1\xbe\xc4\x08\xf7<\xa7\xb7\xe7\x9e\xf6\xe8\xeb\xf5\xe7\xfd\x9c>\xe7Y\xd8\xbawNn\xef\xad-\x95J5\x00\x00@y\x83\xfa{\x01\x00\x00\x18\xe8D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04D3\x00\x00\x04\xea\xfa{\x81<\xd4\xd6\xd6f2\'\xcdW\x8e\xa7\xb9W&_]\x9e\xdb\x8d\xb2\x92\xe7\xc2Y\xfd\x8b\x87\x06\xd4\xc2\x03\xea\xbf\x9f)\xef\x95\x89\xac\xfe\x83gr\xa34\x06\xd4o\x89\xac|"\xff\x15r3\xd0\xfe\xc7\x1b\xcaj\x99<\xff\xdf9\x13\x85\xfb\xb5\xf6\x89\xfcW\xe8G\x9e4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@@4\x03\x00@\xa0\xb6T*\xf5\xf7\x0e\x00\x000\xa0y\xd2\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x81\xba\xfe^\x00\xe0S\xad\xa3\xa3\xe3\xf9\xe7\x9f\x7f\xed\xb5\xd7Z[[\xb7m\xdb\xd6\xd9\xd9\xf9\xde{\xef\xf5\xf4\xf4466\x8e\x181b\xc2\x84\t\x93&M:\xe7\x9csf\xcf\x9e=v\xec\xd8\xfe^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x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x01\xd1\x0c\x00\x00\x81\xff\x03\xf0\xc2\xa5\xc7\xda\xabX&\x00\x00\x00\x00IEND\xaeB`\x82') ** -
Combining two or more queryset or combining different models as a single output
I have created 2 models Images and UserDetails both contain a foreignkey field of auth_user (User) .If i provide a user id i want get data from 3 models. ie; from User , UserDetails and Images as queryset in DRF models.py from django.contrib.auth.models import User from django.db import models class Images(models.Model): name = models.CharField(max_length=10) userid = models.ForeignKey(User,on_delete=models.CASCADE) category = models.CharField(max_length=10) file = models.FileField(blank=True, null=True) class Categories(models.Model): name = models.CharField(max_length=15) class Skills(models.Model): name = models.CharField(max_length=20) category = models.ManyToManyField(Categories) class UserDetails(models.Model): userid = models.ForeignKey(User,on_delete=models.CASCADE) firebase = models.CharField(max_length=50) mobile = models.IntegerField() pin = models.IntegerField( null=True) latitude = models.CharField(max_length=50,null=True) longitude = models.CharField(max_length=50,null=True) profile_pic = models.ManyToManyField(Images,null=True) skill = models.ManyToManyField(Skills,null=True) is_freelancer = models.IntegerField() serializer.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Images fields = '__all__' views.py class Profile(ListAPIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) serializer_class = ImageSerializer def get_queryset(self): img = Images.objects.filter(userid=self.request.user.id) return img if i run this in postman i get { "count": 1, "next": null, "previous": null, "results": [ { "id": 2, "name": "", "category": "profile pic", "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png", "userid": 14 } ] } but i want output something like this { "count": 1, "next": null, "previous": null, "results": [ { "image": { "id": 2, "name": "", "category": "profile pic", "file": "http://127.0.0.1:8000/media/media/brand_EqkvDFf.png", "userid": 14 }, … -
How to properly use django testcase's addCleanup method?
I have a test subclass of APITestCase where I'm using the class-method setUpTestData to create data for my tests and also some mocks. Basically what I want to do is to run mock.patch.stopall (as shown next), but it's not working. I have based my implementation on THIS ANSWER and I'm using: Django v2.2.4 and djangorestframework v3.10.2 import mock from rest_framework.test import APITestCase class FooTest(APITestCase): @classmethod def setUpTestData(cls): patcher_one = mock.patch('route.one') mock_route_one = patcher_one.start() patcher_two = mock.patch('route.two') mock_route_one = patcher_two.start() cls.addCleanup(mock.patch.stopall) # etc super(FooTest, cls).setUpTestData() When running my tests with this code, I get: TypeError: addCleanup() missing 1 required positional argument: 'function' So I edit the addCleanup call to: cls.addCleanup(function=mock.patch.stopall) but I get the following: TypeError: addCleanup() missing 1 required positional argument: 'self' Editing to: cls.addCleanup(cls, function=mock.patch.stopall) I get AttributeError: type object 'FooTest' has no attribute '_cleanups' At this point I'm a bit lost. The workaround that I'm using is to do it in the tearDownClass method: @classmethod def tearDownClass(cls): mock.patch.stopall() But I would like to centralize all the testing logic in the setUpTestData method. Anyone see's where I'm messing up? -
Is it better to aggregate all data in a JSONField or use model ForeignKey?
I'm trying to create a business directory in multiple languages. Should I aggregate all the data in one JSONField, or should split it into multiple models, and why. models.py from django.db import models from django.contrib.postgres.fields import JSONField class Business(models.Model): name = models.CharField(max_length=500) subsidiary = models.ForeignKey(Business, on_delete=models.SET_NULL, null=True, blank=True) data = JSONField() {"name":{"ar":"Arabic Name","en":"English Name"}} etc -
Django how to pass header on request in get_queryset
I am using Django rest framework to pass a get request with a query_param like so: views.py class PlanView(generics.ListAPIView): """ API endpoint which allows prices to be viewed or edited """ serializer_class = PlanSerializer permission_classes = (IsAuthenticated,) # override method def get_queryset(self): queryset = Plan.objects.all() size = self.request.query_params.get("size", None) if portion is not None: if size == "large": queryset = queryset.filter(Large=True) elif size == "small": queryset = queryset.filter(Small=False) return queryset however, I set up an authentication class in settings.py like this: 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication' ] so that I can pass a header with a token in request. This works well when I test with a third party client like postman. however how can I pass a header in the above view? -
Sending images twice to CouchDb instead of 1 time
I try to send zip file which is unpacked in memory and images are sent to database. But images are sent twice and I don`t know where the problem is. Can someone tell please? def uploadZIP(request): if request.method == 'POST': mosaic = 'C:/Users/lenovo/Downloads/myimages.zip' zip_name = ZipFile(mosaic) db_view = launch_db.view('_all_docs', include_docs=True) list_of_files = [name for name in zip_name.namelist()] imageNumber = len(list_of_files) imgInDBNumber = len(db_view) if imageNumber != 0: generalImageNumber = imgInDBNumber - 1 for j in range(imageNumber): for i in range(0, len(list_of_files)): archive = ZipFile(mosaic, 'r') image = archive.read(list_of_files[i]) image = Image.open(BytesIO(image)) file_name = 'img{0}'.format(generalImageNumber) rgb, img = rgbValue(image, file_name) generalImageNumber = generalImageNumber + 1 launch_db.save(rgb) launch_db.put_attachment(rgb, img, 'image.png', 'image/png') launch_db.commit() messages.info(request, 'ZIP file with images was successfully sent') return render(request, 'add_images.html') -
slow process during saving model in database
i want save a list of model in database table but i very slow when i use save() method for each item it took near 20min is that a best way to save objects to table Modles.py class Part(models.Model): block = models.CharField(max_length= 2, null= True) phase = models.CharField(max_length= 3, null= True) department = models.CharField(max_length= 20, null= True) type = models.CharField(max_length= 10, null= True) mark = models.CharField(max_length= 20, null= True) class Task(models.Model): name = models.CharField(max_length= 20) class ProjectTask(models.Model): project = models.ForeignKey('Project', on_delete= models.CASCADE) task = models.ForeignKey("Task", on_delete=models.CASCADE) weight_percent = models.FloatField() class PartTask(models.Model): part = models.ForeignKey('Part', on_delete= models.CASCADE) project_task = models.ForeignKey('ProjectTask', on_delete= models.CASCADE) progress = models.FloatField(null=True) views.py def import_part_task(_project_id): project_id = _project_id project_task = ProjectTask.objects.all().filter(project= int(project_id[0])) part_list = Part.objects.all() part_task_list = [] for part in part_list: for task in project_task: part_task = PartTask() part_task.part =part part_task.project_task = task part_task_list.append(part_task) #This ACTION TAKES VERY LOG TIME for part_task in part_task_list: PartTask.save(part_task) -
Django migrate: django.db.utils.OperationalError: (1364, "Field 'name' doesn't have a default value")
basic datas: mysql-server: 5.7.27-0ubuntu0.16.04.1 Ubuntu: 16.04 Python: 2.7.12 Django: 1.11.16 Virtualenv . I added a new application (gallery) and created the following table: class Medi(models.Model): gd_id = models.CharField(max_length=128) # name = models.CharField(max_length=512, default='1') original_name = models.CharField(max_length=512) title = models.CharField(max_length=512, blank=True, null=True) md5sum = models.CharField(max_length=32) date_of_event = models.DateTimeField() date_of_event_end = models.DateTimeField(blank=True, null=True) last_updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) . To be very clean after getting the above mentioned errors i deleted the table from the database, the entries from the django_migrations table and all the migrations file but init.py . I ran makemigrations and after that migrate which had the following output: python manage.py makemigrations Migrations for 'gallery': gallery/migrations/0001_initial.py - Create model Medi python manage.py migrate Operations to perform: Apply all migrations: admin, auth, bugtrack, common, contenttypes, follow, gallery, infokom, phonebook, sessions, sites Running migrations: Applying gallery.0001_initial... OK Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 227, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/home/lenovo/.virtualenvs/gjt/local/lib/python2.7/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File … -
Django Import Error Module "app1.context_processor" does not define a "songs_list" attribute/class
I have 2 apps in my django project, app1 and app2 app1/views.py def list_view(request): songs = Song.objects.all() context = { 'tracks_list' : songs } return render(request,"app1/list.html",context) I want this list to appear on app2, so I created a file called 'context_processor' inside app1: from .models import Song def songs_list(request): songs = Song.objects.all() return {"songs_list":songs} and inside settings.py I added this to the context_processors: 'app1.context_processor.songs_list', And {{ songs_list }} to the templates In the end I get an Import Error: Module "app1.context_processor" does not define a "songs_list" attribute/class Thank you for any help -
How to construct url path with two detailview
I have following url patterns urlpatterns = [ path('', CategoryListView.as_view(), name='forum'), path('category/<int:pk>/', CategoryDetailView.as_view(), name='forum-detail'), ] Inside the CategoryDetailView I will list the posts related to that category. So, when I click the any of the post I want the post detail view inside the category, because when I will create post with CreateView class I want category already predefined. I could also do the following path('post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'), path('post/new/', ForumPostCreateView.as_view(), name='forum-post-create'), ] In this case user should choose the category by himself when he or she will try create the post. But I want the category to be chosen already something like this ( I know this is wrong) path('category/<int:pk>/post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'), path('category/<int:pk>/post/new/', ForumPostCreateView.as_view(), name='forum-post-create'), ] So how to do it? -
How to allow access to base without permissions in django
How can I allow access to the base route while I have my Default permission classes set to IsAuthenticated in the global settings. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', # 'rest_framework.permissions.AllowAny', 'rest_framework.permissions.IsAuthenticated', ], } I know you can just set permission_classes = [AllowAny] in the individual views. But I want my base route to have the same i.e no permissions. Here is how i have the routes set in urls.py router_public = DefaultRouter() ''' PUBLIC ROUTES HERE ''' router_public.register( r'cars', car_viewset.Car_Public_Viewset, base_name='Cars') router_public.register( r'planes', plane_views.Plane_Public_ViewSet, base_name='Planes') urlpatterns = [ path('admin/', admin.site.urls), path('api/admin/', include(router_admin.urls)), path('api/public/', include(router_public.urls)), ] Since I have set permission_classes for cars and planes to AllowAny in the vews, I can access them without Authentication. How can I do the same for the base route http://localhost:8000/api/public/ since there's no view associated with it. -
Auto add user firstname in author field in django with custom User model
I created Custom User model in django using below code class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(_("Username"), max_length=50, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', ] objects = CustomUserManager() def __str__(self): return self.email And I also created another model for user profiles like below. class UserProfile(models.Model): user = models.OneToOneField(User, verbose_name=_("User"), on_delete=models.CASCADE) first_name = models.CharField(_("First name"), max_length=50) middle_name = models.CharField(_("Middle name"), max_length=50, blank=True, null=True) last_name = models.CharField(_("Last name"), max_length=50) dob = models.DateField(_("D.O.B"), auto_now=False, auto_now_add=False, blank=False, null=False) profile_image = models.ImageField(_("Profile picture"), upload_to='user/profile/', blank=True) webiste_link = models.URLField(_("Websites"), max_length=200, null=True, blank=True) At last I created another model for Category like below. class Category(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_( "Author"), on_delete=models.CASCADE, related_name='blog_category') title = models.CharField(_("Title"), max_length=50) I want to auto save logged in user full name instead of user email address. By the way i used below code to auto save logged in user. It works but It only save user email address. But I want user full name instead of email or username. obj.author = request.user super().save_model(request, obj, form, change) -
django.db.utils.IntegrityError: duplicate key value violates unique constraint, while 2 of 4 rows are different
I have a row in the DB that is: order_id: product_type_id: is_child: child_type_id: 1 2 True 3 I want to add a row with this code: order = 1, product.parent = 2 order_item = OrderItem.objects.create(order=order, product_type=product.parent, child_type_id=None, is_child=False) but it raises this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "order_orderitem_order_id_product_type_id_ee5c1733_uniq" DETAIL: Key (order_id, product_type_id)=(1, 2) already exists. while 2 of 4 rows are different, why I face this problem? -
What is causing this error in Django: NOT NULL constraint failed: mainapp_comment.post_id
I am in the middle of making a social network web application in Django. I have nailed most of the features needed, but I am stuck on making the commenting system work. I originally had it so users could make their own name for comments, but decided against that. The posting system has it, so the user who is logged in and makes the post, their name will be displayed for the author of the post. That's why some of the code is copy-pasted between the 2. I have tried all kinds of things, such as making the view a class instead of a function. It didn't work, and I am back to square one. Right now the user can make a post no problem, however the user's name isn't recorded and I have to set the author manually in the admin interface. The relevant code in views.py class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'mainapp/post_details.html' form_class = PostForm model = Post def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) @login_required def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('mainapp:post_detail',pk=post.pk) def form_valid(self, form): form.instance.author = self.request.user … -
Saving modelform gives 'NoneType' object is not iterable error
I'm showing a form and formset in one template and trying to save each. Formset would save fine but when I add the form, it gives 'NoneType' object is not iterable error. Django shows I'm erroring at this stage and Chrome shows my variables as folows. po = purchaseorder_form.save() ▼ Local vars Variable Value ProductBatchFormset productbatch_formset purchaseorder_form request submitted False # forms.py class PurchaseOrderForm(forms.ModelForm): class Meta: model = PurchaseOrder fields = '__all__' issuedAt = forms.DateField( widget=forms.DateInput(format='%Y%m%d', attrs={'placeholder': 'YYYYMMDD'}), input_formats=('%Y%m%d', ) ) referencePurchaseOrders = forms.ModelChoiceField(widget=forms.SelectMultiple, queryset=PurchaseOrder.objects.all(), required=False) internalManager = forms.ModelChoiceField(queryset=CustomUser.objects.all(), required=False) issuedBy = forms.ModelChoiceField(queryset=Company.objects.all(), required=False) issuedTo = forms.ModelChoiceField(queryset=Company.objects.all(), required=False) productSpendType = forms.ModelChoiceField(queryset=ProductSpendType.objects.all(), required=False) class ProductBatchForm(forms.ModelForm): class Meta: model = ProductBatch fields = '__all__' product = forms.ModelChoiceField(queryset=Product.objects.all(), required=False) quantity = forms.CharField(required=False) unitprice = forms.CharField(required=False) unitcurrency = forms.ModelChoiceField(queryset=Currency.objects.all(), required=False) productSpendType = forms.ModelChoiceField(queryset=ProductSpendType.objects.all(), required=False) # models.py class PurchaseOrder(models.Model): def __str__(self): return str(self.pk) purchaseOrderId = models.CharField(max_length=30, null=True, blank=True, db_index=True) issuedBy = models.ForeignKey('users.Company', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='issued_POs') issuedAt = models.DateTimeField(null=True, blank=True, db_index=True) issuedTo = models.ForeignKey('users.Company', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='received_POs') referencePurchaseOrders = models.ManyToManyField('self', symmetrical=False, null=True, blank=True, db_index=True, related_name='related_POs') internalManager = models.ForeignKey('users.CustomUser', null=True, blank=True, db_index=True, on_delete=models.CASCADE, related_name='managed_POs') note = models.TextField(max_length=500, null=True, blank=True, db_index=True) class ProductBatch(models.Model): def __str__(self): return str(self.pk) purchaseOrder = models.ForeignKey('PurchaseOrder', null=True, blank=True, db_index=True, on_delete=models.CASCADE) … -
unable to process a function inside a view using navigation bar
I'm making a website using django and i have navigation bar that has a few items when i click on another item which is "delete" I am not able to see the page i intended to see presently the 'insert' tab is my default tab and if i want to see the other link using delete tab i am not able the views file is like this def home(request): form=insert() form1=insert() if request.method=="POST" and 'b1' in request.POST: form=insert(request.POST) if form.is_valid(): form.save() return render(request,'employee/form.html') if request.method=="POST" and 'b2' in request.POST: allobjs=emp.objects.all() return render(request,'employee/form.html',{'form1':allobjs}) if request.method=="POST" and 'b3' in request.POST: allobjs=emp.objects.all().delete() #return render(request,'employee/form.html',{'form1':allobjs}) return render(request,'employee/form.html',{'forms':form,'form1':form1}) def dele(request): return render(request,'employee/emp.html') my code for navigation bar is <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="{%url 'employee-insert' %}">Insert Record</a> </li> <li class="nav-item"> <a class="nav-link" href="{%url 'employee-delete' %}">Delete Record</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Update Records</a> </li> <li class="nav-item"> <a class="nav-link " href="#">Assign Duties</a> </li> <li class='nav-item'> <a class='nav-link' href="">View The duties</a> my app which is called employee has url.py like this urlpatterns = [ path('',views.home,name='employee-insert'), path('',views.dele,name='employee-delete'),] -
i get 500 error in /graphql page in production
I have deployed my django application to server using heroku. Other pages gets loaded but when i try to load /graphql page i get 500 server error. I have even used graphiql mode as True. why am i getting this issue? Here is my urls for it urlpatterns = [ path('admin/', admin.site.urls), path('', pdf_generation), path('graphql', csrf_exempt(FileUploadGraphQLView.as_view(graphiql=True))), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) GRAPHENE = { 'SCHEMA': 'config.schema.schema', 'MIDDLEWARE': [ 'graphql_jwt.middleware.JSONWebTokenMiddleware', ], } it works in local environment. Here is the logs 2019-09-08T05:35:45.069808+00:00 heroku[router]: at=info method=GET path="/graphql" host=serene-beach-03946.herokuapp.com request_id=88088a0e-8571-4b18-9986-eb65b1603749 fwd="110.44.125.137" dyno=web.1 connect=1ms service=53ms status=500 bytes=373 protocol=https 2019-09-08T05:35:45.072219+00:00 app[web.1]: 10.65.66.5 - - [08/Sep/2019:05:35:45 +0000] "GET /graphql HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 encors/0.0.6" 2019-09-08T05:43:02.257886+00:00 heroku[router]: at=info method=GET path="/graphql" host=serene-beach-03946.herokuapp.com request_id=79395058-c64b-4576-ba6e-b3684311584d fwd="110.44.125.137" dyno=web.1 connect=0ms service=945ms status=500 bytes=373 protocol=https 2019-09-08T05:43:02.258405+00:00 app[web.1]: 10.113.243.77 - - [08/Sep/2019:05:43:02 +0000] "GET /graphql HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 encors/0.0.6" 2019-09-08T05:43:03.279183+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=serene-beach-03946.herokuapp.com request_id=48c30a98-8581-4bed-ad10-e3d9c39d7353 fwd="110.44.125.137" dyno=web.1 connect=0ms service=26ms status=404 bytes=411 protocol=https -
How to get the whole queryset
I have a model called PostForum class PostForum(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='forum_likes', blank=True) In my class based view I have following code class CategoryDetailView(DetailView): model = Category template_name = 'forum/forum_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = get_object_or_404(Category, id=self.object.id) posts = PostForum.objects.filter(category=category) context['posts'] = posts, return context In template I cant reach posts title or content. I shows nothing {% for post in posts %} {{post.title}} <p>{{post.content}}</p> {% endfor %} when I render {{post}} to see the whole queryset it shows <QuerySet [<PostForum: My first post>]> How to reach posts' title or content -
Invalid signature in Django Rest Frameworl JWT
I've created a custom login view to override obtain_jwt_token view as followed. class LoginView(ObtainJSONWebToken): def post(self, request, *args, **kwargs): user = User.objects.using(self.request.session.get('shop')).get(mobile=str(request.data['mobile'])) if not user.check_password(request.data['password']): return Response({'Error': "Invalid mobile or password"}, status="400") exp = datetime.datetime.now() + datetime.timedelta(seconds=settings.TOKEN_EXP_TIME) exp = int(datetime.datetime.timestamp(exp)) orig_iat = int(datetime.datetime.timestamp(datetime.datetime.now())) if user: payload = { 'user_id': user.id, "username": user.mobile, "exp": exp, "email": "", 'mobile': user.mobile, "orig_iat": orig_iat } jwt_token = {'token': jwt.encode(payload, settings.SECRET_KEY)} return Response(jwt_token, status=status.HTTP_200_OK) else: return Response({'Error': "Invalid credentials"}, status=status.HTTP_400_BAD_REQUEST) response = super().post(request, *args, **kwargs) return response after login token will created successfully but when I want to call an API (from postman) get {"detail": "Invalid signature."} error. I'm using my API using get method and I've added JWT MY_TOKEN in Authorization in header. Any idea? -
how to save dropdown list value to database in django
I am doing an attendance system and the student is able to mark their attendance by looking for their name in the dropdown list value. The student will then press submit and the information will be stored in MarkAtt database. MarkAtt contains: class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=0) attendance = models.IntegerField(default=1) #1 is present The Template displays the class information, today's date and the student's name in a drop drown list box. <form method="post" enctype="multipart/form-data"> {% csrf_token %} Lab Group: {{group.classGrp}} Day: {{group.day}} Time: {{group.time}} Today's date: {{today.date}} <p>{{form.att.label_tag}} {{form.as_p}} </p> The view: def mark_stud(request, class_id,id): if (not class_id or not id): return HttpResponseForbidden() else: try: classGrp = None information = {} information['studName'] = Namelist.objects.get(name=id) form = studentAttendanceForm(request.POST) if form.is_valid(): att = form.save(commit=False) att.studName = information['studName'] att.currentDate = datetime.datetime.now.date() form.save() return redirect('namelist.html') except ObjectsDoesNotExist: print("no entries") return redirect('namelist.html') return render(request, 'namelist.html', {'information' :information, 'form':form}) However, the form did not display in the template page and i am unable to save the value in the database. Really appreciate your help. Thank you so much. -
Should i start web development with django
I want to start web development and am confused whether i should start with django or not. I am a begineer in web development but have some experience in programming. -
A issue to use URL template tag in django
I am currently learning Django. When I apply a url template tag, I found that the output of the url tag is not what I expected. I have read the Django Documents, but it does not help. <a href ="{% url 'movies:detail' movie.id %">{{ movie.title }}</a> from django.urls import path from . import views app_name = 'movies' urlpatterns = [ path('', views.index, name='index'), path('<int:movie_id>', views.detail, name='detail') ] The output of the url tag is localhost/movies/%7B%%20url%20'movies:detail'%20movie.id%20% which is not as I expected: localhost:8000/movies/1 -
Proper way to authenticate graphql with facebook
I'm doing web application using graphql (ariadne) + Django. Now I want to integrate it with Facebook authentication without using DRF. So I wanted to use jwt. Is there any good practice or suggestions ? What is the proper way of doing authentication in graphql ? -
Django with watchtower region error when deploying to Elastic-Beanstalk
I am attempting to use watchtower with my Django API when deploying to AWS Elastic Beanstalk and I have just about run out of Google pages. When I deploy using AWS EB CLI I get an error stating that: ValueError: Unable to configure handler 'watchtower': You must specify a region. I have tried adding my credentials in multiple ways to try to solve this. I have put them in the settings.py file, the credentials file in the .aws dir (both csv and no extension). Settings.py: import os from datetime import timedelta from boto3.session import Session from boto3 import client # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AWS_ACCESS_KEY_ID = 'MY-KEy' AWS_SECRET_ACCESS_KEY = 'Shhh Secret Key' AWS_REGION_NAME = 'us-east-2' boto3_session = Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME) as I stated I also have a dir named ".aws" in my root dir with the credentials: [default] region = us-east-2 aws_access_key_id = key aws_secret_access_key = key My config files: option_settings: - namespace: aws:elasticbeanstalk:container:python option_name: WSGIPath value: Wesbite/wsgi.py - option_name: DJANGO_SETTINGS_MODULE value: Wesbite.settings - namespace: aws:elasticbeanstalk:cloudwatch:logs option_name: StreamLogs value: true container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_collectstatic: command: "python manage.py collectstatic --noinput" 03_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' option_settings: aws:elasticbeanstalk:application:environment: … -
Can't Figure out the Syntax Error in App.js
I am using this tutorial to install React for the front with an API built in Django. https://sweetcode.io/how-use-djang-react-ap/ My repository for this projects so far is here: https://github.com/AlexMercedCoder/DjangoReactCRM When I npm run dev I get a syntax error in App.js, I've played with it and can't seem to figure it out. The error I get is. ERROR in ./frontend/src/components/App.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C:\Users\alexm\projects\DjangoReactCRM\drcrm\frontend\src \components\App.js: Unexpected token, expected "," (29:6) 27 | 28 | wrapper ? ReactDOM.render(<app>, wrapper) : null; > 29 | </app> App.js import React, { Component } from "react"; import ReactDOM from "react-dom"; class App extends Component { state = { data: '' }; componentDidMount() { fetch("/api") .then(response => { return response.json(); }) .then(data => this.setState({ data: JSON.stringify(data)})); } render(){ return ( <p>Jason data = {this.state.data}</p> ) } } wrapper ? ReactDOM.render(<app>, wrapper) : null; </app>