Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to Create with OneToOneField Django
I'm stuck with this issue for a while now and couldn't find a solution. Here is the issue: Background: I have CustomUser(AbstractUser) model and HeroesUser which has OneToOneField relationship with CustomUser model. (Hero user is a user type, later on I'll have more fields but at the moment I just put in "city" to be simple) I want to be able to create a hero user for each custom user, but unable to do so with this OneToOneRelationship. So please please if you have experience, please help me!!! Here are my codes: models.py from django.contrib.auth.models import AbstractUser import datetime class CustomUser(AbstractUser): is_hero = models.BooleanField(default=False) is_host = models.BooleanField(default=False) want_newsletter = models.BooleanField(default=False) def __str__(self): return self.username class HeroesUser(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) city = models.CharField(max_length=50, default="") serializers.py from .models import CustomUser, HeroesUser from django.utils import timezone class CustomUserSerializer(serializers.Serializer): id = serializers.ReadOnlyField() username = serializers.CharField(max_length=200) email = serializers.CharField(max_length=200) password = serializers.CharField(write_only=True) first_name = serializers.CharField(max_length=200) last_name = serializers.CharField(max_length=200) is_hero = serializers.BooleanField(default=False) is_host = serializers.BooleanField(default=False) is_staff = serializers.BooleanField(default=False) def create(self, validated_data): return CustomUser.objects.create_user(**validated_data) class CustomUserDetailSerializer(CustomUserSerializer): def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.is_hero = validated_data.get('is_hero', instance.is_hero) instance.is_host = validated_data.get('is_host', instance.is_host) instance.is_staff = validated_data.get('is_staff', instance.is_staff) instance.save() … -
Is there a way to get the columns from a joined table in the model instance dict object?
t = PurchaseHeader.objects.first() t.__dict__ { '_state': <django.db.models.base.ModelState object at 0x7f4b34aa7fa0>, 'id': 3, 'ref': 'jhkh', 'goods': Decimal('-100.00'), 'discount': Decimal('0.00'), 'vat': Decimal('-20.00'), 'total': Decimal('-120.00'), 'paid': Decimal('-120.00'), 'due': Decimal('0.00'), 'date': datetime.date(2020, 11, 7), 'due_date': datetime.date(2020, 11, 14), 'period': '202007', 'status': 'c', 'created': datetime.datetime(2020, 11, 7, 15, 46, 48, 191772, tzinfo=<UTC>), 'cash_book_id': None, 'supplier_id': 1128, 'type': 'pc' } When I joined the supplier table I was disappointed to find that the columns are not included in the dict. Below, t.__dict__ is the same as above. I noticed that the Supplier model instance is cached inside of t._state so I guess I could create my own method which all models inherit from which does what i want - all the columns from all tables inside a dict. But I wondered if anybody knew a way of doing this sort of thing out of the box? t = PurchaseHeader.objects.select_related("supplier").first() t.__dict__ -
Ckeditor texteditor not appearing in django admin where RichTextfield is applied
I have tried everything but the texteditor is not appearing in the admin page in the richtextfield type. I installed django ckeditor and have the following in the settings.py: Richtextfield pic CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" #ckeditor configs #todo CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'width': 1000, 'height': 400 }, } DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') My urls is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('', admin.site.urls), path('', include('apps.accounts.urls')), path('', include('apps.blogs.urls')), path('', include('apps.enquiry.urls')), path('', include('apps.packages.urls')), path('', include('apps.booking.urls')), path('ckeditor', include('ckeditor_uploader.urls')), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # ]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have even tried collectstatic and every files are collected but still the richtextfield appears blank. How to solve this?? -
Django enum named groups
I want a listing to be able to have a specific category, so the seller will choose a general category and then onto a more specific one, for example: Men's Wear: Jeans: Skinny Fit Slim Fit Regular Fit Pants: Slim Fit Formal Casual Women's Apparel: Tops: Tunics Denim: Jeans I tried the named groups like in django docs: https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-choices-named-groups MEDIA_CHOICES = [ ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), ) ), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), ) ), ('unknown', 'Unknown'), ] But when I tried, it gives the error product.Listing.category: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. here is my code: class Listing(models.Model): CATEGORY = [ ('Women\'s Apparel', ( ('Dresses', ( ('party_dresses', 'Party Dresses'), ) ), ), ), ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=255) description = models.CharField(max_length=255) new_condition = models.BooleanField() category = models.CharField(choices=CATEGORY, max_length=255) why is it showing error ? is it because the enum groups cant be nested more than 1 level ? thank you -
Is there a way to send a form class as parameter to a function in a template in django?
I'm creating a website that has multiple pages that each has one form. This one form on each page has an "add", "modify" and "delete" button. I need to create a lot functions to process all this because they are on different pages working with different form classes and model classes. To create a more general approach it would be usefull if I could just pass the form class and/or model class as a parameter in a template to a view (se example below). When writing a capture pattern for this in the urls.py file I cant find anything to capture a reference to an object though like a form class or model class... I only see that you can capture strings, integers and so on. What im thinking about is something like this: {% url '' id form_class %} where id and form class are the parameters to the view. Is there any way to actually do this ? I want to do this so I dont have to write add, modify and delete view functions for every form on every page and instead have one add, modify and delete for every form without having if loops and checking … -
Delete an object with a large number of CASCADE models on Django
I am running into an issue where I cannot delete user accounts with Django. The problem is that there are several other models in code that have the field: user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) These models themselves have other models that are set to be deleted with on_delete=models.CASCADE when they are deleted. So when I try to delete a user that had a lot of activity on my website, it can quickly become tens of thousands of items to delete. This causes the delete operation to never end and the account to not get deleted. Worse, only some of the content gets deleted as the operation is interrupted. How should I handle deleting a model with many CASCADE delete linked to it? I am using Django 3.1 with a MySQL db. -
Django: posting information to multiple models with one html form
I'm building my first solo django project right now so I'm learning a lot. I've run into a problem that I can't think how to fix. For a fantasy football app project, I've represented each type of player position with their own model. Like this... class Quarterback(models.Model): name = models.CharField(max_length=20) class Runningback(models.Model): name = models.CharField(max_length=20) class Widereceiver(models.Model): name = models.CharField(max_length=20) class Tightend(models.Model): name = models.CharField(max_length=20) class Kicker(models.Model): name = models.CharField(max_length=20) I have a "choose player" page that uses javascript to fill in model forms that I've made for each player model. This is my forms.py class Quarterbackform(forms.ModelForm): class Meta: model = Quarterback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'QB_name'}) } class Runningbackform(forms.ModelForm): class Meta: model = Runningback fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'RB_name'}) } class Widereceiverform(forms.ModelForm): class Meta: model = Widereceiver fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'WR_name'}) } class Tightendform(forms.ModelForm): class Meta: model = Tightend fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'TE_name'}) } class Kickerform(forms.ModelForm): class Meta: model = Kicker fields = "__all__" widgets = { 'name': forms.TextInput(attrs={'id':'K_name'}) } My views.py has this function to save player selections to their respective model. def emp(request): url = 'hidden' r = requests.get(url.format()).json() player_data = [] #print(r) … -
django import export error: Line number: 1 - import_obj() takes 3 positional arguments but 4 were given
I've upgraded a django project to the latest version of django 3.1.2 and also one of it's dependencies django-import-export which as it says helps import data to models, previously importing csv was working ok but with the update of it also to the latest version i get this error Line number: 1 - import_obj() takes 3 positional arguments but 4 were given DAVAN, LEMETEI, M, 37291003, , 4827, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, dry_run) TypeError: import_obj() takes 3 positional arguments but 4 were given Line number: 2 - import_obj() takes 3 positional arguments but 4 were given PARASHINA, NTANIN, M, 12740086, , 4828, , KAMPI YA KANZI, , , , , , , , , 7/9/2020, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, , N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, N/A, Traceback (most recent call last): File "/home/sammy/webapps/envs/kpsga/lib/python3.8/site-packages/import_export/resources.py", line 662, in import_row self.import_obj(instance, row, … -
RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended
When I am daemonizing the celery worker it is giving me the above warning along with the following error: Traceback (most recent call last): File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 316, in start blueprint.start(self) File "/var/app/venv/env/lib/python3.7/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/consumer/consumer.py", line 592, in start c.loop(*c.loop_args()) File "/var/app/venv/env/lib/python3.7/site-packages/celery/worker/loops.py", line 91, in asynloop next(loop) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 299, in create_loop item() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 170, in call return self.throw() File "/var/app/venv/env/lib/python3.7/site-packages/vine/promises.py", line 167, in call retval = fun(*final_args, **final_kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 336, in _schedule_queue queue, callback=promise(self._loop1, (queue,)), File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 352, in _get_bulk_async return self._get_async(queue, maxcount, callback=callback) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 362, in _get_async qname, count=count, connection=self.asynsqs, File "/var/app/venv/env/lib/python3.7/site-packages/kombu/transport/SQS.py", line 456, in asynsqs region=self.region File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/sqs/connection.py", line 27, in init **kwargs File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 186, in init **http_client_params) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/aws/connection.py", line 151, in init self._httpclient = http_client or get_client() File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 22, in get_client client = hub._current_http_client = Client(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/init.py", line 13, in Client return CurlClient(hub, **kwargs) File "/var/app/venv/env/lib/python3.7/site-packages/kombu/asynchronous/http/curl.py", line 43, in init raise ImportError('The curl client requires the pycurl library.') ImportError: The curl client requires the … -
Django 1.6.5 urlreverse change default directory name
import django from django.core.urlresolvers import reverse print django.get_version() # 1.6.5 app -> inventory url = reverse('product', slug='foo-bar') url = '/inventory/foo-bar/ How do I get the django url to reverse and change the name of directory? For example, I am trying to achieve url='/product/foo-bar/' -
How can I search data from a table using a field from the 2 tables below
So, maybe my questions is noth enaught clearly... I'll try to show it in example. I have 3 tables: models.py class Department(models.Model): department = models.CharField(max_length=100) activate = models.BooleanField(default=True) def __str__(self): return self.department class Employee(models.Model): noEmployee = models.DecimalField(max_digits=8, decimal_places=0, default=10) # name = models.CharField(max_length=50) surname = models.CharField(max_length=100) department = models.ForeignKey(Department, on_delete=models.CASCADE, default=1) activate = models.BooleanField(default=True) def __str__(self): return str(self.noEmployee) class List_of_tasks(models.Model): myData = datetime.now() formatedDate = myData.strftime("%Y-%m-%d") task = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) responsible = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) start_date = models.DateField('Start date', default=formatedDate) finish_date = models.DateField('Finish date', default=formatedDate) finished = models.BooleanField(default=False) def __str__(self): return self.task And small class in views.py def filter(request): qs = List_of_tasks.objects.all() task_query = request.GET.get('task_contains') department_query = request.GET.get('department_contains') print(task_query) if department_query is not None: dep = Employee.objects.filter(department__department__icontains=department_query) for d in dep: print('department: ', d.noEmployee, d.name, d.surname) for d in dep: dep2 = List_of_tasks.objects.filter(responsible__noEmployee__exact=d.noEmployee) for d2 in dep2: print('Tasks: ', d2.task, d2.responsible) if is_valid_queryparam(task_query): qs = qs.filter(task__icontains=task_query) context = {'queryset': qs,} return render(request, 'appl01/export.html', context) Finding TASKS or RESPONSIBLE persons in table List_of_tasks is easy but I would like to find for example all tasks assigned to department... two tables down... As you can see I created my own method which works as I want but is not … -
Registration user with multiple usernames - Django REST
I'm trying to implement a user registration and authentication using django rest framework and I'm not sure how to implement it. The thing is that I want a user to have multiple usernames/nicknames so that's why I have a little bit troubles. The current models I have: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=50, unique=True, error_messages={ 'unique': _("Email already exists."), }, ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) gender = models.IntegerField(default=GENDER_MALE, choices=GENDER_CHOICES) date_of_birth = UnixDateTimeField(null=True, blank=True, ) ip = models.GenericIPAddressField(null=True) USERNAME_FIELD = 'email' class Meta: verbose_name = _('user') verbose_name_plural = _('users') class UserNicknames(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) username = models.CharField(max_length=10, null=False, unique=True, validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) is_current = models.BooleanField(default=False) As you can see I have the User model just like the django one but without the username and UserNicknames which contains the user nicknames (the UserNicknames.user field is the foreign key to the User.id field). The question is what is right way to implement the registration serializer? Should I get all the fields in User and UserNicknames and then do the logic or there is … -
How can we pass another field to Create Model Mixin?
Model: class ShopItem(models.Model): id = models.AutoField(db_column='ID', primary_key=True) name = models.CharField(db_column='Name', max_length=255) price = models.IntegerField(db_column='Price', default=0) description = models.CharField(db_column='Description', max_length=63) seller_id = models.ForeignKey(Seller, models.DO_NOTHING, db_column='SellerID') View: class SellerItemAPIView(GenericAPIView, ListModelMixin, CreateModelMixin, UpdateModelMixin): serializer_class = ShopItemSerializer permission_classes = [AllowAny] def get_seller(self, *args, **kwargs): phone_number = self.kwargs.get('phone_number') seller = Seller.objects.filter(Q(user_id__phone_number=phone_number))[0] return seller def post(self, request): seller = self.get_seller() return self.create(request, seller_id=seller.id) Is there any way to use this Creat method with another field? It now give me this error: { "seller_id": [ "This field is required." ] } -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/signup
I am getting page not found 404 ERROR, in Django. Even though i have mapped the URL correctly both in the main app and this app. urlpatterns = [ path('',views.mainpage,name='main'), path("signup/",views.signup,name='signup'), path("login/",views.login,name='login'), path("logout/",views.logout,name='logout') ] Now the below url is of the main app where I have included the urls.py of sub-app which is accounts. urlpatterns = [ path('',include('trial.urls')), path('accounts/',include('accounts.urls')), path('admin/', admin.site.urls), ] This is the URL mapping of the app name accounts, used to handle the account and registration details. The error is in this path http://127.0.0.1:8000/accounts/signup/signup Where as it works finely up to the below mentioned path. http://127.0.0.1:8000/accounts/signup Can anyone suggest me or help me finding out where it going wrong. What it should happen is, http://127.0.0.1:8000/accounts/signup after this path when we click submit it should create a user in database and return or redirect the page to login page, with a message user created. Below is the code of views.py of the accounts app. def signup(request): if request.method == 'POST': firstname = request.POST['first_name'] password1 = request.POST['password1'] user = User.objects.create_user(firstname=first_name,lastname=last_name,username =username ,email=email,password=password1) user.save(); print("USER CREATED SUCCESSFULLY") return redirect('/login.html') Anyone help me out what is going wrong. Thank you. -
Read time out issue while installing latest django version using pip
File "c:\users\hp\envs\dell\lib\site-packages\pip_vendor\urllib3\response.py", line 442, in _error_catcher raise ReadTimeoutError(self._pool, None, "Read timed out.") pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. -
Django: using multi pk in views.py
In django project my url.py looks like: urlpatterns = [ path('', views.home,name='home'), path('customer/<str:customer_id>', views.customer, name='customer'), path('create_order/<str:customer_id>', views.createOrder, name='create_order'), path('update_order/<str:order_id>', views.updateOrder, name='update_order'), path('delete_order/<str:order_id>', views.deleteOrder, name='delete_order'), ] and I have form.py with the following content: class OrderForm(ModelForm): class Meta: model = Order fields = ['product', 'status'] and finally my views.py has these functions: def createOrder(request, customer_id): customer = Customer.objects.get(id=customer_id) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'customer':customer, 'form': form} return render(request, 'accounts/order_form.html', context) def updateOrder(request, order_id): order = Order.objects.get(id=order_id) form = OrderForm(instance=order) print(form) if request.method == 'POST': form = OrderForm(request.POST, instance=order) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'accounts/order_form.html', context) Here in function updateOrder, I need to use customer name and I don't know how to grab it. I have tried to use both order_id and customer_id in urlpatterns but no result! I don't need to get all fields from form.py even customer field. -
handling multiple GenericRelations in django admin
I have multiple GenericRelations from Office to Picture for multiple sets of pictures. I'm having trouble with including them in the admin panel. With the current setup If I add 1 image to HomeSlideshow and two images to OfficeSlideshow and save, I will get three images in both HomeSlideshow and OfficeSlideshow. models.py class Office(models.Model): home_slideshow = GenericRelation(Picture) office_slideshow = GenericRelation(Picture) office_text = QuillField() manifesto_slideshow = GenericRelation(Picture, blank=True) manifesto_text = QuillField(blank=True) employees_pictures = models.ImageField() employees_text = QuillField() class Picture(models.Model): title = models.CharField(max_length=30, blank=True) image = models.ImageField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") def __str__(self): return self.title admin.py from django.contrib import admin from django.contrib.contenttypes.admin import GenericTabularInline from modeltranslation.admin import TranslationAdmin from pictures.models import Picture from .models import Office class HomeSlideshowInline(GenericTabularInline): model = Picture verbose_name = "Picture" verbose_name_plural = "Home-Slideshow" extra = 1 readonly_fields = ("image_preview",) def image_preview(self, obj): if obj.image: return mark_safe( '<img src="{url}" width="70" height="70" />'.format(url=obj.image.url) ) else: return "No image" class OfficeSlideshowInline(GenericTabularInline): model = Picture verbose_name = "Picture" verbose_name_plural = "Office-Slideshow" extra = 1 readonly_fields = ("image_preview",) def image_preview(self, obj): if obj.image: return mark_safe( '<img src="{url}" width="70" height="70" />'.format(url=obj.image.url) ) else: return "No image" class OfficeAdmin(TranslationAdmin): inlines = [HomeSlideshowInline, OfficeSlideshowInline, ManifestoSlideshowInline] admin.site.register(Office, OfficeAdmin) So far, … -
Compare date of datetime object in filter django
I use django 3.1.0 I have a release_time field(a DateTimeFeild) in my model, and i want to retrieve those records that have been released in current date. here is my model: class Test(models.Model): title = models.CharField(max_length=100) release_time = models.DateTimeField() end_time = models.DateTimeField() I use the following line to get my data: cur_time = localtime() // django.utils.timezone.localtime Test.objects.filter(release_time__date=cur_time.date()) This always returns an empty query set. I am sure that there are records that have this condition. PLease tell me am I doing this wrong?? -
getting error while rendering contact form and header title from database together in django
form.py i want to render data to my database together with a contact form attatched but when i try to do that it give an hmtl page instead of my index template def home(request): base = BaseHeader.objects.all() if request.method == 'GET': form = contactForm() else: form = contactForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data['name'] email = form.cleaned_data['email'] Phonenumber = form.cleaned_data['Phonenumber'] try: send_mail( 'Subject here', 'Here is the message.', 'from@gmail.com', ['to@gmail.com'], fail_silently=False,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('home') return render(request, 'index.html', {'form': form},{'menu_titles': base}) -
Django file installation
I am practicing django for last 5 days.I have a doubt in that topic.I installed django in a new virtual environment for my first project. My question is , if I want to start another django project should I want to install django again in the new project directory -
Deducting the value of one django field in a model class from another model class
I am looking for a way to subtract from a field named total in the first class, which i get by multiplying the price and the quantity. It works well and the result is evident in the database. I would like, after calculating the total, to deduct that field by referencing it in my second class. Basically, the sales input value - the referenced total object should return a profit/loss and store that in a field named profit in the second class. I have tried a few ways, it posts the sales value but not the calculated value in terms of profit/loss. Is there something I am overlooking or I am oversimplifying the code? from django.db import models import datetime from django.utils import timezone from numpy import array class CowData(models.Model): title = models.CharField(max_length=20, default="") user = models.CharField(max_length=20, null=False) feed = models.CharField(max_length=20, null=True) quantity = models.PositiveIntegerField() price = models.PositiveIntegerField() total = models.PositiveIntegerField(editable=True, blank=True, null=True, unique=True) # here i calculate the total by multiplying the price and the total def save(self, *args, **kwargs): self.total = array(self.total) self.total = self.price * self.quantity super(CowData, self).save(*args, **kwargs) class Sales(models.Model): # total = models.ForeignKey(CowData, to_field='total', on_delete=models.CASCADE, default=False) sales = models.PositiveIntegerField() profit = models.PositiveIntegerField() # What I … -
Problem in install django-cors-middleware
I installed django-cors-headers 3.5.0 and I got this error when I try to run the project. this is my configurations: requirement.txt: Django==2.2.0 djangorestframework==3.9.1,<3.10.0 psycopg2>=2.7.5,<2.8.0 Pillow>=5.3.0,<5.4.0 django-jalali-date==0.3.1 django-cors-headers==3.5.0 settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', #<------There it is 'core', 'user', 'land', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # its 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', ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) docker-compose: version: "3" services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db container_name: land_api db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword container_name: land_db but when I run "docker-compose up" i get this error: ModuleNotFoundError: No module named 'corsheaders' I try to add the installation in dockerFile but it didn't too. Is it really bug? or I miss something? -
TypeError in django while creating model instances
I have a model onlinebooking and I am trying to save the data the user inputs. However I am getting the error TypeError at /onlinebooking/ onlinebooking() got an unexpected keyword argument 'name'. I get this error after clicking the register button. Here is my model: class onlinebooking(models.Model): name = models.CharField(max_length=30) email = models.CharField(max_length=30) phone_number = models.IntegerField() room_type = models.CharField(max_length=10) booking_date = models.DateField() views.py from django.shortcuts import render,redirect from .models import onlinebooking def onlinebooking(request): if request.method == "POST": name = request.POST['Name'] email = request.POST['email'] phone_number = request.POST['phone_no'] room_type = request.POST['room_type'] booking_date = request.POST['booking_date'] online = onlinebooking(name=name,email=email,phone_number=phone_number,room_type=room_type,booking_date=booking_date) online.save() return redirect('/') else: return render(request,'hotel/onlinebooking.html') form used: <form action="/onlinebooking/" method="post"> {% csrf_token %} <div class="text-primary"> <div class="form-row"> <div class="form-group col-md-6"> <label for="inputEmail4">Name</label> <input type="text" class="form-control" id="inputEmail4" name="Name" required> </div> <!-- <div class="form-group col-md-6"> <label for="lastname">Last name</label> <input type="text" class="form-control" id="lastname" name="lastname" required> </div> --> <div class="form-group col-md-6"> <label for="inputPassword4">Email</label> <input type="text" class="form-control" id="inputPassword4" name="email" required> </div> <div class="form-group col-md-6"> <label for="inputPassword4">Phone no</label> <input type="text" class="form-control" id="inputPassword4" name="phone_no" required> </div> <div class="form-group col-md-6"> <label for="inputState">Room Type</label> <select id="inputState" class="form-control" name="room_type"> <option selected>Standard</option> <option>Delux</option> <option>Premium</option> </select> </div> <div class="form-group col-md-6"> <label for="bookingtime">Booking Date</label> <input type="date" id="bookingtime" name="booking_date" required> </div> <div class="text-center"> <input type="submit" value="Register" name="submit-emp" class="btn … -
I am getting failed on gunicorn status on aws ec2 instance
I installed gunicorn on my aws ec2 instance and start the gunicorn but when I checked the status of gunicorn ubuntu@ip-address:~$ sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2020-11-22 07:40:01 UTC; 2s ago Process: 25002 ExecStart=/webapps/myapps/bin/gunicorn --access-logfile - --workers 3 --preload --bind unix:/webapps/myapps/bin/siteapp.sock siteapp.wsgi:application (code=exited, status=1/FAILURE) Main PID: 25002 (code=exited, status=1/FAILURE) Nov 22 07:40:01 ip-address gunicorn[25002]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Nov 22 07:40:01 ip-address gunicorn[25002]: File "/webapps/myapps/myapps/settings.py", line 244, in <module> Nov 22 07:40:01 ip-address gunicorn[25002]: 'propagate': False, Nov 22 07:40:01 ip-address gunicorn[25002]: File "/usr/local/lib/python3.6/logging/config.py", line 795, in dictConfig Nov 22 07:40:01 ip-address gunicorn[25002]: dictConfigClass(config).configure() Nov 22 07:40:01 ip-address gunicorn[25002]: File "/usr/local/lib/python3.6/logging/config.py", line 566, in configure Nov 22 07:40:01 ip-address gunicorn[25002]: '%r: %s' % (name, e)) Nov 22 07:40:01 ip-address gunicorn[25002]: ValueError: Unable to configure handler 'logfile': [Errno 13] Permission denied: '/webapps/myapps/logs/logfile' Nov 22 07:40:01 ip-address systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Nov 22 07:40:01 ip-address systemd[1]: gunicorn.service: Failed with result 'exit-code'. How can we solve it? -
lookup_field Return None In Django get_queryset
I have a class extend with GenericAPIView , I Can access to the lookup_field in my functions, but I can't use it in the queryset function. serializer_class = ShopItemSerializer permission_classes = [AllowAny] lookup_field = 'phone_number' def get_queryset(self): print(self.lookup_url_kwarg) # It Return None print(self.lookup_field) # It Return 'phone_number' shop_items = ShopItem.objects.filter(Q(seller_id__user_id__phone_number=self.lookup_field)) return shop_items def get(self, request, phone_number): result = self.list(request, phone_number) print(result.status_code) return result How Can I Access to the lookup_field in get_queryset ?