Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to return only form validation messages rather the form itself?
In a Django learning project, I want to return only the custom validation messages either as a list or tuples. But almost all tutorial I found online are utilizing the Form classes, almost similar to the following code: def save(request): if request.method == "POST": form = RegistrationForm( request.POST ) if form.is_valid(): # save employee return redirect('index') else: form = RegistrationForm() return render(request, 'form.html', {'form': form}) Where RegistrationForm contains the following code: from django import forms class RegistrationForm(forms.Form): first_name = forms.CharField(min_length=4) last_name = forms.CharField(required=False) email = forms.EmailField() contact_no = forms.CharField(min_length=11) gender = forms.CharField(min_length=4) This validation is working, it returns the form with all validation messages. But what I want is: I want to return the validation messages, rather than the form itself. I am pretty new in Django so I can not figure out a suitable way (if there is any) how to return validation messages as a list or tuples rather as the form object. Can anyone help to solve the issue? -
GET Django products and their thumbnails from foreignKey with single query
I have these two Django models: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) User inputs some keyword, and based on that, I filter the product names, and matching product names are shown, together with all their product's thumbnails. What is the most efficient way to retrieve all the products, and all their thumbnails, without querying twice separately for the products and for the thumbnails? I know that using .select_related() we can fetch the foreign objects as well, but we can make either a) two separate serializers for each model separately, thus requiring to have two separate viewsets, two querysets and two accesses to the database, or b) nested Serializer, with fields from both models, but in that case we will get repeating data, the product_description will appear in every row for every thumbnail, which is also a problem, since that description can be many characters long, and will be an overkill to repeat it. Omitting it from the fields is not an option either, as I do need to get it at least once somehow. Is there a third, more efficient way? I expect this to be possible with accessing the database only once, but I can't … -
django two-step authentication(otp) with allauth
I want to implement two-step authentication with allauth(otp). Already, normal authentication of allauth is implemented with email Please teach me how to implement two-step authentication(otp) with email. -
Django & MeMSQL Error when running migrate.py: django.db.utils.OperationalError: (2012, 'Error in server handshake')
I have a Django application with a default MySQL database. I want to move my default Database to MeMSQL. I set the credentials in settings.py to be: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': MEMSQL_DB, 'USER': MEMSQL_USER, 'PASSWORD': MEMSQL_PASSWORD, 'HOST': MEMSQL_HOST, 'PORT': '3306' } I try to run manage.py migrate to move all models to the new DB, and get this error: django.db.utils.OperationalError: (2012, 'Error in server handshake') If it helps - I tried to test the connection and credentials throughout a workbench (SQL-Pro), and it work successfully. only the manage.py migrate give me this error -
pipenv failed parsing requirement
I'm new to pipenv and installations in Mac Terminal. I was trying to install Django through pipenv and was getting the following error: ''' File "/Users/sidm/Library/Python/2.7/lib/python/site-packages/pipenv/vendor/requirementslib/models/requirements.py", line 969, in _parse_name_from_line "Failed parsing requirement from {0!r}".format(self.line) pipenv.vendor.requirementslib.exceptions.RequirementError: Failed parsing requirement from u'--python3.7' ''' I'd be so grateful if someone helps me resolving this issue. Cheers. -
Django rest authentication error in processing password_reset | dj-rest-auth
In my project, I tried to allow users to change and reset password. But can't figure out why this mail configuration isn't working. Actually, it doesn't send mail to the user. But showing e-mail has been sent on API. Here is my code: settings.py REST_SESSION_LOGIN = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'optional' #mail config EMAIL_HOST = 'smtp.gmail.net' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_HOST_PASSWORD = '************' #gmail app password EMAIL_USE_TLS = True urls.py urlpatterns = [ path('admin/', admin.site.urls), path('authentication/', include('dj_rest_auth.urls')), path('authentication/registration/', include('dj_rest_auth.registration.urls')), path('api/', include('articles.api.urls')), re_path(r'^authentication/password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm') ] And in terminal at from it shows webmaster@localhost. But why it isn't showing EMAIL_HOST_USER e-mail. Subject: Password reset on example.com From: webmaster@localhost To: gicof53256@tdcryo.com Date: Sun, 29 Nov 2020 08:14:16 -
SQl not connected
I have sql installed but then also its showing me this django.db.utils.OperationalError: (1045, "Access denied for user 'mahima'@'localhost' (using password: YES)") this is from my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev_jrc_api', 'USER':'mahima', 'PASSWORD':'****', 'HOST':'192.168.0.37', 'PORT':'3307', 'OPTIONS':{'init_command':"SET sql_mode='STRICT_TRANS_TABLES'"} } } -
Reuse Primary Key in another Django model field
Is it possible to reference the primary key in another field in a Django model? For example, let's say I want to have a field looking like BUG0001 corresponding to the entry with pk=1. What is the best way to achieve this? I think it is best to keep the primary key as an integer as it is easier to deal with, and I guess formatting the primary key every time is not very effective. -
Saving into through table m2m
I'm trying to save into a table that i created to handle many2many relation. I didn't know why, but my form save into table 'Card', but doesn't save into 'Card_id_user' and i don't get why. This is my code... class New_card_creation_view(CreateView): title = "AGGIUNGI CARD" model = Card template_name = "new_card.html" fields = ['card_title', 'description', 'expiration_date', 'column'] def create_card_view(request): if request.method == 'POST': form = CardCreationForm(request.POST or None) if form.is_valid: form = form.save(commit=False) """nc = Card_id_column(card_id=form.id, column_id=request.column.id) nc.save()""" n_card = Card_id_user(card_id=form.id, user_id=request.user.id) n_card.save() form.save() return render(request, 'board.html') else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) else: form = CardCreationForm() return render(request, 'new_card.html', {'form': form}) def get_context_data(self, **kwargs): context = super(New_card_creation_view, self).get_context_data(**kwargs) context.update({'title': self.title}) return context def get_success_url(self): return reverse('board_view', args=(self.object.column.board.id,)) models.py class Card(models.Model): card_title = models.CharField(max_length=120, verbose_name='Titolo', error_messages={'unique': 'Titolo della Card già utilizzato. Per favore inseriscine un altro.'}) description = models.TextField(default='Il tuo testo...', max_length=300, verbose_name='Descrizione') expiration_date = models.DateTimeField('data di scadenza') column = models.ForeignKey(Column, on_delete=models.CASCADE, verbose_name= 'colonna di riferimento', null=False) story_points = models.PositiveSmallIntegerField(default=0, help_text='inserisci un valore da 1 a 5',validators=[MinValueValidator(1), MaxValueValidator(5)]) id_user = models.ManyToManyField(User, related_name='user_card', verbose_name='id utente', through='Card_id_user') object = models.Manager() class Card_id_user(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) card = models.ForeignKey(Card, on_delete=models.CASCADE) id = models.IntegerField(primary_key=True) n_card seems to be useless -
How to change my inline styles based on the selected language in Django
I am building a django web application. I wish to change the layout of my website from RTL(right to left) to LTR(left to right). I have implemented the HTML[dir='rtl'] in it. It worked but the main issue is that the layout. I want the layouts to get switched from LTR to RTL whenever the selected language is arabic. views.py def index(request): if not request.session.has_key('currency'): request.session['currency'] = settings.DEFAULT_CURRENCY setting = Setting.objects.get(pk=1) # >>>>>>>>>>>>>>>> M U L T I L A N G U G A E >>>>>> START defaultlang = settings.LANGUAGE_CODE[0:2] currentlang = request.LANGUAGE_CODE[0:2] context={'defaultlang': defaultlang} return render(request,'index.html',context) page.html <div id="top-header"> <div class="container"> <div class="{% if defaultlang == 'en' %}pull-left {% else %} pull-right{% endif %}"> <span>{% trans "Welcome to E-shop!" %}</span> </div> <div class="{% if defaultlang == 'en' %}pull-right {% else %} pull-left{% endif %}"> <span>GoodBye</span> </div> </div> </div> I need a way to ensure that the classes change when the language is Arabic. Please kindly help with any suggestions you have.Thanks -
'<=' not supported between instances of 'float' and 'QuerySet'
I want to make a substraction between total (its in model.py) and account balance. So here I have Order Model.py : class Order(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="product") customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) fname = models.CharField(max_length=100, null=True) address = models.CharField(max_length=1000, null=True) phone = models.CharField(max_length=12, null=True) price = models.IntegerField() date = models.DateField(datetime.datetime.today, null=True) status = models.ForeignKey( Status, on_delete=models.CASCADE, blank=True, null=True) payment_method = models.ForeignKey( PaymentMethod, on_delete=models.CASCADE, blank=True, null=True) total = models.IntegerField(null=True) def save(self, *args, **kwargs): self.total = self.quantity * self.price return super().save(self, *args, **kwargs) In this model I have total field so in views.py: def post(self, request, *args, **kwargs): total = Order.objects.filter().only('total') print(total) balance = request.session['customer']['coin'] print(balance) if balance <= total: balance = balance - total print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get( id=request.session['customer']['id']) customer.coin = balance customer.save() request.session['customer']['coin'] = balance return HttpResponse("Remaining balance: " + str(balance)) return HttpResponse("Insufficient Balance") I tried to fetch total field and subtract with balance but its not working and I am getting this error. Another thing is i want to assign total field in a variable after this i want to substract with balance which i showed in views.py Please save me -
How to restrict a custom validator to only pushing errors to field.errors and not django messages?
I am using a custom validator on a model field. Model field: html_content = models.TextField(blank=True, verbose_name=_("HTML content"), validators=[validate_template_syntax]) Validator: def validate_template_syntax(source): try: Template(source) except (TemplateSyntaxError, TemplateDoesNotExist) as err: raise ValidationError(str(err)) However, when the validator error is triggered, it pushes the error to both the django messages framework (messages) and field.errors, so in a template if I am rendering other messages alongside a form the error is displayed twice. How do I restrict the validator to only pushing the error to the field errors context? -
GET products and images from two Django models, by filtering the product name and accessing the database only once
I have two Django models for an eCommerce website: class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Thumnbnail(models.Model): thumnbnail=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) The user will input some keywords, and I filter on the product names with that keyword, and show only those products. With every product, on the results page, I want immediately all its product thumbnails to be loaded and shown as well. How can I retrieve both models in the same viewset and same queryset, in an efficient way? I know I can achieve this with two separate querysets, one being queryset = Product.objects.filter(name__contains="Fanta").all() return queryset and the other viewset for the thumnails queryset = Product.objects.select_related('thumbnail').filter(name__contains="Fanta").all() return queryset # I will create another serializer to only show the thumbnails, for this specific queryset I might not have written the last one most correctly, I am just writing pseudo-code, but I know how to do it. My point is, I need to do the same filtering of the product_names with the input keywords twice, once to retrieve the product names and descriptions, in a ProductViewset, and one more time the same filtering, to get their thumbnails, from a ThumbnailViewset. How do I avoid this, and do the filtering only once? I know … -
How to display saved dynamic images in Django
Hi Im trying to display this image that I am generating in my view file. This image is generated on the basis of a search algorithm. It is saved in this variable "mimg". I don't understand how to display in template. I have tried various methods but nothing is helping. im new to django and don't know how to resolve this issue def match(request): this_file=os.path.abspath(__file__) base_dir=os.path.dirname(this_file) entries = os.listdir('static_in_env/db_images/') entries2= os.listdir('media/images/') list_of_files = glob.glob('media/images/*') latest = max(list_of_files, key=os.path.getctime) img=Image.open(latest) r, g, b = img.split() len(r.histogram()) red=r.histogram() green=g.histogram() blue=b.histogram() mr=max(red) mg=max(green) mb=max(blue) nhr = [i/mr for i in red] nnhr = np.multiply(nhr, 255) nhg = [i/mg for i in green] nnhg = np.multiply(nhg, 255) nhb = [i/mb for i in blue] nnhb = np.multiply(nhb, 255) n=1 p=[fname.rsplit('_', 1)[0] for fname in entries] mylist = list(dict.fromkeys(p))[:-1] for i in range(0, len(mylist)): img1=mylist[i]+'_a.jpg' img2=mylist[i]+'_b.jpg' img3=mylist[i]+'_face.jpg' f1='static_in_env/db_images/'+img1 f2='static_in_env/db_images/'+img2 f3='static_in_env/db_images/'+img3 db_img = Image.open(f1) r1, g1, b1 = db_img.split() red1=r1.histogram() green1=g1.histogram() blue1=b1.histogram() db_img2 = Image.open(f2) r2, g2, b2 = db_img2.split() red2=r2.histogram() green2=g2.histogram() blue2=b2.histogram() db_img3 = Image.open(f3) shr = red1+red2 shg = green1+green2 shb = blue1+blue2 shr1=np.divide(shr, 2) shg1=np.divide(shg, 2) shb1=np.divide(shb, 2) smr=max(shr1) smg = max(shg1) smb = max(shb1) nhr1 = [i/smr for i in shr1] nnhr1 … -
How to Retrieve a specific value of a Tuple from Django database
So here I have a table named Product which contains Food name,Category,Price,Image,Dataset id column so i would like to retrieve the value of Dataset id only ,in Django I would like to put parse dataset_id into recommend function but it doesnt give value of 31 while i select Pizza so i tried just printing it and the output in my console is <django.db.models.query_utils.DeferredAttribute object at 0x03B11CE8> here is my code from views.py from .models import Product def cart(request): if request.user.is_authenticated: print(Product.dataset_id) res=recommend(item_id=31, num=3) customer = request.user.customer order , created = Order.objects.get_or_create(customer = customer , complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items print(res) Here is my code for Products in models.py class Product(models.Model): food_id = models.AutoField food_name = models.CharField(max_length=50, default="") cateory = models.CharField(max_length=50, default="") subcategory = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to='menu/images', default="") dataset_id = models.IntegerField(default = 0) -
Django sends it response to browser it gets this error: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am using Django Rest Framework as my backend and ReactJS as my frontend. My DRF files look like this settings.py ALLOWED_HOSTS=['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'ecom', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True backend/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('ecom.urls')), ] ecom/urls.py from django.urls import path from ecom import views urlpatterns = [ path('categories/',views.CategoryList.as_view(), name = 'categories'), path('categories/<int:pk>/',views.CategoryDetail.as_view(), name = 'categories_detail'), path('products/',views.ProductList.as_view(), name = 'products'), path('products/<int:pk>/',views.ProductDetail.as_view(), name = 'products_detail'), ] REACTJS App.js import React , {Fragment, useEffect, useState} from 'react'; import axios from 'axios'; function App() { const [data, setData] = useState({hits: []}); useEffect(async ()=>{ const result = await axios( `http://127.0.0.1:8000/categories/` , ); setData(result.data) }); return( <ul> {data.hits.map(item=>( <li key={item.id} >{item.name}</li> ))} </ul> ) } export default App; Result Access to XMLHttpRequest at 'http://127.0.0.1:8000/categories/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://127.0.0.1:8000/categories/ net::ERR_FAILED I tested in Postman, my API response is fine. I can see my API. However, when browser tried to fetch the API, it complains by the CORS (I … -
is there a way that i can connect my app with a gprs tracker?
Car theft becoming a major issue in my country, I am trying to build an app that will communicate with the GPRS tracker, I know there are some apps in the market but I want to add some more enhanced features to the app, how do I go about integrating the app with the GPRS tracker. Thanks! -
Django model ImageField creates a nested folder each time it uploads file
I'm sure I'm missing something silly, but I'm confused. I have the following model for my profile: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default="default.jpg", upload_to="profile_pics/", validators=[FileExtensionValidator(["jpeg", "jpg", "png"])], ) def __str__(self): return f"{self.user.username} Profile" def save(self, *args, **kwargs): if self.image: self.image = make_thumbnail(self.image, size=(200, 200)) super().save(*args, **kwargs) else: super().save(*args, **kwargs) But the profile_pics folder keep nesting (I'm not sure what triggers it, I'm not uploading a new avatar). So my folder structure starts to look like this: And I can't login with that user, as I get an error that reads: SuspiciousFileOperation at /login/ Storage can not find an available filename for "profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/profile_pics/1_0hOa7bn.jpg". Please make sure that the corresponding file field allows sufficient "max_length". My variables in settings.py look normal, I believe: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" I'm not sure where to look for the cause of this error. Uploading images to the blog posts work fine, it's just the profile photos behaving like this. Could anyone please help? -
Django queryset renders incorrectly. Just displays <QuerySet [<Modelname: Model object (1)>]>
I'm having a problem with rendering an object from a model. Here is the model. class Quarterback(models.Model): name = models.CharField(max_length=20) When I use a queryset like this... QB = Quarterback.objects.all() It doesn't return the object but this instead. <QuerySet [<Quarterback: Quarterback object (1)>]> The object is being saved by a function inside a form. class PlayerForm(forms.Form): quarterback_name = forms.CharField(label='Quarterback', max_length=100) def save(self): quarterback_name = self.cleaned_data.get('quarterback_name') Quarterback.objects.create(name=quarterback_name) In my admin panel, I can look up this model object and see that it does indeed have the name of a quarterback saved to the table. I'm not sure why my queryset won't return this though. Perhaps it's the save function causing it? -
How to add delete and update functionality to ModelSerializer?
I want to update and delete category instances using api. I have a simple model: class Category(models.Model): name = models.CharField(max_length=80) def __str__(self): return self.name this is my serializer: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["name"] view: class CategorySerializerView(viewsets.ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() def get_permissions(self): if self.request.method == "GET": self.permission_classes = (AllowAny, ) else: self.permission_classes = (IsAdminUser, ) return super(CategorySerializerView, self).get_permissions() urls: router = DefaultRouter() router.register(r'', CategorySerializerView) urlpatterns = [ path("", include(router.urls)) ] -
Why do I get ValidationError on my serializer when I shouldn't be getting one?
So I have this serializer: class MarkReadDeserializer(serializers.Serializer): id = serializers.PrimaryKeyRelatedField(queryset=Message.objects.all()) is_read = serializers.BooleanField() And view: class MarkReadView(CreateAPIView): read_serializer_class = MarkReadSerializer write_serializer_class = MarkReadDeserializer def get_write_serializer(self, *args, **kwargs): kwargs['many'] = True return super().get_write_serializer(args, kwargs) Now my view is being POSTed data in the shape of: [{"id": 1, "is_read": true}, {"id": 2, "is_read": false}] When this happens I get this error: rest_framework.exceptions.ValidationError: {'id': [ErrorDetail(string='This field is required.', code='required')], 'is_read': [ErrorDetail(string='This field is required.', code='required')]} I did override my is_valid method in serializer to see the initial data: def is_valid(self, raise_exception=False): print(self.initial_data) And it is printing expected: {'data': [{'id': 123, 'is_read': True}, {'id': 122, 'is_read': True}, {'id': 121, 'is_read': True}, {'id': 120, 'is_read': True}], 'many': True} Why do I get the ValidationError? -
ModelForm is not generating any form
So my problem is that even though I have created the forms from my model and provided my views with those forms, the related template is not displaying any form: The following is my forms.py : from django import forms from django.contrib.auth.models import User from .models import Account class UserUpdateForm(forms.ModelForm): email = forms.EmailField(max_length=100) class Meta: model = User fields = ['username', 'email'] class AccountUpdateForm(forms.ModelForm): class Meta: model= Account fields = ['image'] And the next one is my views.py: from .forms importUserUpdateForm, AccountUpdateForm def account(request): user_update_form = UserUpdateForm() profile_update_form = AccountUpdateForm() return render(request, 'blog/profile.html', { 'user_update_form':user_upate_form, 'profile_update_form':profile_update_form }) But the following template does not show any form {% extends './base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-12 d-flex flex-column justify-content-center align-items-start"> <img src="{{ user.account.image.url }}" alt="" class="user-profile-pic"> <label for="user-profile-pic-input">Choose an image</label> <input type="file" class="form-control-files w-100" id="user-profile-pic-input" name='user-profile-pic-input'> </div> </div> <div class="row"> <div class="col-12"> <form method="POST"> {% csrf_token %} {{ user_update_form }} {{ profile_update_form }} <input type="submit" value="Save changes!" class="btn btn-info btn-block"> </form> </div> </div> {% endblock %} -
Return two different models in the same queryset in django
Let's use these 2 simple models for example. A product can have multiple images. models.py class Product(models.Model): name=models.CharField(max_length=300) description=models.CharField(max_length=10000) class Image(models.Model): image=models.ImageField(null=True) product=models.ForeignKey(Product, related_name='related_product', on_delete=models.CASCADE) In my viewset, in get_queryset(), I am fetching list of all the products, based on some keyword filter on the product's name and all their images, with queryset = Product.objects.select_related('image').filter(name__contains="Fanta").all() To the client, I want to return: JSON, a table, list of all the products (product_id, product_name, product_description) and, Another JSON, another separate table of all the images of all the products. (image_id, image, product_id) One way to do this is to make a combined Serializer, which will give me the fields (image_id, image, product_id, product_name, product_description) But I don't want this, since for every image, the product_description will be repeated, and since that one can be quite large, 10.000 characters, I want to find a more optimal way. I want to get the product_description as well, but only once, there is no need to repeat it in every row, for every image of that product. Another way to do this is to make two separate viewsets, each one with its own get_queryset(). But for the product model, I will have to filter the product_names … -
Dockerfile error - FROM requires either one or three arguments
I'm trying to import a base image into docker, but when I write the following command in my terminal: docker build . I get the following error: failed to solve with frontend dockerfile.v0: failed to create LLB definition: Dockerfile parse error line 2: FROM requires either one or three arguments It is telling me FROM requires one or three arguments (I'm following a book and they wrote it exactly like that) My Dockerfile contains the following: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ I'm running the code while in the same dir as the Dockerfile - The Dockerfile is named 'Dockerfile' Docker version 19.03.13 Any ideas why this is happening? Thank you in advance -
Error encountered while using py decouple
A string is returned in the settings.py file but SPOTIPY_REDIRECT_URI goes unnoticed. .env SPOTIPY_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxx SPOTIPY_CLIENT_SECRET=xxxxxxxxxxxxxxxxxxxx SPOTIPY_REDIRECT_URI=http://localhost/ settings.py SPOTIPY_CLIENT_ID= config('SPOTIPY_CLIENT_ID') SPOTIPY_CLIENT_SECRET= config('SPOTIPY_CLIENT_SECRET') SPOTIPY_REDIRECT_URI= config('SPOTIPY_REDIRECT_URI') ERROR: decouple.UndefinedValueError: SPOTIPY_REDIRECT_URI not found. Declare it as envvar or define a default value.