Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django return redirect to external url not working
I'm having difficulty getting a redirect to work for external URLs. The following is in the views.py file: def link_out(request): products = products_for_cart(user=request.user) product = get_object_or_404(products, pk=product_id) if product.is_link(): variant_id = request.POST.get('variant') variant = ProductVariant.objects.get(id = variant_id) print(variant.external_url) response = redirect(variant.external_url) print('before redirect') return response print('after redirect') 'before redirect' and the URL are printed in the shell, however, the browser never redirects to an external URL. https://www.google.co.uk/ before redirect INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] INFO django.server "POST /en/products/t-shirt-6/add/ HTTP/1.1" 302 0 [PID:31664:Thread-3] There are two things that seem interesting to me, the three POSTs after the redirect (all INFO prints are coming in threes??), and that the redirect isn't executing in the browser. My questions are, where does the redirect get returned to from the views.py file, and what could be the reason for the broswer not redirecting? Thanks -
CORS blocked in dockerized Django REST + Angular project
I decided to dockerize an existing Django REST + Angular app today. The website is displaying as it should, however CORS requests are being blocked. Access to XMLHttpRequest at 'http://localhost:8000/branches/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The angular App is dockerized using Nginx. I was using this tutorial in the progress (docker + compose files are listed below). Strange thing about this is that I had this problem before and solved it through the use of the djang-cors-headers package. Along with CORS_ORIGIN_ALLOW_ALL = True, this no longer seems to be solving the issue. Can this be related due to the fact that the application now runs in containers? I'm providing the dockerfiles for the projects along with the docker-compose file below. Not sure if they are relevant though. Dockerfile for the Angular project: FROM tiangolo/node-frontend:10 as build-stage WORKDIR /app COPY package*.json /app/ RUN npm install COPY ./ /app/ ARG configuration=production RUN npm run build -- --output-path=./dist/out --configuration $configuration # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx FROM nginx:1.15 COPY --from=build-stage /app/dist/out/ /usr/share/nginx/html # Copy the default nginx.conf provided by … -
Django Rest Framework - Restrict FK entries
I have 2 models, Post and Comments class Post(models.Model): post_id = models.IntegerField(primary_key=True) ... class Comment(models.Model): post = models.ForeignField(Post, on_delete=models.CASCADE, related_name='comment_post') ... I have made a serializer for post class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all___' class PostSerializer(serializers.ModelSerializer): comments = CommentSerializer(many=True, source='comment_post') class Meta: model = Post fields = ('post_id', 'comments') The PostSerializer gives all the comments on a particular post. I want to access 5 latest comments per post. (planning to use something like order_by('-comment_time')[:5]) How can i do this in Django Rest Framework within PostSerializer? Thanks! -
How add extra fields data to database with UserCreationForm Django?
I'm trying to add data from UserCreationForm extra fields to database, i want to add multiple fields to UserCreationForm and save it to database. I saw other examples from topics here in stackoverflow, but it doesn't work. Here is a example of my code: ( fields: "agree_terms" or "price" could be anything else) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs= {'placeholder':'Email'})) agree_terms = forms.BooleanField() price = forms.DecimalField(decimal_places=2, max_digits=10000) class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('username', 'password1', 'email','password2','agree_terms','price') views.py @csrf_protect def registers(request): if request.method == 'POST': form = UserRegisterForm(request.POST) print(form) print(form.is_valid()) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,'Conta criada {}'.format(username)) return redirect('login') else: form = UserRegisterForm() return render(request,'header-login.html',{'form':form}) -
writing unit test for many to many model in django program
in my django projects, I have a two class like following: class DataTag(models.Model): title = models.CharField(max_length=120, unique=True) relations = models.ManyToManyField('DataTag', related_name='related_data_tags', blank=True) and the another class is: class Data(models.Model): tags = models.ManyToManyField('DataTag',related_name = 'data') def tag_name(self): if self.tags.all(): return self.tags.all()[0].title return '' both my models work, but now I want to write a test for main_tag_name, and checking if this function returns a true value or not.until now I write the following: from unittest import TestCase class BusinessTest(TestCase): def test_tag_name(self): self.data = Data.objects.create() self.tag1 = DataTag.objects.create() I am new on writing test. please help me for writing this test. Thanks in advance -
Django template variable (model instance) translation
There is a Product model with name CharField in my db. There is a template for rendering one instance of the Product model on the page. In view i'm passing to the template product variable which is filtered instance of the Product model. In template i need to translate variable {{ product.name }} depending on which Product instances page is rendering now. After reading Django documentation: To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. i decided to use next: {% blocktrans with product_name=product.name%}{{product_name}}{% endblocktrans %} in django.po file i get: msgid "%(product_name)s" Can you tell me please, am i on the right way? And how should name attributes of the other product instances be translated if such approach allows to provide translation only for one product.name? Thanks for any attention! -
Formatting DateTimeField in Django
When saving timestamp in Django's DateTimeField using auto_now_add this way: creation_timestamp = models.DateTimeField(auto_now_add=True) the field is saved with miliseconds: 2018-11-20T15:58:44.767594-06:00 I want to format this to be displayed without miliseconds: 2018-11-20T15:58:44-06:00 But the only option I could come up with does not exactly shows what I need: format="%Y.%m.%dT%H:%M:%S%z" gives me 2018.11.20T15:58:44-0600 How do I format this field the way I need? Alternatively I'd rather save DateTimeField without milliseconds at all but does auto_now_add allow to do this sort of thing? -
jQuery not sending element text to form field [duplicate]
This question already has an answer here: Event binding on dynamically created elements? 23 answers I created a set of links in jQuery. The "zip_list" below is from an ajax call that got the data from a Django database request. This part works as expected, at least I think... //end of ajax call that gives json response dataType: "json", success: function(data) { zip_list = JSON.parse(data); //parse json response x = zip_list.length; //get length value for loop var container = $('<div />'); for(j=0; j<x; j++){ container.append($('<a href="#">').addClass("zip_response").text(zip_list[j]["city"]+','+zip_list[j]["state"])); container.append($('<br>')); } $('.zip_menu').append(container); } It outputs html code that looks like this: <div class="zip_menu"> <div> <a href="#" class="zip_response">COLUMBIA,MO</a> <br> <a href="#" class="zip_response">HINTON,MO</a> <br> <a href="#" class="zip_response">LINDBERGH,MO</a> <br> </div> </div> Now with those links, when they are clicked should fill in form data, with the below jQuery: $(".zip_response").click(function () { var txt = $(this).text(); //****NOT WORKING ON ELEMENTS CREATED THROUGH JQUERY, BUT WORKS ON SAME LINKS IF PUT IN AS NORMAL HTML var city_state = txt.split(","); //splits that text that in the tag, but a comma producing an array, with the city and state console.log(city_state[1]); $("#state").val(city_state[1]); //form field for state $("#city").val(city_state[0]); //form field for city }); The issue is that at this point in the … -
django 2.13 login_required build-in decorator doesn't work
i work on Django 2.1.2 and i wanted decorated my view base on class. I apply login_required decorator in path path('', login_required(CredentialsList.as_view()), name='credentials-list'), when i send request to CredentialList it responds normally, it does not redirect me to the login screen. whether I omitted something from the configuration LOGIN_URL='login/' LOGIN_REDIRECT_URL = 'list/' -
Django second page not found
Can any one tell me why my help page keeps returning page not found please? Views from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): my_dict = {'insert_me':"Hello I am from views.py !"} return render(request, 'first_app/index.html', context=my_dict) def help(request): help_dict = {'help_insert':'HELP PAGE'} return render(request, 'first_app/help.html', context=help_dict) First_app urls from django.urls import path from first_app import views urlpatterns = [ path('', views.index, name='index'), path('', views.help, name='help' ), ] first_app urls: from django.contrib import admin from django.urls import include, path from first_app import views urlpatterns = [ path('', views.index, name='index'), path('first_app/', include('first_app.urls')), path('admin/', admin.site.urls), ] there is a template folder with first app_folder both html files are in there. Have tried http://127.0.0.1:8000/first_app/help and http://127.0.0.1:8000/help What am I missing please? -
Django getstream User object is not iterable
i try to integrate Django with Getstream. Mostly code work, but at the end on profile page, i have error: "User object is not iterable". I follow tutorial get stream Twitter, and search through Getstream pinterest example. I have the same code, but for me don't work. Try both, getstream Twitter profile view and pinterest style profile view. Both the same error. View: def user_detail(request, username): ''' Shows the users profile ''' enricher = Enrich(request.user) profile_user = get_user_model().objects.get(username=username) feed = feed_manager.get_user_feed(profile_user.id) activities = feed.get(limit=25)['results'] context = {} do_i_follow_users(request.user, [profile_user]) context['profile_user'] = profile_user context['activities'] = enricher.enrich_activities(activities) response = render(request, 'account/user/detail.html', context) return response When I check getstream dashboard I see log of actions: Screen getstream dashboard log What are the other options to interate through user. I need only user timeline on this page. -
jQuery not decrementing value in Django Inline Formset UpdateView
I'm using this script - https://github.com/elo80ka/django-dynamic-formset/blob/master/src/jquery.formset.js With this template: <div id="approach_form" class="form-control pl-4 pt-2"> {% for formset in inlines %} <table> {% for form in formset %} {{ form.id }} {{ form.errors }} <tr> <td>{{ form.approach_type }}</td> <td>{{ form.number }}</td> <td>{% if form.instance.pk %}{{ form.DELETE }}{% endif %}</td> </tr> {% endfor %} </table> {{ formset.management_form }} {% endfor %} </div> And it renders this html: <div id="approach_form" class="form-control pl-4 pt-2"> <table> <input type="hidden" name="approach_set-0-id" value="25" id="id_approach_set-0-id"> <tbody><tr class="approach-formset"> <td><select name="approach_set-0-approach_type" id="id_approach_set-0-approach_type"> <option value="">---------</option> <option value="ILS">ILS</option> <option value="CATII">CAT II</option> </select></td> <td><input type="number" name="approach_set-0-number" value="2" min="0" id="id_approach_set-0-number"></td> <td><input type="hidden" name="approach_set-0-DELETE" id="id_approach_set-0-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <input type="hidden" name="approach_set-1-id" value="24" id="id_approach_set-1-id"> <tr class="approach-formset"> <td><select name="approach_set-1-approach_type" id="id_approach_set-1-approach_type"> <option value="">---------</option> <option value="ILS" selected="">ILS</option> <option value="CATII">CAT II</option> <option value="CATIII">CAT III</option> </select></td> <td><input type="number" name="approach_set-1-number" value="1" min="0" id="id_approach_set-1-number"></td> <td><input type="hidden" name="approach_set-1-DELETE" id="id_approach_set-1-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <input type="hidden" name="approach_set-2-id" value="26" id="id_approach_set-2-id"> <tr class="approach-formset"> <td><select name="approach_set-2-approach_type" id="id_approach_set-2-approach_type"> <option value="">---------</option> <option value="ILS">ILS</option> <option value="CATII">CAT II</option> </select></td> <td><input type="number" name="approach_set-2-number" value="3" min="0" id="id_approach_set-2-number"></td> <td><input type="hidden" name="approach_set-2-DELETE" id="id_approach_set-2-DELETE"><a class="delete-row" href="javascript:void(0)">Remove</a></td> </tr> <tr class="approach-formset-add"><td colspan="3"><a class="add-row" href="javascript:void(0)">Add</a></td></tr></tbody></table> <input type="hidden" name="approach_set-TOTAL_FORMS" value="3" id="id_approach_set-TOTAL_FORMS"><input type="hidden" name="approach_set-INITIAL_FORMS" value="3" id="id_approach_set-INITIAL_FORMS"><input type="hidden" name="approach_set-MIN_NUM_FORMS" value="0" id="id_approach_set-MIN_NUM_FORMS"><input type="hidden" name="approach_set-MAX_NUM_FORMS" value="4" id="id_approach_set-MAX_NUM_FORMS"> </div> The specific problem is that the remove links do … -
convert array of strings inside of string into a python list
I've sent some form-data from my React client to my Django + DRF api. inside of the form-data I have an attribute date_strings which is an array of date-time strings. i.e. ["date1", "date2", "date3"] in order to send it to my Django api I converted the array of strings into a string using JSON.stringify const myForm = new FormData(); myForm.set("date_strings", JSON.stringify(dateStrings)); in the create method of my serializer, I'd like to convert this data into a list. def create(self, validated_data): stringified_array = validated_data.pop('date_strings') // stringified_array: '["date1", "date2", "date3"]' how can I convert an array of strings inside of a string into a python list? -
Is the default django development server secure or can others access it?
I'm new to django/python and want to make sure that if I'm learning django on my own from my work machine, it won't be some kind of security breech when django sets up its automatic development server. I'm using this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ And they have you set up the dev server as: $ python manage.py runserver which outputs: Performing system checks... System check identified no issues (0 silenced). You have unapplied migrations; your app may not work properly until they are applied. Run 'python manage.py migrate' to apply them. November 17, 2018 - 15:50:53 Django version 2.1, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Can others access this server, either from within the network or just through the internet? How would one go about checking that? -
Only allow requests from single site in Django Rest Framework
For illustrative purposes let's say I have a website at https://www.signup.com that let's users sign up for an email list. After the user enters their email and hits 'Submit,' signup.com sends POST request to https://www.manager.com: { "email" : "fake@whatever.com" } Then the server adds that email to the database. My question is: what's the best way to ensure that only signup.com is able to successfully send POST requests to manager.com? -
Django autocomplete based on drop down selection
I am storing the autocompletion data in SomeObject objects and successfully use the following to autocomplete with a filter based on current user: views.py def get_autocompletion_list(request): if request.is_ajax(): q = request.GET.get('term', '') results = [] if len(q) > 0: my_words = SomeObject.objects.filter(owner=request.user.id) words = my_words.filter(word__startswith=q) for w in words: results.append(w.word) data = json.dumps(results) else: data = '' mimetype = 'application/json' return HttpResponse(data, mimetype) template: <form action="/" method="post" id=""> {% csrf_token %} {{form.category}} </form> <input id="searching"> javascript function: $(function() { var selection = $(category_id).val() $("#searching").autocomplete({ source: "/api/get_autocompletion_list/", select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 1, }); }); Now I want to filter the autocompletion based on the selection of form.category drop down, I am able to get the current selection in the form, but how would I send it to the view where I can do the filtering? -
How to make a buttons with colors of the rainbow in my cycle in html?
My project is made on jango framework. {% for tag in tags %} <div class="btngroup" role="group" aria-label="tags"> <h3><a href="{{ tag.get_absolute_url }}" class="btn btn-primary">{{tag.title}}</a></h3> </div> {% endfor %} I will explain a little. In this cycle, I get link tags from the database, which I want to wrap in buttons of different colors of the rainbow. But how to do that ? -
How to create another column with filtered value in queryset
I have a query that retrieves 20 questions. The query then should add another column or data to the queryset that indicates which choice the user has answered. So in total there are 4 models, including a User model. class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) Query Question.objects.filter( Q(user=3))[:20] How do I add another column in this query to show which choice the user picked? -
using css/ bootstrap webtabs for django forms
I run into the following issue with my Django project: I have an profile edit page, where I want the user to be able to edit their profile information, which is seperated in tabs that they can navigate: Profile and Extended Information. However, the page loads at the Profile tab, but when I navigate to the Extended Information tab, it just opens this tab below the Profile tab, and it doesn't 'replace' the first tab with the second. Consequently, I get a MultiValueDictKeyError error when I only change something in the Extended Information form under that tab. How do I fix the error with the tabs opening below each other? I suspect that my MultiValueDictKeyError also disappears then (but I'm not sure). Html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <!-- Nav tabs --> <div class="container profile"> <div> <h1>Edit your details:</h1> <h3><strong><a href="{% url 'users:profile' %}">{{user.username}}</a></strong></h3> </div> <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Profile</a> <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Extended information</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> <form method="post"> {% csrf_token %} {% bootstrap_form basic_form %} … -
Django Activation Email
I am following this tutorial: https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html to send my users an activation email which they have to click to verify and activate their account.. but I keep getting this error: AttributeError: 'UserRegister' object has no attribute 'pk' I've been messing with Django's AbstractUser functions to create my own forms and models for users, so i think that has to do with it.. but i'm not sure where to go from here. Do I need to create an attribute called 'pk'? Here is my forms.py: class UserRegister(UserCreationForm): class Meta: model = UserInfo fields = ['first_name', 'last_name', 'email', 'password1', 'password2', 'street_address', 'city', 'state', 'zipcode', 'sendPromo'] first_name = forms.CharField(label='First Name', required=True) last_name = forms.CharField(label='Last Name', required=True) street_address = forms.CharField(label='Street Address', required=False) city = forms.CharField(label='City', required=False) state = forms.ChoiceField(choices=STATES, label='State', widget=forms.Select(), required=False) zipcode = forms.CharField(label = 'Zip Code', required=False) sendPromo = forms.BooleanField(label='Sign up to receive Promotions!', required=False) def clean_email(self): email = self.cleaned_data.get('email') try: match = UserInfo.objects.get(email=email) print(match) except UserInfo.DoesNotExist: return email raise forms.ValidationError('This email address is already in use.') def getFirstName(self): return self.cleaned_data.get('first_name') def getLastName(self): return self.cleaned_data.get('last_name') def check_passwords(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 != password2: raise forms.ValidationError('Passwords do not match.') return password2 And my models.py: class UserInfo(AbstractUser): '''REQUIRED_FIELDS = ('first_name', … -
Parsing json returned in django modelformset in template
One of the fields returned to my template in a formset generated by modelformset_factory() is a JSONField. I'd like to parse the json and display elements in it separately within the form, read-only. This is readily done if I just return the queryset list, using a builtin filter I created, get(). But it has to be in a form that has some added fields for users to fill. {% for foo in foo_list %} <h5>{{ foo.json|get:"title" }}</h5> {% endfor %} The problem is that doing the same for a formset field I get the error "'BoundField' object has no attribute 'get'" {% for form in formset %} <h5>{{ form.json|get:"title" }}</h5> {% endfor %} Here is the filter: @register.filter(name='get') def get(d, k): print('get(d,k):',d,k) return d.get(k, None) The relevant bits of the view: ... foo_list = Foo.objects.all() ... FooFormset = modelformset_factory( Foo, fields = ['task_id','authority','dataset','place_id', 'authrecord_id','json'], form=FooModelForm, extra=0) formset = FooFormset(request.POST or None, queryset=foo_list) context['formset'] = formset ... return render(request, 'datasets/review.html', context=context) -
Pass parameter to a function-based view from the forms.py in Django
Good day. I have a function-based view and would like to know how to pass the self.update parameter that is in my forms.py exactly in the init function. Form.py class AnuncioForm(forms.ModelForm): justificacion = forms.CharField(widget=forms.Textarea) motivo = forms.ModelChoiceField(queryset=Catalogo.objects.filter(tipo=MOTIVO_DE_RECTIFICACIONES)) class Meta: model = Anuncio def __init__(self, *args, **kwargs): self.update = kwargs.pop('update', None) # THIS PARAMETER super(AnuncioForm, self).__init__(*args, **kwargs) if self.update: self.fields['motivo'].required = True self.fields['justificacion'].required = True Function-Based Views: def Anuncio_create_update(request, pk=None): if pk: anuncio = Anuncio.objects.get(pk=pk) nave = anuncio.nave navefoto = NaveFotos.objects.filter(nave_id=nave.id).first() tipo_navefoto = TipoNave.objects.filter(anu_tipo_nave=anuncio.id).values_list('foto') historial_anuncio = anuncio.historialedicionanuncios_set.all().select_related('usuario').order_by('-fecha').all() update = True anuncio_tmp = anuncio.has_bodega_reporte() tiene_bodega = anuncio_tmp[0] title_meta = u'Anuncio de Naves: Actualización' title = u'Anuncio de Naves' nav = ( ('Panel Mando', '/'), ('Anuncio de naves', reverse('anuncio_list')), (u'Actualización', '') ) # muelle = TarjaMuelle.objects.filter(anuncio=pk, tipo_autorizacion=COMUN_SALIDA) # if muelle is not get_es_directo(tipo_operacion=OPE_EMBARQUE_INDIRECTO): # pass else: anuncio = Anuncio() tiene_bodega = False update = False title_meta = u'Anuncio de Naves: Registro' title = u'Anuncio de Naves' nav = ( ('Panel Mando', '/'), ('Anuncio de Naves', reverse('anuncio_list')), ('Registro', '') ) unidad_operativa_id = request.session.get(SESION_UNIDAD_OPERATIVA_ID) tipo_nave = TipoNave.objects.all().values_list('id', 'descripcion') tipo_trafico = Catalogo.objects.filter(tipo='16').values_list('id', 'nombre') lineas = Catalogo.objects.filter(tipo='02').values_list('id', 'nombre') lista_tipo_carga = get_tipo_carga() # formset AnuncioBodegaFormSet = inlineformset_factory( Anuncio, AnuncioBodega, extra=0, can_delete=True, fields=( 'anuncio', 'bodega', 'total', 'bultos', 'id') ) … -
can i make a simple social media web with python,django, Html,bootstrap,jquery
i just wondering if i can make a simple social media web with these: Html five css three java-script J-query bootstrap python Django very basic knowledge about database** i wanna that web just for posting not for Instant Message (IM). what else i need to make it fast without unnecessary code? if any one can advise me how to start my project in the right path i would be so thankful for you. -
Django, Docker, and Pipenv - Error adding new packages
Using Pipenv with Docker is causing some issues in my Django project. I've installed Django locally with Pipenv which generates a Pipfile and Pipfile.lock. Then used startproject to start a new Django project. Then I add a Dockerfile file. # Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY . /code RUN pip install pipenv RUN pipenv install --system And a docker-compose.yml file. # docker-compose.yml version: '3' services: web: build: . command: python /code/manage.py migrate --noinput && /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 And run docker-compose up --build to build the image and start the container. Everything works. Now here's the issue...I want to add a new package, let's say psycopg2 so I can use PostgreSQL. So...update my docker-compose.yml to add PostgreSQL. # docker-compose.yml version: '3' services: db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /code/manage.py migrate --noinput && /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db volumes: postgres_data: And update the DATABASE config in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432 } } Now if I install psycopg2-binary locally like pipenv install psycopg2-binary this "should" sync with Docker. But I … -
What causes the error "Invalid password format or unknown hashing algorithm."?
I see a lot of answers as to how to solve this issue, but I'd like to know what exactly causes this? I have a random password generator that generates a random sequence consisting of uppercase letters, lowercase letters and numbers like this: min_char = 10 max_char = 12 allchar = string.ascii_letters + string.digits genpassword = "".join(choice(allchar) for x in range(randint(min_char, max_char))) This causes the "Invalid password" error and I'd like to know why.