Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model object with foreign key add another model properties
I have two models: class Client(models.Model): name = models.CharField('Name', max_length=250) surname = models.CharField('Surname', max_length=250) phone = models.CharField('Phone', max_length=10) ... def __str__(self): return str(self.surname ) + ' | ' + str(self.name) class Checklist(models.Model): client_name = models.ForeignKey(Client, on_delete=models.CASCADE) point1 = models.BooleanField('point1', default=False) point2 = models.BooleanField('point2', default=False) point3 = models.BooleanField('point3', default=False) ... def __str__(self): return self.client_name The questions are: How can i provide or add all Client properties to Checklist instance? (note: I create Checklist object via forms.py) And when it's done how to get an access to Client properties using Checklist object? When I calling Checklist instance and send it to Telegram app - Telegram gives me an 'Id' instead of client_name...how fix it? Thank you all for any help in advance!! -
Django foreign keys queryset displayed in react-redux
I know that this question was asked a lot of times, but I can't find the answer to my specific problem. I have tried to get to the solution both on the backend (Django) and on the frontend (React.js and Redux) but I can't find it. I'm trying to make a simple dependent dropdown for car brands and car models, but I can only get the full list of models and not only the ones that are related to their brand. I'm new at Django and I don't know if my mistake is that I'm retrieving all data in my serializer or if I'm making the foreign key relationship wrong. If you need any more information or explanation please let me know. Thanks for your help! models.py: class Brand(models.Model): name = models.CharField(max_length=120, unique=True) def __str__(self): return self.name class Model(models.Model): brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, related_name='brand_id') name = models.CharField(max_length=120, unique=True) def __str__(self): return self.name serializers.py: class BrandSerializer(serializers.ModelSerializer): class Meta: model = Brand fields = '__all__' class ModelSerializer(serializers.ModelSerializer): class Meta: model = Model fields = '__all__' views.py: @api_view(['GET']) @permission_classes([AllowAny]) def getBrands(request): brands = Brand.objects.all() serializer = BrandSerializer(brands, many=True) return Response(serializer.data) @api_view(['GET']) @permission_classes([AllowAny]) def getModels(request): #This is wrong, but I don't know how to … -
How can I iterate through each item in a database and display them in divs on my html page with django?
I have some code written to find the first post in the database and output it to my page, but I', not sure how to go about iterating through the database. I've done similar things before but this is my first time using django and bootstrap. My view currently looks like this: def gallery_view (request): obj = GalleryPost.objects.get (id =1) context = { 'object' : obj } return render(request, "gallery.html", context) This works well enough for 1 object but as you can see it takes a set ID of 1, so I need to somehow iterate this to fetch every item from my DB and somehow output them properly. -
pytest-django: Register a database type after creation of test databases
I have a django model field that registers a database type: class FieldMeta(type): def __init__(cls, name, bases, clsdict): super().__init__(name, bases, clsdict) cls.register_type() def register_type(cls): db_type = cls().db_type(connection) cursor = connection.cursor() try: cursor.execute( "CREATE TYPE foo AS (first integer, second integer);" ) _logger.warn("creating type") except ProgrammingError: pass cls.python_type = register_composite( db_type, connection.cursor().cursor, globally=True ).type _logger.warn("registering composite") def adapt_composite(composite): return AsIs(...get sql...) register_adapter(Foo, adapt_composite) class FooField(models.Field, metaclass=FieldMeta): def db_type(self, connection): return "foo" This works fine in these situations: Database already knows about type foo Database does not know about type foo The problem is that pytest-django seems to run these init methods before creating the test database, meaning that the test database does not have the required type. I can fix this on individual tests by calling FooField.register_type() in the setUpClass method of the test, but this is not ideal, since it should always be present. I tried overriding the django_db_setup fixture to look like this: @pytest.fixture(scope="session") def django_db_setup( request, django_test_environment: None, django_db_blocker, django_db_use_migrations: bool, django_db_keepdb: bool, django_db_createdb: bool, django_db_modify_db_settings: None, ) -> None: """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True with django_db_blocker.unblock(): db_cfg … -
User() got an unexpected keyword argument 'tutors_data'
How can I solve this error User() got an unexpected keyword argument 'tutors_data' in Django rest-framework and djoser? I found some solutions but couldn't help me models.py # Tutoruser Model class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor_user') full_name = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255) phone_number = models.CharField(max_length=14, blank=True) profile_img = models.ImageField(upload_to='images/tutor/profile-img', blank=True) description = models.TextField(blank=True) serializers.py class TutorUserSerializer(serializers.ModelSerializer): class Meta: model = TutorUser fields = [ 'id', 'full_name', 'phone_number', 'description', 'profile_img', ] class UserCreateSerializer(UserCreateSerializer): tutors_data = TutorUserSerializer() class Meta(UserCreateSerializer.Meta): model = User fields = ['id', 'email', 'is_tutor', 'password', 'tutors_data'] def create(self, validated_data): #create user tutor_user_data = validated_data.pop('tutors_data') user = User.objects.create( email = validated_data['email'], password = validated_data['password'], is_tutor = validated_data['is_tutor'], ) if user.is_tutor: for tutor_data in tutor_user_data: TutorUser.objects.create( tutor_user = user, **tutor_data, ) return user if I change tutors_data = TutorUserSerializer() to tutor_user = TutorUserSerializer() it works but gives me another error Cannot assign "OrderedDict()...: "..." must be a "..." instance.... and is it possible to get only one field on UserCreateSerializer from TutorUserSerializer? Thanks in advance. -
Should I be adding the Django migration files in the .dockerignore /.gitignore file?
This is probably a duplicate of this question. My question is how should I approach this when working in a docker environment so for my project I have a docker-compose.yml and docker-compose-deploy.yml for my production environment and obviously migration files are generated only in the docker images and aren't included in my version control system. How should I approach this? should I stop using Docker as my development environment and go for something like virtual environments or even machines? -
Multiple authors for blogpost
I am a bit stuck on trying to solve this So I have a webapp, and decided to add a blog section using wagtail. This means I have quite a few pages and models already preexisting, that I do not want to touch, as well as some users already. I am aware of the owner field in the base Page class, but can't see a way to extend to into a m2m field. To achieve this, I have created a custom user model at users.User. For blog community purposes, I wanted to add the option of picing an avatar and setting a biography, so I added those two (avatar and bio are newly added fields) class User(AbstractUser): name = models.CharField(_("Name of User as displayed to other users"), blank=True, max_length=255) company = models.ForeignKey(Company, null=True, on_delete=models.CASCADE) job_title = models.CharField(max_length=100) avatar = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+') bio = models.TextField(max_length=300, blank=True) Then I have a classic Blogpost page, with title, body streamfield etc... However, I am trying to replace something where you can add multiple post editors, and each of them has edit rights. So I tried something like this: First an orderable since I need many2many: class PostAuthorsOrderable(Orderable): page = ParentalKey("blog.BlogPost", related_name="post_authors") … -
How do I get local server running - here with language error message?
I have a Django app (with a postgres database) running in a virtual environment. Everything has been working on my localhost until a few days ago when I got an error saying my SSL certificate had expired (localhost:8000). Today, when I tried the python manage.py runserver command I got an error saying psycopg2 was not installed. I know it was because I have been using this app for the last nine months! Anyway, I reinstalled psycopg2 and tried the runserver command again. This time I got the following error message: $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\coding\registrations\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "E:\coding\registrations\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "E:\coding\registrations\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "E:\coding\registrations\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "E:\coding\registrations\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "E:\coding\registrations\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, … -
Problem with invitation to event in my project
i have a following problem... I create "event" in my project but i can not invite friends to this "event". I don't get how to identify the "event" correctly to make a invite request to friend. models.py class Event(models.Model): title = models.CharField(max_length=200, blank=False, null=False) creator = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name='creator') participators = models.ManyToManyField(Profile, blank=True) description = models.TextField(blank=True) start = models.CharField(max_length=5) finish = models.CharField(max_length=5) event_date = models.CharField(max_length=50) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-timestamp', ) def __str__(self): return f"Event: {self.title} by {self.creator}. \ Date: {self.event_date}. From:{self.start} to {self.finish}" def get_sum_participators(self): return self.participators.count() class EventInviteRequest(models.Model): from_event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='from_event', null=True) to_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='to_profile', null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"From {self.from_event} to {self.to_profile}" This is a function i'm trying to use, but it sends request to 'event' creator. def from_event_to_user_invite_request(request, id): event = Event.objects.get(id=id) to_profile = Profile.objects.get(id=id) event_invite, created = EventInviteRequest.objects.get_or_create( request, from_event=event, to_profile=to_profile) return redirect('events:event_page', event.id) Could you give me some tips how to fix the problem Thank you -
error when saving multiple (onetoonefield) forms in django views.py. pls, Need correct working view or suggestion
models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) mobileno = models.IntegerField(blank=True, null=True) is_customer = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class VendorDetails(models.Model): vendoruser = models.OneToOneField(CustomUser, on_delete=models.CASCADE) aadhar_number = models.CharField(max_length=200) pan_number = models.CharField(max_length=200) store_name = models.CharField(max_length=200) brand_name = models.CharField(max_length=200) mail_id = models.EmailField(max_length=200) contact_no = models.IntegerField(blank=True, null=True) gst_number = models.CharField(max_length=100) acct_number = models.CharField(max_length=100) ifsc_code = models.CharField(max_length=100) fb_account = models.CharField(max_length=100,blank=True, null=True) insta_account = models.CharField(max_length=100,blank=True, null=True) website = models.CharField(max_length=100,blank=True, null=True) door_no = models.CharField(max_length=100,blank=True, null=True) street_name = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) def __str__(self): return self.mail_id forms.py class UserCreationForm(UserCreationForm): """ A Custom form for creating new users. """ class Meta: model = CustomUser fields = ['email','first_name','last_name','mobileno'] """ For Vendor users forms""" class VendorAdminDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['aadhar_number', 'pan_number'] class VendorStoreDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['store_name', 'brand_name', 'mail_id', 'contact_no', 'gst_number'] class VendorBankDetailsForm(forms.ModelForm): class Meta: model = VendorDetails fields = ['acct_number', 'ifsc_code'] class VendorSocialMediaDetailsForm(forms.ModelForm): fb_account = forms.CharField(required=False) insta_account = forms.CharField(required=False) website = forms.CharField(required=False) class Meta: model = VendorDetails fields = ['fb_account', 'insta_account', 'website'] class VendorContactDetailsForm(forms.ModelForm): door_no = forms.CharField(required=False) street_name = forms.CharField(required=False) pincode = forms.IntegerField(required=False) class Meta: model = VendorDetails … -
Can anybody help me to find out why the db values are not showing up in the admin form?
I am a newbie so please help me in resolving this issue. I have a DurationField in my models.py. I have overridden the widget attribute of the field in admin.py. I need duration field as a choice field without changing the DurationField in models.py file. So, I have overridden that field with choice field widget so it displays as dropdown limited to five days. Coming to the issue now. When I click on save in admin the data is saved to the database my widget is not getting updated with the values saved in database. Posting the images and code for reference. Im stuck with this issue for more than 5 days. any help would be appreciated class ManagedAccountAdmin(admin.ModelAdmin): form = ManagedUserAdminForm model = ManagedAccount exclude = ('customer', 'created_by', 'modified_by', 'verification_code') formfield_overrides = { models.DurationField: {"widget": forms.Select(choices=((str(i)+" day",str(i)+" Day") if i==1 else ((str(i)+" days", str(i)+" Days")) for i in range(1,6))) }} def get_form(self, request, obj=None, **kwargs): form = super(ManagedAccountAdmin, self).get_form(request, obj, **kwargs) for field in form.base_fields.keys(): form.base_fields[field].widget.can_change_related = False form.base_fields[field].widget.can_add_related = False return form def save_model(self, request, obj, form, change): obj.program = form.cleaned_data.get('program') obj.managed_by = form.cleaned_data.get('managed_by') obj.created_by = request.user obj.duration_in_days = form.cleaned_data.get('duration_in_days') print("duration in save model",obj.duration_in_days) if change: obj.modified_by = … -
Can't find a guide about how to setup Django+Auth0+Graphene
I've been trying to setup my graphene API with Auth0 but I can't make it work. I found similar questions like this: Auth0 - Django and Graphene but yet unanswered. I'd like to get some guidance about how to setup this 3 things together. Maybe pointing me out with a link? -
Headless Django-Oscar - Correct middleware/session setup
I am a bit confused about the correct setup for a headless middleware/session setup using django-oscar-api. The documentation for the latter is telling me to use oscarapi.middleware.ApiBasketMiddleWare if I want/need to mix "normal" django-oscar and django-oscar-api. The same documentation tells me to use oscarapi.middleware.HeaderSessionMiddleware if django-oscar is being communicated from an "external client using Session-Id headers". In my case I am not using Session-Id headers, but only communicate with oscar via api calls. What would be the correct setup/path for my case? Can I just use the oscarapi.middleware.ApiBasketMiddleWare and just use api calls? How will it handle anonymous baskets and merging of baskets after user login(jwt)? -
I am trying to post on to a manytomany relationship field via a model where the model with the manytomany relationship is nested
When I try to post by using the get_or_create, and writable nested serializers, I can do that but the fields with many to many relationships somehow even though they are an array of ids when posted, I get the error: TypeError at /Albums/ Field 'id' expected a number but got [<Order: 2B>]. the structure: Tracks have Orders (where orders is a manytomany field of the class Orders) Album has Tracks I can post in tracks and mention the orders as an array "orders":[2,4] When I try to post in the Album together with the Tracks, I can post the tracks with the fields that ARE NOT manytomany fields, but if I try with the manytomany fields I get the type error mentioned above. 2B is the value of another field and not the id of the Order, is the value of the field returned in the def __str__(self) -> str: return (self.name) -
How to order django models according decimal points
I have created model where I am ordering by feature_req_no Feature_req_no is in the form of: 1, 1.1, 1.1.1, 2, 2.1, 10, 10.1, When I try to do Ordering using feature_req_no the ordering is as follows: 1, 10, 10.1, 1.1, 1.1.1, 2, 2.1 Expected output: 1, 1.1, 1.1.1, 2, 2.1, 10, 10.1 -
use toggle to switch django boolean field
I have a bootstrap toggle and I would like every time I switch to activate or deactivate a boolean field within my model. html <div class="form-check form-switch"> <input class="form-check-input" {% if slide.attivo == True %} checked {% endif %} type="checkbox"> </div> model class Slide(models.Model): attivo = models.BooleanField(default=True) -
Django does not open the form for taking inputs instead returns directly the final page mentioned in views.py
[Here is the views.py instead of reading inputs from the user after opening the form it jumps directly to index.html line and returns it[][1]1 -
Filter field based on tenant on Django default administration template
Good afternoon, given 2 django models: class Person(TenantAwareModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) full_name = models.CharField(max_length=200) personal_car= models.ForeignKey(Car, on_delete=models.SET_NULL , null=True, blank=True) ... def __str__(self): return self.full_name class Car(TenantAwareModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) car_name = models.CharField(max_length=200) ... def __str__(self): return self.car_name I simply want , working on Template and Form in administration register, that WHEN I 'am going to edit an "Person" object, I can only SELECT, from the "personal_car" dropdown, the "Car" that is of the Tenant of that Person. Cause with default tenant implementation I can select ALSO Car that is of another Tenant... and this is wrong. Actual ""admin.py"" settings, I would reach this goal only work on this file: class PersonAdminForm(forms.ModelForm): class Meta: model = Person fields = "__all__" def __init__(self, *args, **kwargs): super(PersonAdminForm, self).__init__(*args, **kwargs) self.fields['personal_car'].queryset = Car.objects.filter() #this empty filter return all personal_car objects... also from other tenants.. can't filter here... class PersonDedicatedTemplate(admin.ModelAdmin): list_display = ('tenant','full_name','personal_car') list_filter = ('tenant') full_path=None form=PersonAdminForm super_admin_site.register(Person,PersonDedicatedTemplate) thank you ! -
Is context processor only wawy to access global variable in in Django?
I am creating a website and i have to access golbal variables for the footer section and i found the context processor one way to access global variable and my question is that Is context processors one and only way to access global variable in django ? -
Django model order and duplicate
I have two models with a manytomany relationship. class Exercise(models.Model): BODYPART_CHOICES = ( ('Abs', 'Abs'), ('Ankle', 'Ankle'), ('Back', 'Back'), ('Biceps', 'Biceps'), ('Cervical', 'Cervical'), ('Chest', 'Chest'), ('Combo', 'Combo'), ('Forearms', 'Forearms'), ('Full Body', 'Full Body'), ('Hip', 'Hip'), ('Knee', 'Knee'), ('Legs', 'Legs'), ('Lower Back', 'Lower Back'), ('Lumbar', 'Lumbar'), ('Neck', 'Neck'), ('Shoulders', 'Shoulders'), ('Thoracic', 'Thoracic'), ('Triceps', 'Triceps'), ('Wrist', 'Wrist'), ) CATEGORY_CHOICES = ( ('Cardio', 'Cardio'), ('Stability', 'Stability'), ('Flexibility', 'Flexibility'), ('Hotel', 'Hotel'), ('Pilates', 'Pilates'), ('Power', 'Power'), ('Strength', 'Strength'), ('Yoga', 'Yoga'), ('Goals & More', 'Goals & More'), ('Activities', 'Activities'), ('Rehabilitation', 'Rehabilitation'), ('Myofascial', 'Myofascial') ) EQUIPMENT_CHOICES = ( ('Airex', 'Airex'), ('BOSU', 'BOSU'), ('Barbell', 'Barbell'), ('Battle Rope', 'BattleRope'), ('Bodyweight', 'Bodyweight'),('Bands', 'Bands'), ('Cables', 'Cables'), ('Cones', 'Cones'), ('Dumbbells', 'Dumbbells'), ('Dyna Disk', 'Dyna Disk'), ('Foam Roller', 'Foam Roller'), ('Kettlebells', 'Kettlebells'), ('Leg Weights', 'Leg Weights'), ('Machine', 'Machine'), ('Medicine Ball', 'Medicine Ball'), ('Plate', 'Plate'), ('Power Wheel', 'Power Wheel'), ('Ring', 'Ring'), ('Sandbag', 'Sandbag'), ('Stick', 'Stick'), ('Strap', 'Strap'), ('Suspension', 'Suspension'), ('Swiss Ball', 'Swiss Ball'), ('Theraball', 'Theraball'), ('Towel', 'Towel'), ('Tubbing', 'Tubbing'), ('Wobble Board', 'Wobble Board'), ) name = models.CharField(max_length=200) photograph = models.ImageField(null=True, upload_to=exercise_image_file_path) body_part = models.CharField(max_length=50, choices=BODYPART_CHOICES) equipment = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES) equipment_two = models.CharField(max_length=200, choices=EQUIPMENT_CHOICES, blank=True, null=True) category = models.CharField(max_length=100, choices=CATEGORY_CHOICES) workout_tip = models.TextField(max_length=3000, blank=True) cmf_url = models.URLField(max_length=400, blank=True) # exercise_id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def … -
Django: filter results using Primary Key
In my data.html I need both information from the File Model and the Week Model. Using colors = File.objects.filter(user=request.user.userdata).filter(pk=pk) I can get all the information that I need of the file with the right PK when I open the html without problems, but data = list(Week.objects.filter(user=request.user.userdata).filter(pk=pk).values_list())[2:] is giving me back just a blank variable. How can I access all the values in my field based un pk for te data variable? Thank you MODEL class File(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) docfile = models.FileField(upload_to=path) color = models.CharField(max_length=250) class Week(models.Model): user = models.ForeignKey(UserData, on_delete=models.CASCADE) file_doc = models.OneToOneField(File, on_delete=models.CASCADE) monday = models.PositiveIntegerField(null=True) tuesday = models.PositiveIntegerField(null=True) wednesday = models.PositiveIntegerField(null=True) thursday = models.PositiveIntegerField(null=True) friday = models.PositiveIntegerField(null=True) saturday = models.PositiveIntegerField(null=True) sunday = models.PositiveIntegerField(null=True) VIEW def week_data(request, pk): colors = File.objects.filter(user=request.user.userdata).filter(pk=pk) labels = [f.name for f in Week._meta.get_fields()] data = list(Week.objects.filter(user=request.user.userdata).filter(pk=pk).values_list())[2:] context = { 'labels': labels, 'data': data, 'colors': colors } return render(request, 'data.html', context) HTML <!DOCTYPE html> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script> <canvas id="doughnut-chart" width="800" height="450"></canvas> new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels: [{% for label in labels %} '{{ label|capfirst }}', {% endfor %}], datasets: [ { label: "Population (millions)", backgroundColor: [{% for color in colors %} '{{ color }}', {% endfor %}], data: [{% for value … -
overwrite save django method
I need to override Django's method save so when the purchase is made by a certain cpf, it is saved with "Approved" status. Can someone help me? Follow the models.py class Purchases(TimeStampedModel): APROVADO = "AP" EM_VALIDACAO = "VA" STATUS_CHOICHES = ( (APROVADO, "Aprovado"), (EM_VALIDACAO, "Em validação"), ) values = models.DecimalField(decimal_places=2, max_digits=10, default=0) cpf = BRCPFField("CPF") status = models.CharField(max_length=20, choices=STATUS_CHOICHES, default=EM_VALIDACAO) -
Why CORS headers does not concern http requests from the browser
I want to understand in depth CORS. If we consider the definition of https://developer.mozilla.org/: Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. So my question is quite simple : Its normal if CORS policy is triggered if we use fetch() from a website hosted on a separate server (separate ip). But the question is, why when we make a HTTP request from a browser to a particular website the CORS policy is not triggered ,knowing that the source of the request comes from a different ip from that of the server hosting the website ? Thanks in advance -
Facing errors while using Django post office setup for sending mails
Issue Error is due to attachments folder(post_office_attachments) not being able to generate on linux server. Error TypeError at /dev/generate_request/ Object of type 'TypeError' is not JSON serializable Request Method: POST Django Version: 2.2.3 Exception Type: TypeError Exception Value: Object of type 'TypeError' is not JSON serializable Exception Location: /usr/lib/python3.6/json/encoder.py in default, line 180 Python Executable: /usr/bin/python3 Related Code try: html = template.render(context) email_message = EmailMultiAlternatives(subject, html, from_email, [to_email]) email_message.attach_alternative(html, 'text/html') template.attach_related(email_message) email_message.send() return "success" except Exception as e: return "Error: unable to send email due to" + e Which piece of code is causing the error template.attach_related(email_message) -
Django: Changing the model field in the database when the button is clicked
I am creating a web application for a pizzeria. You need to add an action: when you click on the "Order delivered" button, the order status should change to "Order completed". How to do it? It is necessary that when you click on the button, the status field in the order changes models.py: from django.db import models from django.db.models.fields import DecimalField, NullBooleanField import decimal from django.utils import timezone from django.db.models.signals import pre_save from django.dispatch import receiver class Product(models.Model): title = models.CharField(verbose_name='Название продукции', max_length=100) count = models.DecimalField(verbose_name='Кол-во на складе', max_digits = 10, decimal_places=4) price = models.DecimalField(verbose_name='Цена', max_digits = 10, decimal_places=4) date = models.DateField(verbose_name='Дата обновления', default=timezone.now()) def __str__(self): return self.title class Meta(): verbose_name = 'Продукты' verbose_name_plural = 'Продукция' class Technology_card(models.Model): title = models.TextField(verbose_name='Название ТК',default='Технологическая карта для пиццы') pizza_box = models.DecimalField(verbose_name='Коробки пиццы',max_digits = 10, decimal_places=4, default=1) napkins = models.DecimalField(verbose_name='Салфетки',max_digits = 10, decimal_places=4, default=6) dough = models.DecimalField(verbose_name='Тесто',max_digits = 10, decimal_places=4, default=0) flour = models.DecimalField(verbose_name='Мука',max_digits = 10, decimal_places=4, default=0) tomato_sauce = models.DecimalField(verbose_name='Соус томатный',max_digits = 10, decimal_places=4, default=0) cream_sauce = models.DecimalField(verbose_name='Соус сливочный', max_digits = 10, decimal_places=4, default=0) olive_oil = models.DecimalField(verbose_name='Оливковое масло', max_digits = 10, decimal_places=4, default=0) mozzarella_cheese = models.DecimalField(verbose_name='Сыр Моцарелла', max_digits = 10, decimal_places=4, default=0) parmesan_cheese = models.DecimalField(verbose_name='Сыр Пармезан', max_digits = 10, decimal_places=4, default=0) dor_blue_cheese = …