Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django is not sending e-mails
guys! I have an issue with my Django project. About project: Django version: 3.0.7 Django hosting provider: Digitalocean E-mail hosting provider: Beget.com OS: Ubuntu 18.04.6 Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.beget.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'my@email.com' EMAIL_HOST_PASSWORD = 'MyVerySecretPassword' DEFAULT_FROM_EMAIL='my@email.com' Here is my views.py from django.core.mail import send_mail def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Please, activate your account by clicking the link below.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') send_mail(mail_subject, message, settings.DEFAULT_FROM_EMAIL, [to_email]) What I have tried to solve my problem: Using gmail account (yes, with anabled 'Allow less secure apps') Sending via Django shell (nope, it returns code '1', the mailbox is as empty as my ideas:( ) I have opened 587 and 465 ports in ufw I tried to write and run simple python smtp script to send e-mail via Django shell (spoiler: it worked perfectly on my server via shell), but when I tried to implement this code into my Django code, it failed just like Django send_mail() function: here is the code: import … -
for loop to populate a django template table
I'm trying to make a table in Django template. I'm sending a dict as my data inside my views.py like this: data = { "year_most_launches": result_launches, "launch_sites":result_sites, "launches_2019_2021":result_2019_2021 } return render(request,"main/launches.html", {"data":data}) My table in HTML code: <table class="table"> <thead> <tr> <th>Year with most launches</th> <th>Launch site with most launches</th> <th>Number of launches between 2019 and 2021</th> </tr> </thead> <tbody> {% for element in data.values %} <tr> <td>{{ element }}</td> </tr> {% endfor %} </tbody> </table> My problem is that the values of data just appears in the first columm, creating 3 rows instead of just appearing in the first row. How can I solve that? It is a problem inside my html? -
How to replace port 8000
I'm working on a project now and I'm currently using Django+uWSGI+Nginx to deploy the backend on the server. There is also a frontend using Vue.js on the same server. So the frontend is www.mysite.com The backend uses port 8000 as www.mysite.com:8000 But I encountered a problem, that is, many users' work network blocked port 8000, so that users could only use the front end, but could not connect to the back end. Is there any way to avoid using www.mysite.com:8000 and replace it with another url? -
django rest framework RetrieveUpdate
I'm now making user profile update API using drf with RetreiveUpadteAPIView there is one question I cant' figure out what the solution is. With this logic, request datas are well updated on DB. Only password given is set without hashed but just normal character. even that changed normal character password is also not matched as with i set. How can i fix it.. your best regard Here is my code below. #views.py @permission_classes([IsAuthenticated]) class UpdatePartialUserView(RetrieveUpdateAPIView): queryset = User.objects.all() serializer_class = UserProfileSerializer def get_object(self): queryset = self.filter_queryset(self.get_queryset()) obj = queryset.get(pk=self.request.user.id) self.check_object_permissions(self.request, obj) return obj def retrieve(self, request, *args, **kwargs): serializer = UserSerializer(request.user) return Response(status=status.HTTP_200_OK, data = serializer.data) def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) self.object = self.get_object() serializer = self.get_serializer(request.user, data = request.data, partial=partial) # serializer = self.get_serializer(self.object, data = request.data, partial=partial) if not serializer.is_valid(raise_exception=True): return Response(status=status.HTTP_409_CONFLICT, data = {'message':serializer.errors}) self.perform_update(serializer=serializer) self.object.set_password(request.data['password']) self.object.save() return Response(status=status.HTTP_202_ACCEPTED, data={"message": "success!"}) #serializers.py class UserProfileSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) profile_img = serializers.ImageField(use_url=True, required = False) def validate(self, attrs): if attrs.get('password') != attrs.get('password2'): raise serializers.ValidationError({ "password" : "비밀번호가 다릅니다."}) return attrs def validate_old_password(self, value): #check user request = self.context.get('request') if request and hasattr(request, "user"): user = request.user … -
Django renders the HTML file without including static files(CSS styles, images)
There I have tried to render the HTML file html_message = get_template('mail.html').render(context=data) email = EmailMultiAlternatives( "Subject", html_message, settings.EMAIL_HOST_USER, ['example@gmail.com', ], ) email.attach_alternative(html_message, 'text/html') email.send(fail_silently=False) The HTML file {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Title</title> <link rel="stylesheet" href="{% static 'mail.css' %}"> </head> <body> <header> <div> <img class="logo" src="{% static 'logo.svg' %}" alt=""> </div> </header> </body> As the Result HTML file was rendered without static files -
Questions about moving from Django ro DRF [closed]
I've completed my little project in Django for imaginary company where users have different roles from seller to top manager and bunch of tables containing users, products, orders, contractors, reports and of course I made a whole lotta class-based CRUDs and other views. The questions are: I wanna learn Django REST framework and as far as I can tell it has it's own way of doing CRUD operations as well as authorization. Do I have to replace all my CRUDs with the new ones from DRF? And what about my User model? Can I keep it and just set up a DRF authorization on top of it? What parts of standard Django project should be replaced? Thanks! -
how to return couple of variables in models.py
i need to return shop_nama nad adress to django site administration, here's the code shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') def __str__(self): return self.shop_name but it shows error when i type return self.shop_name, self.adress error says: str returned non-string (type tuple) sooo how to fix this problem? -
how to use msg91 in django?
def send_email(request): conn = http.client.HTTPSConnection("api.msg91.com") payload = "{\r\n\"to\": [\r\n{\r\n\"name\": \"Test\",\r\n\"email\": \"email\"\r\n}\r\n],\r\n\"from\": {\r\n\"name\": \"Joe\",\r\n\"email\": \"email\"\r\n},\r\n\"domain\": \"my domian name\",\r\n\"mail_type_id\": \"1\",\r\n\"template_id\": \"mytemplate-name\",\r\n\"variables\": {\r\n\"VAR1\": \"12345\",\r\n\"VAR2\": \"1234\"\r\n},\r\n\"authkey\": \"myauthkey\"\r\n}" headers = { 'Content-Type': "application/JSON", 'Accept': "application/json" } conn.request("POST","/api/v5/email/send",payload,headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) return None -
Showing Operation object (1) when trying to get foreignkey django
I am trying to post a table in HTML and i get This "Operation object (1)" insted of just the id "1" How is posible to fix this as you can see in the picture where is selected i want to have the id not text models.py operationID = models.IntegerField(primary_key=True) assignee = models.ForeignKey('Employee', on_delete=models.CASCADE) dateRegistered = models.DateTimeField(auto_now_add=True) timeStart = models.DateTimeField(auto_now_add=True, null=True) timeFinish = models.DateTimeField(null=True) status = models.ForeignKey( 'Status', on_delete=models.CASCADE) class Subtask(models.Model): subtaskID = models.IntegerField(primary_key=True, auto_created=True) operationID = models.ForeignKey('Operation', on_delete=models.CASCADE) containerID = models.CharField(max_length=255) containerWeightT = models.DecimalField(max_digits=6, decimal_places=2) loadSeq = models.IntegerField() moveTo = models.ForeignKey('MoveTo', on_delete=models.CASCADE) stow = models.ForeignKey('Stow', on_delete=models.CASCADE) status = models.ForeignKey( 'Status', on_delete=models.CASCADE)``` views.py ```def displaydata(request): results1 = Subtask.objects.prefetch_related( 'moveTo', 'operationID', 'stow', 'status').all() return render(request, 'ee.html', {'Subtask': results1})``` [website][1] [1]: https://i.stack.imgur.com/cWFdd.png -
remove div only on one page in Django template
I have a website that contains 15 seperate pages. On each page I have a div named header. Right know I am removing this element via JavaScript like this: homepage.html <script> const element = document.getElementById('header'); element.remove(); </script> The problem is that I can see the header element for a second before it is removed. The script is placed on the top of the page. I also tried to do it via css like this: .header { height: 0rem !important; visibility: hidden !important; } However, I still see the element disappearing when refreshing the page. I know that I could create a template block in my base.html file and just exclude it in the homepage.html page but I'd need to include it in the other 14 HTML files manually. Question Is there any other/better way to exclude div so I don't see it at all on my homepage? -
Django, django-filter and pagination
my goal is to have a 'user_profile' page that displays relevant information of the user of interest. Furthermore, the 'user_profile' page should include all the posts that were created by the respective user as new blog entries. These posts, however, should be filterable with the application 'django-filter' and be paginated. At the moment I have difficulties to paginate the filtered posts. So my question is how to achieve the latter? So far, I used following approach: filters.py import django_filters class AccountPostFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') category = django_filters.ChoiceFilter(choices=cat_list) class Meta: model = Post fields = ['title', 'category'] views.py class UserProfile(DetailView, MultipleObjectMixin): model = Account template_name = 'account/user_profile.html' paginate_by = 5 def get_context_data(self, **kwargs): posts = Post.objects.all().filter(author=self.kwargs['pk']) context = super().get_context_data(object_list=posts, **kwargs) context['filterset'] = AccountPostFilter(self.request.GET, queryset=posts) return context Thank you very much for your time. Best wishes, Daniel -
Django ElasticBeanstalk Deploy- error deterministic=True requires SQLite 3.8.3 or higher
so, i deployed my application in my local venv i did python make migrations python migrate and i did eb deploy and eb status the helth returned green so its working, but when i enter the web site it returns deterministic=True requires SQLite 3.8.3 or higher Note: Locally it works just fine commands that i ran to make my project: python manage.py mamemigrations python manage.py migrate python manage.py createsuperuser eb init python-3.8 Naameofmyproject eb create Nameofmyproject Requirments.txt: asgiref==3.5.0 autopep8==1.6.0 certifi==2021.10.8 charset-normalizer==2.0.12 dj-database-url==0.5.0 Django==4.0.3 django-anymail==8.5 django-autoslug==1.9.8 django-crispy-forms==1.14.0 django-environ==0.8.1 django-model-utils==4.2.0 idna==3.3 Pillow==9.1.0 psycopg2-binary==2.9.3 pycodestyle==2.8.0 python-dateutil==1.5 requests==2.27.1 six==1.16.0 sqlparse==0.4.2 stripe==2.70.0 toml==0.10.2 tzdata==2022.1 urllib3==1.26.9 settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' STATICFILES_DIRS = [BASE_DIR / 'templates/static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' CART_SESSION_ID = 'cart' AUTH_USER_MODEL = 'account.UserBase' LOGIN_REDIRECT_URL = '/account/dashboard' LOGIN_URL = '/account/login/' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' -
numpy heroku error: legacy-install-failure
I'm trying to deploy django webapp on heroku but getting error: legacy-install-failure on numpy package. Building on Heroku-20 stack, default python-3.10.4, pip 22.0.4. note: This is an issue with the package mentioned above, not pip -
OSX monterey -> ld: library not found for -lintl
When pipenv install uwsgi This error comes, ld: library not found for -lintl I guess it requires X-code library ? I tried this as well $xcode-select --install xcode-select: error: command line tools are already installed, use "Software Update" to install updates However it is already installed. How can I solve this? -
I tried to add sub frontend project in my templates but I got error "MIME checking is enabled."?
goal I have two frontend project and I want to do create a new folder called build_2 inside my templates folder. inside the build_2 have index.html file and it was working just fine problem but where I added <link href="my_styles.css" rel="stylesheet"> I got this error Note: the directory myProject/home/templates/static/css/my_styles.css full error message: Refused to apply style from 'http://127.0.0.1:8000/css/my_styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. I tried add #settings.py TEMPLATES['DIRS'].append(os.path.join(BASE_DIR, 'home/templates/build2'), os.path.join(BASE_DIR, 'home/templates')) add STATICFILES_DIRS.append(os.path.join(BASE_DIR, 'home/templates/static')) but I am still getting the same error? -
download and add files in vuejs and django
how can i add a file in my front end vuejs and download my file from my backend django rest framework with v-model in vuejs my modele is article , class Article(models.Model): conference = models.ForeignKey(Conference,related_name='articles',on_delete=models.CASCADE) title =models.CharField(max_length=50) Auteur =models.CharField(max_length=50) resume =models.TextField() motcles =models.TextField() create_by = models.ForeignKey(User, related_name='articles',on_delete=models.CASCADE) fichier = models.FileField(upload_to='uploads',blank=True, null=True) def __str__(self): return self.title this code is about how i add a new article , i should here add how to enter a file <form v-on:submit.prevent="submitArticle()"> <div class="field"> <label class="label">Title</label> <div class="control"> <input type="text" class="input" v-model="article.title"> </div> </div> <div class="field"> <label>Auteur</label> <div class="control"> <input type="title" class="input" v-model="article.Auteur"> </div> </div> <div class="field"> <label class="label">Resume</label> <div class="control"> <textarea type="text" class="input" v-model="article.resume"></textarea> </div> </div> <div class="field"> <label>motcles</label> <div class="control"> <input type="title" class="input" v-model="article.motcles"> </div> </div> <div id="app"> <a href="#" @click.prevent=" downloadItem({ url: 'https://test.cors.workers.dev/?https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', label: 'example.pdf', }) " > download </a> </div> <div class="field"> <div class="control"> <button class="button is-link">submit</button> </div> </div> </form> this is how i enter my article submitArticle() { console.log('submitArticle') const conferenceID = this.$route.params.id this.errors = [] if (this.article.title === '') { this.errors.push('The title must be filled out') } if (this.article.resume === '') { this.errors.push('The content must be filled out') } if (!this.errors.length) { axios .post(`/api/v1/add-article/${conferenceID}/`, this.article) .then(response => { this.article.title … -
Django - Permissions in file upload
I'm trying to build a file sharing application using Django REST Framework in the backend. In order to upload files, I have the following field in my models: user_file = models.FileField() However, when a user uploads a file, that file is stored in the directory of the DRF project, and if I put the path of that file in a browser, every user can then access it as well. How can I prevent this? I've thought of having an Apache HHTPd server where there would be a folder for each user and when a user tries to access a file that was not uploaded my them, the backend would do that verification and would not allow it, but I don't know if that would solves the problem? How can I do this? Thanks -
Django - Show all ForeignKeys belonging to the given ID as a select multiple field
I have this model: class OrderProduct(models.Model): order = models.ForeignKey(to=Order, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) price_paid = models.DecimalField(max_digits=5, decimal_places=2) @property def total_value(self): return self.price_paid * self.quantity def __str__(self): return f"{self.order.id} / {self.order.user} // {self.product.name} / {self.quantity} ks" def save(self, *args, **kwargs): self.price_paid = self.product.price super(OrderProduct, self).save(*args, **kwargs) This is my form: class ChangeOrderProductForm(ModelForm): class Meta: model = OrderProduct fields = ('product',) This is my view: def change_orderproduct(request, order_id: int): set_session_cookie_restraunt_status(request) if not check_if_user_has_permission(request, 'kitchen.change_orderproduct'): messages.warning(request, 'Unauthorized to perform this action.') return redirect("index") ordered_products = OrderProduct.objects.filter(order__pk=order_id).first() order = Order.objects.filter(pk=order_id).first() if not order: messages.info(request, "Given order does not exist.") return redirect(request.META.get('HTTP_REFERER', index)) if request.method == "GET": form = ChangeOrderProductForm() context = { "form": form, "order": order } return render(request, "kitchen/change_orderproduct.html", context=context) if request.method == "POST": form = ChangeOrderProductForm(data=request.POST, instance=ordered_products) if form.is_valid(): form.save() messages.success(request, f"Products in order {order.pk} were successfully changed.") return redirect(request.META.get('HTTP_REFERER', all_orders_view)) The code above works, but it only allows you to choose 1 Product in the ChangeOrderProductForm view: However, there are multiple products for almost all Order instances. How do I make it to: Show all the possible Product instances to choose from in the form? Make the already existing ForeignKeys assigned to OrderProduct as the pre-selected ones? … -
find top performing list of category which have highest number of orders in django
models.py class Line_items(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey('Products' , on_delete=models.DO_NOTHING ) class Products(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=400 , blank=True) category = models.ManyToManyField('Categories', through='Product_Categories', related_name='products') class Categories(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100 , blank=True) slug = models.CharField(max_length=200 , blank=True) class Product_Categories(models.Model): id = models.AutoField(primary_key=True) product_id = models.ForeignKey(Products, on_delete=models.DO_NOTHING) category_id = models.ForeignKey(Categories, on_delete=models.DO_NOTHING) here are my models. where line_items contains number of orders done till now. in line_items we have connect product id with product table. but we don't have any connetion from product table to category table. ( category table contains every category and their id ). to connect product table with category table we have created new table 'product_categories' which connects each category with their respective product. here what we want is top performing category. category which have highest number of orders. thanks -
TypeError: hasattr(): attribute name must be string (Django)
Hi how to solve this issue, when i am excluding this code i am getting this type error. my admin.py is this, list_display = [ "id", exclude==("mode_of_action",)] -
AWS Lambda, An error occurred (InvalidToken) when calling the PutObject operation: The provided token is malformed or otherwise invalid
I made a Django application and tried to deploy it using Zappa and AWS Lambda. My deployment was successfully deployed but, the image was not uploaded to AWS S3 to invoke the API. This is my cloudwatch error log [ERROR] 2022-04-22T08:35:19.84Z cbf18c70-f478-4363-8f5a-0777c76564e9 Internal Server Error: /production/v1/ReviewCamping/ Traceback (most recent call last): File "/var/task/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/var/task/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/task/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/var/task/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/var/task/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/var/task/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/var/task/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/var/task/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/var/task/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) File "/var/task/service/views/v1/camping.py", line 80, in perform_create serializer.save(owner=self.request.user) File "/var/task/rest_framework/serializers.py", line 212, in save self.instance = self.create(validated_data) File "/var/task/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/var/task/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/task/django/db/models/query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "/var/task/django/db/models/base.py", line 806, in save self.save_base( File "/var/task/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/var/task/django/db/models/base.py", line 1000, in _save_table results = self._do_insert( … -
Is it possible to link multiple models to one fiel in django?
Let's say I have these models: class Material(models.Model): name = models.CharField([...]) class Consumable(models.Model): name = models.CharField([...]) restores = models.IntegerField([...]) class Weapon(models.Model): name = models.CharField([...]) damage = models.IntegerField([...]) # And then I have an 'inventory', like this one: class Inventory(models.Model): user = models.ForeignKey([...]) # to which user you want to link the item item = models.ForeignKey([...]]) # which item quantity = models.IntegerField([...]) # how many of it I want to be able to have all Material, Consumable, and Weapon models listed in the 'item' field, so when you want to add an item as an inline, you would see all 3 models' objects. Something like # instead of this item = models.ForeignKey(Consumable) # which item # want something like this item = models.ForeignKey(Consumable and Material and Weapon) # which item # this wouldn't work ofc... Is there a way to collect all 3 of them and pass them to the 'item' field, without the need of restarting the server? (when making a "choices" list that queries from a model you must restart the server to see the newly added objects, I don't want that.) I also want to stick to the built-in admin of Django since it provided everything I need … -
How to add similar key value in python?
Sorry if you find the question misleading This is the array of data: [{'user': 1, 'coins': 2}, {'user': 18, 'coins': 8}, {'user': 1, 'coins': 1}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}, {'user': 18, 'coins': 0}] Expected Outcome: [{'user': 1, 'coins': 3}, {'user': 18, 'coins': 8}, {'user': 3, 'coins': 1}, {'user': 5, 'coins': 1}, {'user': 7, 'coins': 0}] So, there will be an array of those data, and we have to add the coins to similar user which can be identified by user key value. If user key have similar value that is 1 (in above case) then coins of both or multiple user must be added making it a total sum of that user coins. -
Password validation with CustomUser Django
I am trying to validate a password against CustomUser fields: email and full_name. All test validations are working except for UserAttributeSimilarityValidator, which is the only test that I have included with the code below. forms.py class RegistrationForm(forms.ModelForm): email = forms.EmailField(label=_('Email address'), widget=forms.EmailInput(attrs={'class': 'form-control mb-4', 'class': 'form-control mb-4', })) full_name = forms.CharField(label=_('Full name'), widget=forms.TextInput(attrs={'class': 'form-control mb-4', })) password = forms.CharField(label=_('Password'), widget=forms.PasswordInput(attrs={'class': 'form-control mb-4', 'autocomplete': 'new-password', 'id': 'psw', })) class Meta: model = get_user_model() fields = ('full_name', 'email', 'password') def clean_password(self): password = self.cleaned_data.get("password") if password: try: password_validation.validate_password(password, self.instance) except ValidationError as error: self.add_error("password", error) return password def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise forms.ValidationError( mark_safe(_(f'A user with that email already exists, click this <br><a href="{reverse("account:pwdreset")}">Password Reset</a> link' ' to recover your account.')) ) return email tests.py @override_settings( AUTH_PASSWORD_VALIDATORS=[ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 'OPTIONS': { 'user_attributes': ( 'email', 'full_name', )}, }, ] ) def test_validates_password(self): data = { "email": "jsmith@example.com", "full_name": "John Smith", "password": "jsmith", } form = RegistrationForm(data) self.assertFalse(form.is_valid() self.assertEqual(len(form["password"].errors), 1) self.assertIn( "The password is too similar to the email.", form["password"].errors, ) Which results in this test result: FAIL: test_validates_password (account.tests.test_forms.RegistrationFormTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/tester/Documents/dev/test/venv/lib/python3.8/site-packages/django/test/utils.py", line 437, in inner return func(*args, **kwargs) File "/Users/tester/Documents/dev/test/account/tests/test_forms.py", line 112, in … -
How to make files available not in "/static/", but in "/app/static/"?
I have Django 1.11 project structure like this: project static img1.png app static img2.png File "settings.py" contains: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] Images are available at: my-site.com/static/img1.png my-site.com/static/img2.png But I want the images to be available in a different way: my-site.com/app/static/img1.png my-site.com/app/static/img2.png I can write to a file "project/app/urls.py": urlpatterns += static('static/', document_root=os.path.join(BASE_DIR, 'app' + STATIC_URL)) And then "img2.png" will be available, but not "img1.png". How can I make "img1.png" available?