Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF calling ModelSerializer with model object as dict throws 'object has no attribute RelatedManager'
I'm trying to call a ModelSerializer named RegistrationSummarySerializer with my model object. When I'm trying to insert the object directly it throws Invalid data. Expected a dictionary, but got Registration. When I create a dict from my object, it gets validated successfully but now the Serializer throws AttributeError: 'collections.OrderedDict' object has no attribute 'participantgroup_set' as obj is not the model object but a dict, as obj is now an OrderedDict and not a Registration. Does someone have tips how to solve that? registration = get_object_or_404(Registration, pk=data['id']) registration_dict = { 'id': registration.id, 'scout_organisation': registration.scout_organisation.name, 'responsible_persons': [i.username for i in registration.responsible_persons.all()], 'event': registration.event.name, 'free_text': registration.free_text, 'is_confirmed': registration.is_confirmed, 'is_accepted': registration.is_accepted } serializer = RegistrationSummarySerializer(data=registration_dict) valid = serializer.is_valid(raise_exception=True) print('valid', valid) registration_data = serializer.data print('serializer data ', registration_data) class RegistrationSummarySerializer(serializers.ModelSerializer): total_participants = serializers.SerializerMethodField('get_total_participants') responsible_persons = serializers.SlugRelatedField( many=True, read_only=False, queryset=User.objects.all(), slug_field='username' ) scout_organisation = serializers.SlugRelatedField( many=False, read_only=False, queryset=ScoutHierarchy.objects.all(), slug_field='name' ) event = serializers.SlugRelatedField( many=False, read_only=False, queryset=Event.objects.all(), slug_field='name' ) class Meta: model = Registration fields = ( 'total_participants', ) def get_total_participants(self, obj): num_group = obj.participantgroup_set.aggregate(num=Coalesce(Sum('number_of_persons'), 0))['num'] num_pers = obj.participantpersonal_set.count() result = num_group + num_pers self.total_participants = result return result -
How to pass form data to stripe webhook in Django so it emails them to me once payment's done
I'm trying to get my Django app to email order details to me (name, shipping address, etc.) once my Stripe webhook confirms payment but have no idea how to pass on that data. To webhook? (checkout function redirects to a Stripe server checkout) buy.html <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="nume">Nume si Prenume</label> <input type="text" name="nume" class="form-control" id="nume" required> <div class="form-group"> <label for="strada">Strada</label> <input type="text" name="strada" class="form-control" id="strada" required> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" id="email" required> </div> <div class="form-group"> <label for="telefon">Telefon</label> <input type="text" name="telefon" class="form-control" id="telefon" required> </div> <div class="form-group"> <label for="cantitate">cantitate</label> <input type="number" id="cantitate" name="cantitate" min="1" max="8" required> </div> <button type="submit" class="btn btn-primary">Send order</button> <div class="jumbotron"> <h1 class="display-3">The Product</h1> <p class="lead">Purchase The Product for only $99.</p> <a href="#" id="buy_now_btn" class="btn btn-primary">Buy Now</a> </div> <script src="https://js.stripe.com/v3/"></script> <script> const buy_now_button = document.querySelector('#buy_now_btn') buy_now_button.addEventListener('click', event => { fetch('/checkout/') .then((result) => { return result.json() }) .then((data) => { var stripe = Stripe(data.stripe_public_key); stripe.redirectToCheckout({ sessionId: data.session_id }).then(function (result) { }); }) }) </script> I already have a working email function set up and can call it with sendemail('sample@outlook.com', 'subject', email_content) And also got how to extract the data from the .html form. Just don't know how to send email … -
Drop down list for different products
Drop down list for different products in page. my html page {% for deal in Deals %} <div id="innermain"> <div id="dealsdesc"> <div id="desc"> <div class="deals_fav flex-row"> <span class="smallgreytext">{{ deal.source }}</span><br/> {% if request.session.name %} <span class="far fa-heart dropbtnDeals" onclick="myFunctionDeals()" data-original-title="Click" data-toggle="tooltip" style="position: relative; left: 154px; color: #01ABAA; cursor: pointer;"></span> <div class="dropdown-contentDeals" id="myDropdownDeals"> <a href="#" data-dismiss="modal" data-target="#myModal_create" data-toggle="modal">Create new list</a> <a href="/wishlist_deal/{{deal.id}}">Deals</a> </div> {% endif %} </div> {% if deal.type_of_product == 'D' %} <div class="price_presentation flex-row"> <span><strike style="color:lightgray;">${{ deal.price }}</strike></span><br/> <span class="dealsale_price">${{ deal.sale_price }}<span class="pipe">|</span></span> <span class="deal_rebate">{{ deal.rebate }}%</span><br/> </div> {% endif %} {% endfor %} In views.py def wishlist_deal(request, id): data_deals = master_table.objects.filter(type_of_product='D', id=id) if data_deals: for i in data_deals: wishqury = Wishlist_cl.objects.filter(wished_item=i.product_name).first() if wishqury is not None: messages.error(request, "Already this product exists in the selected wish list.") else: Wishlist_cl.objects.create(wished_item=i.product_name, email=email, price=i.price, sale_price=i.sale_price, image=i.img_url, type_of_product=i.type_of_product, adv_id=i.id, name="Deals") messages.success(request, "Added successfully") return redirect(request.META.get('HTTP_REFERER')) return redirect(request.META.get('HTTP_REFERER')) For list of products it has drop down list should be prompted in for different products after clciking fav icon. Please help me ton achieve this thank you. -
how can i transilate english to arabic language using checkbox toggle button
i am working in python-Django.I need to convert english to arabic language by using checkbox <input type="checkbox" id="che" style="margin-top: 30px;padding-top: 15px;"> #che { -webkit-appearance: none; position: relative; width: 80px; height: 40px; background-image: url(../images/us.png); background-size: cover; border-radius: 50px; outline: none; transition: background-image .90s; box-shadow: 0px 2px 5px 1px gray; } #che:before { content: ""; position: absolute; top: 0; left: 0; height: 40px; width: 40px; background-color: navy; border-radius: 50px; transition: all .9s; background-color: #004d66; } #che:checked { background-image: url(../images/kwd.png); transition: background-image .90s; } #che:checked:before { transform: translate(100%); transition: all .9s; background-color: #ECF0F3; } this is the image of my checkbox-toggle button -
Is it feasible to create an extra field that indicates the number of related entries to be searched in another table?
My goal is to get the best compromise between space and performance for the situation. I have two similar situations but they differ slightly. Situation 1: Suppose I have two tables for a classic situation: 'survey' and 'question'. class Survey(models.Model): survey_owner_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) survey_title = models.CharField(max_length=70, blank=False, null=False) class Question(models.Model): survey_id = models.ForeignKey(Survey, on_delete=models.CASCADE, blank=True) question = models.TextField(max_length=150, null=False, blank=True) One survey can have up to 10 questions, but may also have fewer, but must have at least 5. I am pondering whether it would be feasible to add another field to the 'survey' table that indicates the number of questions that this survey has, and therefore, the number of rows that will need to be queried in the 'question' table, so that not the entire table needs to be queried from start to end, each time the survey is pulled up. In this case, a survey will likely not be pulled up as frequently. For example: class Survey(models.Model): survey_owner_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) survey_title = models.CharField(max_length=70, blank=False, null=False) question_amount = models.IntegerField(blank=False, null=False) Situation 2: Suppose a similar situation as in the survey-question example, but in this case, the survey can only have up to 4 questions (but may also … -
Conditional formatting Bootstrap cards in Django
I am building a Django template using Bootstrap 4. I'm looking at formatting the badges based on a categorical field from my Project model (for example, if category is "Complete", I'd like the badge to be green). So far, I've created this long if / elif statement with a lot of repetition but as I'm looking at implementing something with more categories, I feel like I'm missing out on a smarter / cleaner way to do this. Below is my Django template (which currently leverages default Bootstrap colors / formats). {% if project.status == "complete" %} <span class="badge rounded-pill bg-success text-light">{{ project.status|title }}</span> {% elif project.status == "review" %} <span class="badge rounded-pill bg-active text-light">{{ project.status|title }}</span> {% elif project.status == "autopilot" %} <span class="badge rounded-pill bg-light text-dark">{{ project.status|title }}</span> {% elif project.status == "issues" %} <span class="badge rounded-pill bg-warning text-dark">{{ project.status|title }}</span> {% elif project.status == "submitted" %} <span class="badge rounded-pill bg-dark text-light">{{ project.status|title }}</span> {% elif project.status == "draft" %} <span class="badge rounded-pill bg-info text-light">{{ project.status|title }}</span> {% endif %} Things that I've been thinking about but there must be something simpler or more straightforward: Create a new model attribute for formatting only (possibly derived from the categorical attribute). … -
I am not able to import of icons in django from font awesome. help me about it
I have copy the icon from font-awesome to my html file and bootstrap-CDN for font-awesome to CSS file but I am not able to show the icons. Is there any suggestion for me to show the icon -
Django tests response object zipped
So I have SearchResultView(listview) with a method get_context_data were i zip publications and images. For easy looping in the template: context['publications'] = zip(context['publications'], cover_images) Now I am testing and I have the following: def setUp(self): user = User.objects.create_superuser(username='admin', password='12345', email='') user.save() Publication.objects.create(title='eindhoven') Publication.objects.create(title='لحضور المؤتمر الدولي العاشر ليونيكود') Publication.objects.create(title='مزامير') #mazamir And this: def test_search_results(self): client = Client('127.0.0.1') response = client.login(username='admin', password='12345') response = client.get('/publication/show/', {'q': 'eindhoven'}) Now I need to unpack zip that is in the response. I tried the following: list(zip(*response.context['publications'])) list(zip(*response.context[-1]['publications'])) But they are returning an empty list. Anyone any ideas? -
BFF architecture with Python
I dont know if SO is the better place to discuss about that, but i need some opinions and suggestions about how to do a system using BFF architecture. I'm asking that, because at my internship i will need to refactor a system that was written with Golang and microsservices architecture with 4 services decoupled, and a BFF with Node. And now this system it will work with a single API and the BFF will be written in Python. Gimme some views about architecture and tools and how can i implement this. * I was thinking to implement that with Django, but i have never use this. Thanks for your help. -
How to save URL to a Django ImageField
I have Django model with Image field, but sometimes I don't need to actually upload file and store path to it, but I need to store only path. Especially url. I mean, I have web client, that receives both foreign urls like sun1-17.userapi.com and url of my own server, so sometimes I don't need to download but need to store url. Is it possible, to store url in ImageField, or I need to make CharField and save files via python? If its impossible, how do I save file in python3, having one, sent me via multipart? -
Azure Django App has SECRET_KEY Exception
I deployed my django web app on azure using GitHub, but the error I'm getting is: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My settings.py file is 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__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = False TEMPLATE_DEBUG = DEBUG ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), "C:/Users/ande/Documents/FC_Database/FC_Database/frontend/templates/frontend/index.html" ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'SLAR', 'import_export', 'rest_framework', 'frontend' ] 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', ] ROOT_URLCONF = 'FC_Database.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 = 'FC_Database.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('NAME'), 'USER': os.getenv('USER'), 'PASSWORD': os.getenv('PASSWORD'), 'PORT': 3306, 'HOST': os.getenv('HOST') } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' … -
convert-engine issue with saving any thumbnail
So I have a model like this from django.db import models from sorl.thumbnail import get_thumbnail class Upload(BaseModel): @staticmethod def upload_path_handler(instance, filename): return f'boxes/{instance.box.id}/uploads/{filename}' @staticmethod def thumbnail_path_handler(instance, filename): return f'boxes/{instance.box.id}/thumbnails/{filename}' def save(self, *args, **kwargs): if self._state.adding: # we cache the file size and store # it into the database to improve performance # we cannot edit the object's file so we don't # bother to modify the file size on updates self.size = self.file.size super(Upload, self).save(*args, **kwargs) thumbnail = get_thumbnail(self.file, '1280x720', crop='center') # sorl is not saving the thumbnails for non-image files return self.thumbnail.save(thumbnail.name, ContentFile(thumbnail.read()), True) super(Upload, self).save(*args, **kwargs) objects = api_managers.UploadManager() size = models.PositiveBigIntegerField() name = models.CharField(max_length=100, default='untitled', validators=[MinLengthValidator(2)]) channel = models.ForeignKey('api_backend.Channel', on_delete=models.CASCADE, editable=False) box = models.ForeignKey('api_backend.Box', on_delete=models.CASCADE, editable=False) owner = models.ForeignKey('api_backend.User', on_delete=models.CASCADE, editable=False) thumbnail = models.ImageField(max_length=512, upload_to=thumbnail_path_handler.__func__, null=True, blank=True) file = models.FileField(max_length=512, upload_to=upload_path_handler.__func__) REQUIRED_FIELDS = [file, owner] the file field can be literally any file, and I want sorl-thumbnail to make a thumbnail for the same and save it into the thumbnail field. I am on windows and am using ImageMagick. [python version- 32 bits] this is the binary distribution I installed. https://imagemagick.org/script/download.php ImageMagick-7.0.10-61-Q16-x86-dll.exe Win32 dynamic at 16 bits-per-pixel component settings.py THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.convert_engine.Engine' However, whenever an upload-model is … -
how to Insert or update if already exists use Django and SQLITE
I want to insert data in SQLite use Django, I want that if data is in Database exist, new record will only update my db, The next is if not exist will insert new. class User(models.Model): email= models.CharField(max_length=200, unique=True) name= models.CharField(max_length=200) salary = IntegerField(null=True) I tried to use try: # update codes except: # Insert codes but failed, all times it insert and fail and it give me error of that email is unique, without update existing record. What can I do? -
Django difficulty ORM annotate/aggregate query suggesion
I'm trying to come up with code for a fairly difficult query (for me at least). I'm not sure it's possible to do in the ORM. If not, dropping into SQL is fine, but I can't quite wrap my head around that either. Say I have these two models: class BlogArticle(models.Model): published_date = models.DateField() sentiment_score = models.DecimalField() Publication(models.Model): articles = models.ForeignKey() In the view, I want to accept Publication ids from query params. I then want to end up with a dictionary with a key for each publication, containing a value of a list of key-value pairs. The key will be a day (using TruncDay('publication_date')), and the value will be the average sentiment_score for that day. For example: { 'Some publication': [ '2021 01 31': 0.23, '2021 01 30': 0.31, ... ], 'Another publication': ... } The closest I've gotten is this: ids = request.GET.getlist('id', []) blog_articles = BlogArticle.objects.filter(publication__id__in=ids) blog_articles = self.perform_other_blog_filters(blog_articles) return blog_articles .annotate(day=TruncDay('publish_date')) .order_by('day').values('day').annotate(Avg('sentiment_score')) This doesn't work, because it will give the average per day for blog articles from all Publication ids passed in, whereas I need them separated by Publication. The kicker here is I need to start from a list of blog articles, not publications, because … -
Redis Django - how to rename all cache keys according to a specific pattern In python (django)
I have multiple keys in redis such as key_1, key_2, key_3 and so on. I wanted to append "s" after each keys prefix, (here key prefix is "key") so it will become keys_1, keys_2, keys_3 I am using django cache from django.core.cache import cache is there any functionality that can rename keys based on pattern or is there anything in redis-cli to solve this problem. Please help. -
why cron job is not showing the output in ubuntu?
I've setup corn job using django. the logs is showing that job is scheduled but it is not working. crontab -e: */1 * * * * /home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/log/file.log # django-cronjobs for iStudyMain Django setup: settings.py: INSTALLED_APPS = [ .. 'django_crontab', ] CRONJOBS = [ ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log'), ] CRONTAB_COMMAND_SUFFIX = '2>&1' cron.py: from .models import * def sendNotification(): # notificationList = dateBasedNotificaton.objects.filter(scheduleDate = date.today()) obj = test(name="working") obj.save() obj.refresh_from_db() # print("sending notifications/messages") return "success" (env) karanyogi@karanyogi:~/E-Mango/Jan27New/eMango$ python manage.py crontab show Currently active jobs in crontab: 60a198cfdc0c719d07735a708d42bafb -> ('*/1 * * * *', 'allActivitiesApp.cron.sendNotification', '>> /path/to/log/file.log') also when I check the logs of ubuntu it is showing something is running: **** CRON[56232]: ***** CMD (/home/karanyogi/E-Mango/env/bin/python /home/karanyogi/E-Mango/Jan27New/eMango/manage.py crontab run 60a198cfdc0c719d07735a708d42bafb >> /path/to/> -
Istio 503 Service Unavailable (Django App)
I am trying to implement Istio on a Django project. The projects work fine until Istio sidecars are injected to the pods, and I am unable to access the app inside Istio. Deployments.yaml apiVersion: apps/v1 kind: Deployment metadata: name: api-manager labels: app: api-manager spec: replicas: 1 selector: matchLabels: app: api-manager template: metadata: labels: app: api-manager spec: containers: - name: api-manager image: api-manager:v1 command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] imagePullPolicy: Always ports: - containerPort: 8000 Service.yaml apiVersion: v1 kind: Service metadata: name: api-manager-service spec: selector: app: api-manager type: LoadBalancer ports: - protocol: TCP name: http port: 8000 targetPort: 8000 Istio Gateway and Virtual Service apiVersion: networking.istio.io/v1alpha3 kind: Gateway metadata: name: api-manager-gateway spec: selector: istio: ingressgateway # use istio default controller servers: - port: number: 90 name: http protocol: HTTP hosts: - "*" --- apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: api-manager-vs spec: hosts: - "*" gateways: - api-manager-gateway http: - route: - destination: host: api-manager-service port: number: 8000 I use http://localhost:90/ to access the app inside that returns 503 Service Unavailable. The Application is accessible and works fine inside kubernetes with out Istio. I also tried disabling tls to see if that was causing the issue, but that did not work. -
django.db.utils.IntegrityError: duplicate key value violates unique constraint “my_model_id_pkey”
Stack: Django2.2.5/Postrgesql 10/Docker I try to run a test where I create User and related Customers models based on csv file 5 Users are creating with Django data migration as initial data When I run my test, I got an error but I do not understand why ... pk (user_id)=(6) already exist But this PK should not already exist I DROP and CREATE DATABASE but always the same issue def test_create_customers(self): with open('./import/randomuser.csv', newline='') as csvfile: has_header = csv.Sniffer().has_header(csvfile.read(1024)) csvfile.seek(0) spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') if has_header: next(spamreader) for row in spamreader: user = User.objects.create( password = row[0], is_superuser = strtobool(row[2]), username = row[3], first_name = row[4], last_name = row[5], email = row[6], is_staff = strtobool(row[7]), is_active = strtobool(row[8]), ) Customers.objects.create( user = User.objects.get(username=row[3]), customer_type = 3, drink_preferences = 2, food_preferences = 1, ) -
Choose multiple choices in a MultipleChoiceField generated from a dynamic tuple list in Django 2.2
I have a MultipleChoiceField that is generated dynamically from a filtered tupled list and I want to be able to choose, or select multiple choices. The below form field only works for selecting one choice, how can I change it to select multiple choices? # in forms.py class Form1(forms.ModelForm): class Meta: model = ModelA fields = ('title',) def __init__(self, *args, **kwargs): self.dynamic_ls = kwargs.pop('dynamic_ls', None) super(Form1, self).__init__(*args, **kwargs) # It's only possible to select one choice with this widget and with this formulation when I want to select multiple choices self.fields['options'] = forms.MultipleChoiceField(widget=forms.SelectMultiple(attrs={'class': 'form-control'}),choices=[(o, str(o)) for o in self.dynamic_ls], required=False) def clean(self): cleaned_data = super(Form1, self).clean() return cleaned_data -
How Can I Host My Django Project On Hostinger Shared Hosting
Please Tell Me That How Can I Host My Django Project On Hostinger shared Hosting Otherwise My Rs.6200 Will Waste -
Django loaddata command error - cannot find fixutres
I can't figure this out.. I've tried what seems like every possible variation, loaddata can't find fixtures in any of my apps. It works in previous versions of Django but on 3.1.5 it does not work. CommandError: No fixture named 'products' found. python manage.py loaddata products python manage.py loaddata products.json python manage.py loaddata products --app product python manage.py loaddata product/fixtures/products python manage.py loaddata product/fixtures/products.json python manage.py loaddata */fixtures/*.json Here's my folder structure myproject ├─product ├─fixtures ├─products.json ├─models.py -
Use user_passes_test after login_required in function based view
I have written a passing condition for user which is as follows: def check_admin(user): isAdmin = False if user.role == "ADMIN": isAdmin=True return isAdmin This is working fine in class based view: class AgentUpdate(LoginRequiredMixin,UpdateView): model = User form_class = UserUpdateForm template_name_suffix = '_update_form' success_url='/agents' @method_decorator(user_passes_test(check_admin)) def dispatch(self, *args, **kwargs): return super(AgentUpdate, self).dispatch(*args, **kwargs) Bu when i use it in function based view it is giving me error 'AnonymousUser' object has no attribute 'role' @login_required @user_passes_test(check_admin) def upload_topic(request): ---- Rest of the view--- -
Ajax/Axios cookies not being set, but still being included in following requests
For some reason cookies set by server are not being saved, can't access them from within my js code, in devtools in Application tab in cookies section it's all empty, but somehow when I make a request to the server after the initial one, those cookies that apparently didn't save are being included in the header. I have set withCredentials to true in axios config, as well as CORS_ALLOW_CREDENTIALS to true on my backend. Here are the headers from the request that should save cookies: Response Header: access-control-allow-credentials: true access-control-allow-origin: <frontend url> content-length: 22 content-type: text/html; charset=utf-8 date: Mon, 01 Feb 2021 12:04:09 GMT server: nginx/1.19.2 set-cookie: csrftoken=<token>; expires=Mon, 31 Jan 2022 12:04:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax set-cookie: sessionid=<sessionid>; expires=Mon, 01 Feb 2021 13:04:09 GMT; HttpOnly; Max-Age=3600; Path=/ strict-transport-security: max-age=31536000 vary: Cookie, Origin x-frame-options: SAMEORIGIN Request Headers: :authority: <backend url> :method: POST :path: /login/ :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 cache-control: no-cache content-length: 66 content-type: application/json;charset=UTF-8 dnt: 1 origin: <frontend url> pragma: no-cache referer: <current frontend url query> sec-fetch-dest: empty sec-fetch-mode: cors sec-fetch-site: same-site user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 As you can see in the response I'm getting … -
Online store deployment error, with many models
As soon as I click on the link, a standard error is written to me. Tried to increase the request processing time but the error persists. I also updated the database completely and changed the host address. Before adding a new model, everything worked, but as soon as I made a couple of changes it stopped working. Here is my code https://github.com/Daryna00/My File location Preset >home >media >merchan >order >Preset >product >staticfiles >templates >' >db.sqlite3 >debug.log >manage.py >Procfile >requirements.txt >runtime.txt Procfile web: gunicorn Preset.wsgi After entering the command such errors. (venv) D:\PycharmProjects\My\Preset>heroku logs --tail 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-02-01T11:48:20.661821+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-02-01T11:48:20.661822+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 790, in exec_module 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-02-01T11:48:20.661823+00:00 app[web.1]: File "/app/home/urls.py", line 2, in <module> 2021-02-01T11:48:20.661835+00:00 app[web.1]: from .views import index, what_is_it, sign_in, register, logout_user, my_page, ajax_reg_login, contact, change_order_count, delete_from_card, add_to_card, get_pdf, questions_answer 2021-02-01T11:48:20.661835+00:00 app[web.1]: File "/app/home/views.py", line 19, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf import pisa 2021-02-01T11:48:20.661836+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/pisa.py", line 18, in <module> 2021-02-01T11:48:20.661836+00:00 app[web.1]: from xhtml2pdf.default import DEFAULT_CSS 2021-02-01T11:48:20.661837+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/xhtml2pdf/default.py", line 5, in … -
ImportError: No module named attr while starting any docker-compose file [closed]
Tried reinstalling docker but didn't help Traceback (most recent call last): File "/usr/bin/docker-compose", line 11, in <module> load_entry_point('docker-compose==1.17.1', 'console_scripts', 'docker-compose')() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 480, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2693, in load_entry_point return ep.load() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2324, in load return self.resolve() File "/usr/lib/python2.7/dist-packages/pkg_resources/__init__.py", line 2330, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python2.7/dist-packages/compose/cli/main.py", line 20, in <module> from ..bundle import get_image_digests File "/usr/lib/python2.7/dist-packages/compose/bundle.py", line 12, in <module> from .config.serialize import denormalize_config File "/usr/lib/python2.7/dist-packages/compose/config/__init__.py", line 6, in <module> from .config import ConfigurationError File "/usr/lib/python2.7/dist-packages/compose/config/config.py", line 44, in <module> from .validation import match_named_volumes File "/usr/lib/python2.7/dist-packages/compose/config/validation.py", line 12, in <module> from jsonschema import Draft4Validator File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/__init__.py", line 11, in <module> from jsonschema.exceptions import ( File "/usr/local/lib/python2.7/dist-packages/jsonschema-3.2.0-py2.7.egg/jsonschema/exceptions.py", line 9, in <module> import attr ImportError: No module named attr