Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Save io.BytesIO pdfrw PDF into Django FileField
What I am trying to do is basically: Get PDF from URL Modify it via pdfrw Store it in memory as a BytesIO obj Upload it into a Django FileField via Model.objects.create(form=pdf_file) My issue is that when the create() method runs, it saves all of the fields except for the form. helpers.py import io import tempfile from contextlib import contextmanager import requests import pdfrw @contextmanager def as_file(url): with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile: tfile.write(requests.get(url).content) tfile.flush() yield tfile.name def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict): template_pdf = pdfrw.PdfReader(input_pdf_path) ## PDF is modified here buf = io.BytesIO() print(buf.getbuffer().nbytes). # Prints "0"! pdfrw.PdfWriter().write(buf, template_pdf) buf.seek(0) return buf views.py class FormView(View): def get(self, request, *args, **kwargs): form_url = 'http://some-pdf-url.com' with as_file(form_url) as temp_form_path: submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"}) print(submitted_form.getbuffer().nbytes). # Prints "994782"! FilledPDF.objects.create(form=File(submitted_form), name="Test PDF") return render(request, 'index.html', {}) As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? -
Read 35 GB file and write into a ZIP file without creating temp file in Django
I have Django app where user selects a file then i read that file, create a write the content in temp file then create a zip out of it. I want to remove the middle step where i create a temp file before creating a zip Here is my upload.html <div class="form-container"> <form method="post" enctype="multipart/form-data" class="my-form" action="/upload-policy" id="my-form"> {% csrf_token %} <h2 class="form-header" style="color: white;">Upload Job</h2> <div class="form-group"> <label for="laf-file"></label> <input required="required" type="file" accept=".*" class="form-control" id="any_file" placeholder="Select File" name="document"> <small class="form-text"></small> </div> <button id="file-btn" type="submit" class="btn-submit btn-primary">Submit</button> </form> Django view.py def upload_job(request): archive_list = [] print(request.data) uploaded_file = request.FILES['document'] # ** document is field from html submit** filename = uploaded_file.name content = uploaded_file.read() # ****reading file**** temp_file = os.path.join(tempPath, filename) with open(temp_file, 'wb') as meta: # ****Write into temp file**** meta.write(content) archive_list.append(temp_file) # **** creating zip of the temp file**** retry_attempt = 0 while True: try: retry_attempt += 1 zipfilepath = os.path.join(tempPath, filename + ".zip") zippedfile = zipfile.ZipFile(zipfilepath, "w", allowZip64=True) for file in archive_list: zippedfile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED) error = zippedfile.testzip() zippedfile.close() break except: if retry_attempt >= 3: raise else: os.remove(zipfilepath) zippedfile = None continue More impotently i also would love to know if i can do this as Ajax request … -
Django model object access in views
I have a view in django which get a value through post request and i want to get a model object using that value as an attribute. View is as: def accessObject(request): if request.method =="POST": value = request.POST.get('value') object = RandomModel.objects.get(value=value) return render(request,template,{'object':object}) I want to know if this is the correct way of doing things in production, because if value is an integer type then the view will throw an error even if object exists. Should I use type conversion every time I write this type of view in django? -
How to display videos in homepage from database in django
I've made a portfolio website with django and bootstrap framework. Now i'm trying to display multiple videos in my homepage. So through admin panel i uploaded 3 videos and in template used video tag. In model FileField for upload and also summary for video description. After setup and runserver my website homepage is showing just video description and video player and controls. There is no such videos or thumbnails to play. Please help me on that matter.enter image description here enter image description here enter image description here -
Creating PDF report in Django with visulaization/graph
I want to create a PDF report when a request is sended to the Django rest API. The things I looked into weasy print that works fine but I didn't really able to include visualization in there such as Histogram, pie/bar chart. Secondly, I looked into report lab and able to create the visualization such as Histogram but they are not good looking and kinda old fashion. I want to have a pdf with some fancy charts like created by Chart.js basically good UI PDF. -
Apply sorting on field in foreign key django rest framework
I have three models: Class Book(models.Model): book_name = models.CharField(max_length=10) author = models.Foreignkey('author', on_delete=models.cascade) Class Author(models.Model): name = models.CharField(max_length=50) addr = models.CharField(max_length=50) Class Bookinfo(models.Model): book = models.ForeignKey('book', on_delete=models.cascade) page_number = models.IntegerField() Serializers are: Class bookserializer(modelserializer): Class Meta: Model= book Fields = ("__all__") Class authorserializer(modelserializer): Class Meta: Model= author Fields = ("__all__") Class bookinfoserializer(modelserializer): Class Meta: Model= bookinfo Fields = ("__all__") Depth=2 Viewset: Class Bookinfoviewset(viewsets.modelviewset): Queryset= bookinfo.objects.all() Serializer_class= bookinfoserializer In the response I get the nested values: { Book_id:{ Book_name: Author_id: { Name: Addr: } }, Page_number: } In the backend I am using PageNumberPagination , searchfilter and ordering. In the book info view, I want to apply ordering on book_name which is inside book_id which is a foreign key. How to do that without affecting filter and pagination. Please help. I am using python 3.5 django 2.2.9 -
__init__() takes 1 positional argument but 2 were given, when adding Latex support to markdown
I'm following this tutorial to add LaTeX support to markdown, and I get this error: init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost/posts/ttttt/ Django Version: 2.2.10 Exception Type: TypeError Exception Value: init() takes 1 positional argument but 2 were given Exception Location: C:\Users\abdom\OneDrive\Desktop\project\wagtailmd\mdx\mdx_mathjax.py in makeExtension, line 23 Python Executable: C:\Users\abdom\OneDrive\Desktop\project.venv\Scripts\python.exe Python Version: 3.7.3 Python Path: mdx_mathjax.py : import markdown import cgi class MathJaxPattern(markdown.inlinepatterns.Pattern): def __init__(self, md): markdown.inlinepatterns.Pattern.__init__( self, r'(?<!\\)(\$\$?)(.+?)\2', md) def handleMatch(self, m): # Pass the math code through, unmodified except for basic entity # substitutions. # Stored in htmlStash so it doesn't get further processed by Markdown. text = cgi.escape(m.group(2) + m.group(3) + m.group(2)) return self.markdown.htmlStash.store(text) class MathJaxExtension(markdown.Extension): def extendMarkdown(self, md, md_globals): # Needs to come before escape matching because \ is pretty important # in LaTeX md.inlinePatterns.add('mathjax', MathJaxPattern(md), '<escape') def makeExtension(configs=[]): return MathJaxExtension(configs) wagtailmd.py : import markdown from django import template register = template.Library() @register.filter(name='markdown') def markdown_filter(value): return markdown.markdown( value, extensions=[ 'wagtailmd.mdx.mdx_mathjax', ], output_format='html5' ) thanks. -
Django Rest Framework Permissions not being called for Detail and List View
I created this custom permission class and it does not seem to be called when I make a request from the view. I event set it to return false and requests are still successful. Tried placing a print statement to see if there would be any output but no. Not sure what I'm doing wring. View: class EventEditView(RetrieveUpdateDestroyAPIView): authentication_classes = ( ) permission_classes = (EventVisibilityPerm, ) serializer_class = EventEditSerializer def get(self, request, *args, **kwargs): event = get_object_or_404(Event, slug=kwargs['slug']) serializer = EventSerializer(event) return Response(serializer.data) Permissions.py: class EventVisibilityPerm(permissions.BasePermission): """ Permission class determines whether a user has access to a specific Event """ def has_object_permission(self, request, view, obj): print('here line 15') return False **Serializer: ** class EventSerializer(serializers.ModelSerializer): class Meta: model = Event exclude = ('user', 'id') Currently testing permissions for this detail view but this permission will also need to be used on a List view. -
Django logging - logging on ValidationError not working
So I want to be able to track any ValidationErrors being raised by the def clean method on a certain form. I have the a form called AdForm, the validation on the form does work, I can see the errors in the html output. The logging also works since I get the logger info in the text file. The strange thing is, I get the notice; 2020-02-11 18:17:43,099 [INFO] .forms: AdForm is called But I don't see the raised validation error in my log files? Is there anything wrong with my settings? For some of you this might be piece of cake but I'm struggling to find my own errors, any help will be appreciated! forms.py from .models import Ad import logging logger = logging.getlogger(__name__) class AdForm(forms.ModelForm) logger.info("AdForm is called") class Meta: model = Ad fields = [ 'title', 'description' ] def clean(self): cleaned_date = super(AdForm, self).clean() title = cleaned_data.get('title') if len(title) < 4: logger.info("Title is shorter then 4 characters") raise forms.ValidationError("Title is too short") if len(title) > 24: logger.info("Title is shorter then 4 characters") raise forms.ValidationError("Title is too long") settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': … -
How to set the default urlpatterns for Django projects
Whenever I start a Django project the url patterns are like this: url(r'^admin/', admin.site.urls) I am using venv and I install the latest version of Django so shouldn't the url patterns default to?: path('admin/', admin.site.urls) In the auto comments at the top of the urls.py file it seems to be referencing Django 1.11 even though I am using 3.03: The urlpatterns list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ -
creating an object based on some conditions in django
I have a model called Showcase that users use to showcase projects. I am trying to implement a case where any administrator in the Administrators field in the showcase can add collaborators through the Collaborator model. When I run my code below, I get name 'APIException' is not defined. models.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) administrator = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="administrators", blank=True) class Collaborator(models.Model): post = models.ForeignKey(Showcase, on_delete=models.CASCADE, related_name="collaborated_showcases") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="collaborators") skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True, related_name="creative_type") role = models.TextField(null=True) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) serializer class CollaboratorSerializer(serializers.ModelSerializer): post = serializers.SlugRelatedField(read_only=True, slug_field='slug') class Meta: model = Collaborator exclude = ['created_on', 'updated_on'] class ShowcaseAdminSerializer(serializers.ModelSerializer): administrator = serializers.SlugRelatedField(slug_field='slug', many=True, queryset=User.objects.all()) class Meta: model = Showcase fields = ['administrator',] def update(self, instance, validated_data): users = validated_data.get('administrator') for user in users: instance.administrator.add(user) return instance views.py class collaboratorCreateView(APIView): ''' add collaborator to a showcase ''' serializer_class = CollaboratorSerializer permission_classes = [IsAdmin] def post(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) try: self.check_object_permissions(request, showcase) collaborator = Collaborator.objects.create( post = showcase ) serializer = self.serializer_class(collaborator, data=request.data, partial=True) … -
increase the column size in template
I can strech(adjust) rows through cursor but problem is i cant do the same for column (as shown in picture) here is the code i used: {% extends "base.html" %} {% block content %} <h2>New Blog</h2><br> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-success ml-2" value="save"> <a class="btn btn-primary" href="{% url 'blog_list' %}" role="button">Cancel</a> </form> {% endblock content %} -
django check if the whole website is idle
My django website connects to a sqlite database. If the website is idle for 3 minutes, I want to disconnect the database file. Can django detect if the website is idle? -
When changing s3 buckets - "The request signature we calculated does not match the signature you provided"
Really struggling with this one. I have the following config: Django/DRF Boto3 Django-storages I am using an IAM user credentials with one set of keys. I have removed all other sets of keys including root keys from my account, to eliminate keys mismatch. Original bucket name was my-staging-bucket. I created that one from django by running python3 manage.py collectstatic. So far so good, I can upload files, download files and delete them as well. Now I wanted to create a new bucket my-prod-bucket. Updated the bucket name settings in my env file. I ran python3 manage.py collectstatic and it created the new bucket without a problem. I can upload and delete however when I try to download a file I get: <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> <AWSAccessKeyId>AKIA6FUWELHPTCYOIUMP</AWSAccessKeyId> <StringToSign> AWS4-HMAC-SHA256 20200211T162650Z 20200211/us-east-1/s3/aws4_request 127b05746c0713faa86b1f1c5c1e135dca82ba5d700211ede1b63f1821bf0b18 </StringToSign> <SignatureProvided> ef92df31dde436a8c43adccb916693d944bacd5ca5258856c3bc18cc655d85bd </SignatureProvided> I'm not sure what I'm doing wrong. I cleared any aws config and env variables from my system. The only env variables are the ones inside the .env file in my local project. Now to add to that, if I delete all buckets, and set the bucket name … -
Templates not found Django
I was trying this project mentioned in "Lightweight Django_ Using REST, Websockets & Backbone [Elman & Lavin 2014-11-13]" but in this i got stuck when my templates are not found can anyone help in this my settings are import os import sys from django.conf import settings DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', '%jv_4#hoaqwig2gu!eg#^ozptd*a@88u(aasv7z!7xt^5(*i&k') ALLOWED_HOSTS = [] BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), INSTALLED_APPS=( 'django.contrib.staticfiles', ), TEMPLATE_DIRS=( os.path.join(BASE_DIR, 'templates'), ), STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', ) my views are def index(request): example = reverse('placeholder', kwargs={'width': 50, 'height':50}) context = { 'example': request.build_absolute_uri(example) } return render(request, 'home.html', context) #and urls are urlpatterns = ( url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$', placeholder, name='placeholder'), url(r'^$', index, name='homepage'), ) and my template order in the folder is - foo - templates - home.html - static - site.css -
Filter option from Enum in Django Admin
The below is my main model. It contains many fields but will concentrate on required 2 fields class CustomAuditType(models.Model): name = models.CharField(max_length=100) type = models.PositiveIntegerField(choices=choices(Type)) Enum class is class Type(Enum): Custom = 0 Generic = 1 Instructions = 2 From this main parent model I'm inheriting in other model using Proxy model inheritance class Instruction(CustomAuditType): class Meta: proxy=True Now coming to our model for which I'm using admin also class CustomAssignment(models.Model): custom_audit_name = models.ForeignKey(Instruction) value_stream = models.ForeignKey(dashboard.ValueStream, null=True, blank=True) category = models.ForeignKey(CustomAuditCategory, null=True, blank=True) user = models.ManyToManyField(User) My admin is class CustomAuditUserAssignmentAdmin(admin.ModelAdmin): list_display = ('custom_audit_name','value_stream','category') filter_horizontal = ['user'] def get_queryset(self, request): queryset = super().get_queryset(request) print('Prashant',queryset) return queryset.filter(type=Type.Custom.value) I am trying to override get_queryset to take only Custom type from CustomAuditType model which is present in type field. So the requirement is I need to only show the Custom type in CustomAuditUserAssignmentAdmin admin in field of Custom Audit Name. Ignoring Instructions and Generic from class Type(Enum) Please help me. Thank you! -
Django CheckConstraint: Elements of reverse ForeignKey lookup must not be empty
I've got these models: class Container(models.Model): ... class Meta: constraints = [ models.CheckConstraint(check=~Q(elements=None), name='container_must_have_elements'), ] class Element(models.Model): container = models.ForeignKey(Container), related_name='elements', on_delete=models.CASCADE ) I want to enforce the constraint that every Container object must have at least one Element referencing it via the foreign key relation. As you can see I already added a check constraint. However, the negation operator ~ on the Q object seems to be forbidden. I get django.db.utils.NotSupportedError: cannot use subquery in check constraint when I try to apply the generated migration. Without the negation operator the constraint seems to be valid (it only fails due to a data integrity error). Is there another way I can express this constraint so it is supported by CheckConstraint? (E.g. is there a way to check if the set of elements is not empty?) -
NoReverseMatch at /login - error with LOGIN_URL or reverse function?
I am developing an app in Django. I am developing users authentication. I have a registration.html and a login.html templates inside path: templates > authentication Everything, including the registering function, works fine, but as I try to access to login template, the browser returns: NoReverseMatch at /login 'app' is not a registered namespace I bet the problem lies in the LOGIN_URL that I added in settings.py to enable authentication system (I am following a tutorial). In fact, all the others view work fine, just the one pointing to login.html is not. Here below are all my lines relating to the authentication system: In my settings.py: LOGIN_URL = '/login' In my base.html: {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">{{ user_form.username }}</a> <div class="dropdown-menu"> <a class="dropdown-item" href="">profilo</a> <a class="dropdown-item" href="{% url 'logout' %}">Log out</a> </div> </li> {% elif not user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Login</a> <div class="dropdown-menu"> <a class="dropdown-item" href="{% url 'registration' %}">Registrati</a> <a class="dropdown-item" href="{% url 'login' %}">Accedi</a> </div> </li> {% endif %} In my app > urls.py, Inside urlpatterns list: path('authentication/registration', views_users_authentication.registration, name="registration"), path('login', views_users_authentication.user_login, name="login"), in my project > urls.py, Inside urlpatterns list: path('admin/', … -
ModelSelect2Widget gives empty dropdowns
I've created a template, view, form and model, that the models are all synced at one by foreign keys, and now I need to select 3 dropdowns depending on the choices that I have defined on the previous dropdowns, but after doing that the dropdowns are empty with no data, but the querysets are there as well as the form.media.js and the form.media.css. Bellow are the forms and models. class GoodDistributorLocationCreateForm(ModelForm): good = ModelChoiceField( queryset=Good.objects.all(), label=u"Good", widget=ModelSelect2Widget(model=Good, search_fields=['name__icontains'],), ) distributor = ModelChoiceField( queryset=Distributor.objects.all(), label=u"Distributor", widget=ModelSelect2Widget( model=Distributor, search_fields=['name__icontains'], dependent_fields={'good': 'good'}, ), ) location = ModelChoiceField( queryset=Location.objects.all(), label=u"Location", widget=ModelSelect2Widget( model=Location, search_fields=['address__icontains'], dependent_fields={'distributor': 'distributor'}, max_results=500, ), ) class Meta: """Add good distributor location form.""" model = GoodDistributorLocation fields = ['good', 'distributor', 'location', 'price'] def __init__(self, *args, **kwargs): """Initialize form for setting good distributor location request fields.""" super(GoodDistributorLocationCreateForm, self).__init__(*args, **kwargs) self.fields['good'].required = True self.fields['distributor'].required = True self.fields['location'].required = True self.fields['price'].required = True Models: class Good(models.Model): TYPE_TUKTUK = 0 TYPE_CHOICES = ((TYPE_TUKTUK, 'TukTuk'),) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) good_type = models.IntegerField(choices=TYPE_CHOICES, default=TYPE_TUKTUK) brand = models.CharField(max_length=255, blank=True) def __str__(self): """ Unicode representation for a Good model. :return: string """ return '{} - {}'.format(self.name, self.get_good_type_display()) @property def shortened_id(self): """Get shortened version of id.""" return … -
How can I initialise group names in Django every time the program runs?
I have this code and I want it to just create the groups every time the program runs so that if the database is deleted it will still be a sufficient program itself and someone won't have to create groups again, do you know an easy way to do this? system_administrator = Group.objects.get_or_create(name='system_administrator') manager = Group.objects.get_or_create(name='manager') travel_advisor = Group.objects.get_or_create(name='travel_advisor') -
django configure multiple upload buttons to transfer file to s3
I want to upload multiple files from multiple upload buttons to s3 from django.I know basic concept for uploading files to s3 for single upload buttons..how can we apply same concept if we have more than one upload buttons at a same time?(I used post method to send the files to s3) -
did an upgrade on KIWI I am using DOCKER container to run with now my manage.py fails for django asserts
I did an upgrade per the documentation at https://kiwitcms.readthedocs.io/en/latest/installing_docker.html Upgrading Steps to Reproduce cd Kiwi/ git pull # to refresh docker-compose.yml docker-compose down make docker-image if you build from source or docker pull kiwitcms/kiwi # to fetch latest version from Docker Hub docker pull centos/mariadb # to fetch the latest version for MariaDB docker-compose up -d docker exec -it kiwi_web /Kiwi/manage.py migrate Actual results When I run docker exec -it kiwi_web /Kiwi/manage.py migrate I get an assert of: sudo docker exec -it kiwi_web /Kiwi/manage.py migrate Traceback (most recent call last): File "/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/venv/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect return Connection(*args, **kwargs) File "/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Kiwi/manage.py", line 12, in execute_from_command_line(sys.argv) File "/venv/lib/python3.6/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/venv/lib/python3.6/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv … -
Making Django migrations backwards compatible with SQL-Server
We have a Django application that previously only used Postgres as its DB backend. Now a client would like to use the application with MS SQL-Server. Previously, a developer added a unique constraint on a text field. It's a small table, so the index doesn't overwhelm things, and of course Postgres thinks this is fine, so testing didn't detect any problems. We have an existing release (several releases back, in fact), that includes a migration to add that constraint. Let's say this was called app/migrations/0002_add_unique.py Now we get the request for SQL-Server compatibility. We added a site configuration option to let an installer specify the DB engine as well as the connect string, so you can pick MS SQL-Server rather than Postgres, but of course migrations breaks when it tries to create the database in SQL-Server. Migrations has to run in the correct order, so SQL-Server blows up trying to add the illegal constraint before it gets to the migration that either removes the constraint or changes the text field to a long varchar. We solved this in the current release candidate by modifying the old 0002_add_unique.py migration so that it doesn't add the uniqueness constraint. There is also a … -
windows10 workon "env_name" no response
I'm using python 3.8.1 to build a django project using virtualenv I create my virtualenv by "mkvirtualenv my_django_environment" after that i use "workon" command and i can see this env really created. and when i tried to activate it , it just shows nothing, just like below: C:\Users\User>workon Pass a name to activate one of the following virtualenvs: my_django_environment C:\Users\User>workon my_django_environment C:\Users\User>python it just didn't happen anything! but i try this on my laptop (windows 10) it work well. i have no idea how to solve this. -
Django - Cannot test request as authenticated user with django-allauth
I have a new django project (2.2), a custom user model and django-allauth to manage user registration (not via social, just with the email confirmation) and I'm trying to test some protected views. In the setUp method of the test I create a new user and create a new EmailAddress (from allauth.account.models) with verified and primary set to True. Next I try to login with: self.client.login(username=username, password=password) and I get True so everything is working so far and the user is logged. Now if I try to get any views that requires login I always get a 301 redirect to the login page! I looked around but didn't find a solution to my problem so far. Let me show you some code: user creation in setUp username = 'test@test.com' password = 'testtesttest' new_user = User.objects.create_user( username=username, email=username, password=password, ) new_user.save() new_user.is_active = True new_user.save() new_email_address = EmailAddress( user_id=new_user.id, email=username, verified=True, primary=True, ) new_email_address.save() login and test logged in logged_in = self.client.login(email=username, password=password) self.assertTrue(logged_in) # and this works as expected Now if I try to request a view that requires login: response = self.client.get("/protected") I get <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/protected/"> What am I doin't wrong? Thanks in advance for the …