Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting a server (500) error when Debug=False in Django for Heroku?
So, I am attempting to serve up my local files to heroku. Everything works fine when my debug=True, but I am now setting debug=False and it pushes fine, but then I get a server 500 error. heroku logs--tail 2020-07-01T20:49:52.625458+00:00 app[web.1]: [2020-07-01 16:49:52 -0400] [10] [INFO] Worker exiting (pid: 10) 2020-07-01T20:49:52.625694+00:00 app[web.1]: [2020-07-01 16:49:52 -0400] [11] [INFO] Worker exiting (pid: 11) 2020-07-01T20:49:52.826436+00:00 app[web.1]: [2020-07-01 20:49:52 +0000] [4] [INFO] Shutting down: Master 2020-07-01T20:49:52.913999+00:00 heroku[web.1]: Process exited with status 0 2020-07-01T21:48:52.452437+00:00 heroku[web.1]: Unidling 2020-07-01T21:48:52.468183+00:00 heroku[web.1]: State changed from down to starting 2020-07-01T21:49:02.609064+00:00 heroku[web.1]: Starting process with command `gunicorn dating_project.wsgi --log-file -` 2020-07-01T21:49:04.647623+00:00 app[web.1]: [2020-07-01 21:49:04 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-07-01T21:49:04.648440+00:00 app[web.1]: [2020-07-01 21:49:04 +0000] [4] [INFO] Listening at: http://0.0.0.0:41874 (4) 2020-07-01T21:49:04.648596+00:00 app[web.1]: [2020-07-01 21:49:04 +0000] [4] [INFO] Using worker: sync 2020-07-01T21:49:04.654902+00:00 app[web.1]: [2020-07-01 21:49:04 +0000] [10] [INFO] Booting worker with pid: 10 2020-07-01T21:49:04.738652+00:00 heroku[web.1]: State changed from starting to up 2020-07-01T21:49:04.752279+00:00 app[web.1]: [2020-07-01 21:49:04 +0000] [12] [INFO] Booting worker with pid: 12 2020-07-01T21:49:06.636432+00:00 heroku[router]: at=info method=GET path="/" host=cupids-corner.herokuapp.com request_id=37718085-380c-4321-a3b2-2e5aa76f3ef9 fwd="69.171.251.32" dyno=web.1 connect=0ms service=101ms status=500 bytes=234 protocol=https 2020-07-01T21:49:06.636517+00:00 app[web.1]: 10.123.144.18 - - [01/Jul/2020:17:49:06 -0400] "GET / HTTP/1.1" 500 27 "-" "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" 2020-07-01T22:24:34.101909+00:00 heroku[web.1]: Idling 2020-07-01T22:24:34.108226+00:00 heroku[web.1]: State changed from up to … -
create user and user profile with django rest auth
i'm having troubles with django rest auth register view when i try to register a user it give me this error: user = serializer.save(self.request) TypeError: save() takes 1 positional argument but 2 were given i've read that i need to override the save method in my serializer but i'm new to django and really don't how to do it can any one help please? her is the code : from rest_framework import serializers from django.contrib.auth.models import User from .models import Userprofile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model=Userprofile fields=('Type','name','phone','Email', 'landing_page','Facebook' ,'Youtube','LinkedIn','Twitter','description' ,'messenger','whatsapp','profilePic') class UserSerializer(serializers.ModelSerializer): profile=UserProfileSerializer(required=True) password = serializers.CharField(write_only=True, required=False) confirm_password = serializers.CharField(write_only=True, required=False) class Meta: model=User fields = ( 'id', 'username', 'email', 'password', 'confirm_password', 'profile' ) def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'],) user.save() Profile=UserProfile.objects.create(user=user) Profile.save() return user the model: from django.db import models from django.contrib.auth.models import User # Create your models here. class Userprofile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') .... -
How to show messages in Python?
I am new to Django and trying to create an Application. My scenario is: I have a form on which there are many items and user can click on Add to Cart to add those item to Cart. I am validating if the user is logged in then only item should be added to Cart else a message or dialogue box must appear saying please login or sign up first. Although I was able to verify the authentication but the somehow not able to show the message if user is not logged in. For now I tried the below things: Using session messages, but somehow it needs so many places to take care when to delete or when to show the message Tried using Django Messages Framework, I checked all the configuration in settings.py and everything seems correct but somehow not showing up on HTML form Does anyone can help me here? I want to know a approach where I can authenticate the user and if user is not logged in a dialogue box or message should appear saying Please login or Signup. It should go when user refreshes the page. -
setUpTestData integrity error; database does not refresh
I am new to Django unit testing and trying to understand how to instantiate fixtures for a class, that are then removed from the database once the tests in the class are finished. My understanding is its best to use setUpTestData for this. However, when set up the same fixtures in two different classes, I get a django.db.utils.IntegrityError: duplicate key value violates unique constraint error: class TestClass1(TestCase): @classmethod def setUpTestData(cls): cls.i1 = Issuer.objects.create(issuer_name='Issuer 1') cls.i2 = Issuer.objects.create(issuer_name='Issuer 2') cls.i3 = Issuer.objects.create(issuer_name='Issuer 3') def test_1A(self): // etc class TestClass2(TestCase): @classmethod def setUpTestData(cls): cls.i1 = Issuer.objects.create(issuer_name='Issuer 1') cls.i2 = Issuer.objects.create(issuer_name='Issuer 2') cls.i3 = Issuer.objects.create(issuer_name='Issuer 3') def test_2A(self): // etc Produces: django.db.utils.IntegrityError: duplicate key value violates unique constraint "myapp_issuer_pkey" DETAIL: Key (id)=(6) already exists. Why doesn't the database "reset" after each TestCase class is complete? Where am I going wrong? -
Django QuerySets - Related Models
I have a set of related models - main points included below: class OrganisationDetails(models.Model): FormFieldOrgID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) FormFieldOrgCode = models.CharField(max_length=10, verbose_name='Organisation Code', help_text='Enter organisation identifier', default='NULL', ) FormFieldOrgName = models.CharField(max_length=75, help_text='Enter Organisation Name', verbose_name="Organisation Name") class DepartmentDetails(models.Model): FormFieldID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) FormFieldDeptName = models.CharField(max_length=75, help_text='Enter Department Name', verbose_name="Department name") # name for a department FormFieldDescription = models.CharField(max_length=200, help_text='Enter department description ', verbose_name="Department description") # describe the department class OrgDeptLink(models.Model): FormFieldID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) FormFieldDeptID = models.ForeignKey(DepartmentDetails, on_delete=models.CASCADE, related_name='DepartmentDetails', verbose_name='Department', help_text='Select department') # department FormFieldOrgID = models.ForeignKey(OrganisationDetails, on_delete=models.CASCADE, related_name='SubordinateRole', verbose_name='Organisation', help_text='Select organisation') class OIRLinkStakeholders(models.Model): FormFieldOIRStakeLinkID = models.UUIDField(primary_key=True, default=uuid.uuid4(), editable=False) FormFieldOIRStakeholderID = models.ForeignKey(DepartmentDetails, on_delete=models.CASCADE, help_text='Select Internal Stakeholder', verbose_name='Stakeholder ID') # TODO Set list to Organisation Departments FormFieldOIR = models.ForeignKey(OIROverview, help_text='Select OIR Document Name', on_delete=models.CASCADE, verbose_name='OIR ID') # TODO Default to be set to a selected organisation I would like to get: FormFieldDepartmentName from class DepartmentDetails(models.Model) using pk from Orgdetails - extract from views.py: def oirdetails(request, pk): orgdetails = OrganisationDetails.objects.filter(FormFieldOrgID=pk) oiroverview = OIROverview.objects.filter(FormFieldOrgDetailID=pk) alldepartments = OrgDeptLink.objects.filter(FormFieldOrgID=pk) currentstake = OIRLinkStakeholders.objects.filter( FormFieldOIRStakeholderID__DepartmentDetails__FormFieldOrgID_id__exact=pk) The variable for currentstake is the one im trying to relate to: ive include a snapshot of the relationships below Ive had a look at the documentation - but … -
How to access django server using raspberrypi hostname from a Mobile?
I have a django development server running on my raspberrypi server. The raspberrypi has a hostname assigned within the raspberrypi as 'raspberrypi'(which is default). Withinin settings.py of django project I have allowed hosts as ALLOWED_HOSTS = ['localhost','raspberrypi','192.168.0.101'] where '192.168.0.101' is ip address of raspberrypi server.To run the development server using command python manage.py runserver 0.0.0.0:8000 I have my laptop and mobile(Android) in same wifi network as of raspberry pi. I can access the django server from laptop using raspberrypi hostname as address http://raspberrypi:8000/ but not from my mobile. To access it from my mobile i have to give the address http://192.168.0.101:8000/. Why cant the website be accessed using hostname from mobile when it is possible from laptop ? Note: giving ALLOWED_HOSTS = ["*"] doesn't change this -
Google app engine crash when i switch to manual scaling
I have Google app engine standard environment instance with Django 2.2 (python 3.7). This instance works fine when i use "basic scaling". However, when i try to enable 1 instance always on by setting the "manual scaling" to 1 instance, the app keeps crashing and i can't figure out why. this is the error message: 2020-07-01 20:00:34 [2020-07-01 20:00:34 +0000] [8] [INFO] Starting gunicorn 20.0.4 2020-07-01 20:00:34 [2020-07-01 20:00:34 +0000] [8] [INFO] Listening at: http://0.0.0.0:8080 (8) 2020-07-01 20:00:34 [2020-07-01 20:00:34 +0000] [8] [INFO] Using worker: sync 2020-07-01 20:00:35 {"severity": "WARNING", "message": "App is listening on port 8080. We recommend your app listen on the port defined by the PORT environment variable to take advantage of an NGINX layer on port 8080."}\n[2020-07-01 20:00:35 +0000] [15] [INFO] Booting worker with pid: 15 2020-07-01 20:00:38 [2020-07-01 20:00:38 +0000] [8] [INFO] Handling signal: term 2020-07-01 20:00:38 [2020-07-01 20:00:38 +0000] [15] [INFO] Worker exiting (pid: 15) 2020-07-01 20:00:38 [2020-07-01 20:00:38 +0000] [8] [INFO] Shutting down: Master 2020-07-01 20:02:12 "GET /_ah/start HTTP/1.1" 500 2020-07-01 20:02:14 "GET /_ah/start HTTP/1.1" 500 This is my app.yaml configuration: runtime: python37 entrypoint: gunicorn -b 0.0.0.0:8080 generator.wsgi manual_scaling: instances: 1 handlers: - url: /static static_dir: static/ - url: /.* script: auto secure: … -
Adding a Context to a ListView returning AttributeError
I am trying to add the count of comments of an item to a list view but I keep getting Exception Value: 'DesignerOnlyPostListView' object has no attribute 'object' error I was trying to fix it at first but it returns the total no. of comments for all items not just a displayed item. Here is the models.py class Comment(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments") comment = models.CharField(max_length=250, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.subject, str(self.user.username)) def total_comments(self): return self.comment.count() Here is the views with the attribute error class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') def get_context_data(self, **kwargs): comments = Comment.objects.filter(item=self.object, status='New') context = super().get_context_data(**kwargs) context["total_comments"] = comments.count() return context Here is the views with total no. of comments not just the item displayed class DesignerOnlyPostListView(ListView): model = Item template_name = "designer_only_posts.html" context_object_name = 'items' paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Item.objects.filter(designer=user).order_by('-timestamp') def get_context_data(self, **kwargs): comments = Comment.objects.all() context = super().get_context_data(**kwargs) context["total_comments"] = comments.count() return context Here is the complete template {% for item in object_list %} {% if item.image … -
Django queryset filter based on number of children
I'm using Django filters in order to do some filtering for my project. I have the following models: class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo, models.CASCADE) My query looks like this: Foo.objects.filter(blah=blah) I want to narrow this filter by only giving me Foo objects that have at least 5 Bar objects connected with it via FK. So if I have 3 Foo objects which respectively have 7, 5, and 3 Bar objects that have their id, then only the first two should be in the end queryset. How would I do that so that the evaluated queryset only has the first two objects in memory? Thanks! -
save model on TabularInline
I want to update the quantity whenever a new purchase is made. I am using admin for it. Here's what I tried, admin.py: class Purchased_InventoryInline(admin.TabularInline): model=Purchased_Inventory extra=0 classes = ['collapse'] raw_id_fields=['vendor_name'] readonly_fields=('time_purchased',) can_delete=False def save_model(self, request, obj, form, change): obj.user = request.user obj.item.quantity+=obj.qty obj.item.save() obj.save() super().save_model(request, obj, form, change) class Inventory_Checklist_admin(admin.ModelAdmin): inlines=[Purchased_InventoryInline] def save_model(self, request, obj, form, change): obj.user = request.user pur=0 consu=0 if Purchased_Inventory.objects.filter(item=obj).exists() : for o in Purchased_Inventory.objects.filter(item=obj): pur+=o.qty if Consumed_Inventory.objects.filter(item=obj).exists(): for o in Consumed_Inventory.objects.filter(item=obj): consu+=o.qty pc=pur-consu obj.save() super().save_model(request, obj, form, change) admin.site.register(Inventory_Checklist, Inventory_Checklist_admin) Here is my models.py: Here Vendor is another class with Vendor details which is added as raw_id class Inventory_Checklist(models.Model): item=models.CharField(max_length=30) quantity=models.FloatField(default=0, null=True) units=models.CharField(max_length=10) min_qty=models.IntegerField(default=0) vendor=models.ForeignKey(Vendor,on_delete=models.SET_NULL, null=True) categories=models.CharField(max_length=20) class Meta: verbose_name_plural="Inventory Management" def __str__(self): return self.item class Purchased_Inventory(models.Model): time_purchased=models.DateTimeField(default=timezone.now()) qty=models.IntegerField(default=0) price=models.IntegerField(default=0, verbose_name="Total Cost") item=models.ForeignKey(Inventory_Checklist, on_delete=models.SET_NULL, null=True ) vendor_name=models.ForeignKey(Vendor,on_delete=models.SET_NULL, null=True) class Meta: verbose_name_plural="Purchased" def __str__(self): return "" -
Hosting Django And React with parcel bundler on Heroku
I've been trying to host my Django rest application using react at the frontend with Parcel bundler, After a successful hosting, the styles and js are not loaded, with a MIME type error in the console: Refused to apply style from 'https://minglemarket.herokuapp.com/src.aaba6b6a.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. minglemarket.herokuapp.com/:1 Refused to apply style from 'https://minglemarket.herokuapp.com/style.e1ff692e.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. minglemarket.herokuapp.com/:1 Refused to execute script from 'https://minglemarket.herokuapp.com/src.8d3ada04.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. -
When to use UserPassesTestMixin vs PermissionRequiredMixin
It seems to me that these mixins can accomplish similar goals in different ways. I can let someone access a view by checking if the user has a permission with PermissionRequiredMixin, or I can use UserPassesTest and write a test_func that checks if a user is in a particular group, or even check the permission there. I'm new to Django and am having trouble knowing when to use one versus the other. In isolation I understand what they do, but not well enough to understand where they are appropriate. A couple scenarios I've come across I'm not certain which is best Which should I use to limit access to certain views? In an app where users can create objects, limiting updating/deletion of these objects to the creator -
Cant save Details Continuously using Django model
i am trying to insert some data Continuously , but showing error "IntegrityError('duplicate key value violates unique constraint "RFIDActivation_ActivationId_key"\nDETAIL: Key ("ActivationId")=(6de9ed9a) already exists.\n',)" my models.py class RFIDActivation(models.Model): RFIDActivationId = models.AutoField(primary_key=True, db_column='RFIDActivationId') Device = models.ForeignKey(Device, on_delete=models.CASCADE, db_column='DeviceId') Employee = models.ForeignKey(Employee, on_delete=models.CASCADE, db_column='EmployeeId') ActivationId = models.CharField(max_length=10, unique=True, default=uuid4().hex[:8]) ActivationStatus = models.CharField(max_length=1)default=None) CreatedDate = models.DateField(null=True, blank=True, default=None) CreatedUser = models.ForeignKey(Login, on_delete=models.PROTECT, db_column='CreatedUser', related_name='CreatedUser_Rfid', null=True, blank=True, default=None) ModifiedDate = models.DateField(null=True, blank=True, default=None) ModifiedUser = models.ForeignKey(Login, on_delete=models.PROTECT, db_column='ModifiedUser', related_name='ModifiedUser_Rfid', null=True, blank=True, default=None) class Meta: db_table = "RFIDActivation" my serializer.py class RFIDActivationSerializer(serializers.ModelSerializer): class Meta: model = RFIDActivation fields = '__all__' my views.py @api_view(["POST"]) @permission_classes([IsAuthenticated]) def insert_data(request): activation = { "Employee": request.data.get("Employee"), "Device": request.data.get("Device"), "ActivationStatus": "0", "ActivationMessage": "Activation Initiated", "CreatedDate": date.today(), "CreatedUser": request.user.id } serializer = RFIDActivationSerializer(data=activation) if serializer .is_valid(): serializer .save() else: return Response(serializer .errors, status=status.HTTP_400_BAD_REQUEST) 1st time data inserted successfully. and activationid generated as 6de9ed9a then i tried insertion using the same input once more using the postman but showing error "IntegrityError('duplicate key value violates unique constraint "RFIDActivation_ActivationId_key"\nDETAIL: Key ("ActivationId")=(6de9ed9a) already exists.\n',)" if i rerun the application we can insert with the same data. why previous ActivationId(not primary key - its a automatic generating unique key) is taking again with next insertion ? How can … -
Django create object but not save to DB
I am trying to build parcel box which should have few parts inside. I need to transfer parcel ID (as I know it can be done only when object is created) to every selected part and problem is if page is refreshed or pressed back, empty parcel is created. Currently my logic looks like this: Select parts from a list -> press button(GET) -> create new box and add all selected parts to that box -> Fill parcel information -> save all data. My views: if request.GET.getlist('_action'): selected_values = request.GET.getlist('_action') selected_objects = ReturnedParts.objects.filter(id__in=selected_values) l = request.user.groups.values_list('id', flat=True) l_as_list = list(l)[0] query_set = Group.objects.filter(user=request.user) company_name = query_set[0].name box = BoxPackage(company_id=l_as_list) box.save() box_obj = BoxPackage.objects.get(id=box.id) box_form = BoxPackageForm(request.POST, instance=box_obj) for part in selected_objects: part.package = box part.save() if request.method == "POST": box_form = BoxPackageForm(request.POST, instance=box_obj) if box_form.is_valid: box_form.save() return redirect('parts') context = { 'box_form': box_form, 'company_from': company_name, 'selected_objects': selected_objects, } return render(request, 'package_view_edit.html', context) return HttpResponse("Select parts before creating package!") I have tried to save() method with POST method, but in this case, my selected data is lost when on new template I press submit button. How can I overcome this issue? What methods should I use? -
New Postgresql databse : column "id" is of type integer but expression is of type uuid when creating super user
I decided to work with a new database and in the same time change my custom user id field to UUID class PersoUser(AbstractBaseUser): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField( verbose_name="Email Adress", max_length=200, unique=True) username = models.CharField( verbose_name="username", max_length=200, unique=True) first_name = models.CharField(verbose_name="firstname", max_length=200) last_name = models.CharField(verbose_name="lastname", max_length=200) date_of_birth = models.DateField(verbose_name="birthday") is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = PersoUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["date_of_birth", "username"] def __str__(self): return self.username def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return self.is_admin class PersoUserManager(BaseUserManager): def create_user(self, username, email, date_of_birth, password=None): if not username: raise ValueError("Users must have a username ") user = self.model( username=username, email=self.normalize_email(email), date_of_birth=date_of_birth ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, date_of_birth, password=None): user = self.create_user( username, email=email, password=password, date_of_birth=date_of_birth ) user.is_admin = True user.save(using=self._db) return user When attempting to create a super user threw the shell, after providing an email username psswd and date_of_birth … -
first_name in django model
how can I access to first_name of a user in django template?. for example my writer in django model is like this below : writer = models.ForeignKey(User, on_delete=models.CASCADE) -
Cannot run django-admin.py startproject in virtual environment, or at all, in Ubuntu
I am trying to create a project in a virtual environment in Ubuntu 16.04 I am using Python 3.6 What I do so far is sudo bash cd Desktop/DamLevels-course2/Damlevels2/ source venv2/bin/activate django-admin.py startproject dams The error says: ImportError: No module named 'secrets' I have checked the list of modules in python and secrets is there, but when I try to import to the virtual environment I get an error saying : import: not authorized 'secrets' @ error/constitute.c/WriteImage/1028 I tried adding the shebang line as well (#!/usr/bin/env) but that didn't seem to work; running the startproject line again results in the same error message as before. I am very new to all of this, so I would appreciate fairly simple help. -
Django MPTT, get_children of node, then get_children of that node until through the entire tree
I'm using Django-MPTT to create a website where you can create a goal, and then create infinite subgoals with each subgoal containing a "progress" field. The progress of each child is determined by the parents progress divided by number of siblings. This way i can add up "finished" leaf_node subgoals to get an overall progress bar for the goal. I want to start from the root, get_children(), go through each child and set a "progress" for that field equal to the parents "progress" divided by number of of siblings. Then check if that child is_leaf_node or if it has children and repeat till done. Any help is GREATLY appreciated as i've been struggling with this problem for a long time... :) -
Can't find static CSS file/images when deploying Django app to PythonAnywhere
I am having trouble deploying my Django portfolio using PythonAnywhere. I have successfully deployed the application, but it is failing to find my static images and CSS file. settings.py: """ Django settings for portproject project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '********************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['pbuzzo.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'portapp', ] SITE_ID = 1 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', ] STATIC_URL = '/portapp/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) ROOT_URLCONF = 'portproject.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', ], }, }, ] WSGI_APPLICATION = 'portproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
TypeError: 'tzinfo' is an invalid keyword argument for this function Django
I am creating an api to get date on excel sheet,but unable to fetch date in desired form. I am getting this error.Even if i remove .replace(tzinfo=None).then also not getting the date in correct form.(output of date is 44013) #models class Task(models.Model): Id=models.IntegerField() Name=models.CharField(max_length=50,null=False,blank=True) Image1=models.FileField(blank=True, default="", upload_to="media/images",null=True) Image2=models.FileField(blank=True, default="", upload_to="media/images",null=True) Date=models.DateField(null=True,blank=True) def __str__(self): return str(self.Name) #viewset class TaskViewSet(viewsets.ViewSet): def list(self, request): try: response=HttpResponse(content_type='application/ms-excel') response['Content-Disposition']='attachment; filename="users.xls"' wb=xlwt.Workbook(encoding='utf-8') ws=wb.add_sheet('Tasks', cell_overwrite_ok=True) row_num=0 font_style=xlwt.XFStyle() font_style.font.bold=True columns=['Id','Name','Image1','Image2','Date'] for col_num in range(len(columns)): ws.write(row_num,col_num,columns[col_num],font_style) font_style=xlwt.XFStyle() data=Task.objects.values_list('Id','Name','Image1','Image2','Date') date_format=xlwt.XFStyle() date_format.num_format_str='yyyy/mm/dd' for row in data: row_num+=1 print('row_num', row_num) for col_num in range(len(row)): if isinstance(row[col_num],date): print(row[col_num]) ws.write(row_num,col_num,row[col_num].replace(tzinfo=None),font_style) else: ws.write(row_num,col_num,row[col_num],font_style) wb.save(response) #print(row.Date) return response except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) -
Don't manage to use a dynamic view for an url with Django
I'm trying to dynamically call a view for an url. Let me precise this. I would like to create some objects, in fact 'Exercises', and each one would need a view (because of a huge number of variables, which would be different from an exercise to another). I'm using a TemplateView for each exercise. Actually, each one needs a different htlm too, but this one can be given in the view. I tried the method found here : Dynamic for url Here is the code that interest us : I precise that each exercise of the class Exercise (in models.py) would have at least one attribute called wanted_view which would indicate the wanted view for the exercise. example.html (which contains the link to an exercise : {% for exercise in list_exercise %} ... <a href="{% url 'vue_exercise' exercise.id exercise.wanted_view %}"> The link to the wanted exercise </a> ... {% endfor %} where list_exercise is a context variable of example.html which contains all the objects of the class Exercise. urls.py : ... from . import views urlpatterns = [ url(r'^exercise/(?P<exercise_id>\d+)/(?P<channel>\w+)/$', views.switcher, name='vue_exercise'), ] Here a dynamic url which waits for exercise_id (here exercise.id) and channel (here exercise.wanted_view). views.py : def switcher(request, … -
Django: How to filter with the abbreviations in Django?
I'm working on a Django project. There is a model named University which stores the University names and other details. I've a search view where I'm supposed to search the universities with full name or abbreviations. For example if there is a university with name "University of Engineering and Technology", I should be able to search it with "UET". Here is my search view: def search(request): search = request.GET["search"] universities = University.objects.filter(Q(name=search)) context = {"universities": universities} return render(request, "company/search.html", context) -
Django with opencv live streaming face detection and identifying images webstream issue
I am trying to use Django with OpenCV for face detection I am able to detect the face by using the live streaming that gets streamed in browser. I am able also able to match the face and label it with the correct name. issue I have is the video stream freezes while the detection process. I am looking to ensure the video stream should work the normal way before and after detection which is not happening. My images are stored in a folder and if the corresponding image person comes in front of the webcam it identifies and labels the person. Here is the code i use .. any help on this is much appreciated. import os import face_recognition import cv2 import numpy as np from face_recognition.face_recognition_cli import image_files_in_folder from pprint import pprint #from ecapture import ecapture as ec #cap = cv2.VideoCapture('vid2.mp4') #WHITE = [255, 255, 255] dir_path ='Images' my_dir = 'Images/' # Folder where all your image files reside. Ensure it ends with '/ known_face_encodings = [] # Create an empty list for saving encoded files for i in os.listdir(my_dir): # Loop over the folder to list individual files image = my_dir + i image = face_recognition.load_image_file(image) # … -
'URLPattern' object is not a mapping. Django
I am trying to add sitemap.xml I followed this tutorial https://pocoz.gitbooks.io/django-v-primerah/rasshirenie-prilozheniya-blog/dobavlenie-sitemap.html I have an error 'URLPattern' object is not a mapping In template /home/alex/root_folder/projects/6_eda_parser_regru/eda_parser_regru/src/blog/templates/blog/base.html, error at line 33 ... <a class="navbar-brand js-scroll-trigger" href="{% url 'main_list' %}"><span style="color: red">E</span>damer</a> blog/sitemaps.py (added new file) +from django.contrib.sitemaps import Sitemap +from .models import Shop + + +class ShopSitemap(Sitemap): + changefreq = 'weekly' + priority = 0.9 + + def items(self): + return Shop.objects.all() + + def lastmod(self, obj): + return obj.publish blog/urls.py from django.contrib.sitemaps.views import sitemap from .sitemaps import ShopSitemap from django.conf.urls import include, url sitemaps = { 'shops': ShopSitemap, } urlpatterns = [ path('', HomePageView.as_view(), name='main_list'), path('search/', SearchResultsView.as_view(), name='search_results'), path('search_shop/<slug:slug>/', ProductListView.as_view(), name='search_shop'), path('shops/', ShopListView.as_view(), name='shop_list'), path("robots.txt", TemplateView.as_view(template_name="blog/robots.txt", content_type="text/plain"), #url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), # NEW LINE url(r'^sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ), -
How to write the urls in urls.py in django?
I am trying to write a class based view which will take two input say city and bankname and filter the data and send the results? I am trying to write http://127.0.0.1:8000/api/bankcitydetail?city=mumbai&bankname=CENTRAL BANK OF INDIA. How I will write the urls path in urls.py