Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change React frontend and Django backend to load as one Heroku application
I've built a React frontend in the style of this tutorial: https://codeburst.io/react-image-upload-with-kittens-cc96430eaece (source code here) This is connected to a Django backend (already had experience with Django, so don't have an example tutorial there). Running the frontend and backend locally works fine. Now I want to deploy it as one application to Heroku, so I followed this tutorial about how to do this: https://www.youtube.com/watch?v=r0ECufCyyyw (source code here) I configured the Django application exactly like in the video tutorial. The application builds successfully but the page is empty. I think it might be because I didn't use routers in the React application, but I don't know what exactly it's supposed to do so that the code in App.js gets called. Any suggestions greatly appreciated - I'm not sure where to start and I've found so many ways to write a React app I'm having trouble separating important differences from the inessential. -
how to get column names from a Django object list
I'm trying to generate some tables based on Django models to make them modifiable and alter the database, and since i have more than 200 tables i'm trying to generate them automatically instead of hardcoding each one. in this example i'm trying to get the table columns in django template so i can generate the table with for loops only. here is my views.py class bclist(ListView): template_name = "table2.html" queryset = BaseCase.objects.all() and here is my template <table border="1px"> <tr> <th>Base Case Name</th> <th>version</th> <th>default</th> </tr> {% for instance in object_list %} <tr> <td>{{ instance.base_case_name }}</td> <td>{{ instance.version }}</td> <td>{{ instance.default }}</td> <td><a href='/{{ instance.pk }}/update' >edit</a></td> <td><a href='/{{ instance.pk }}/delete' >delete</a></td> </tr>{% endfor %} </table> my models.py class BaseCase(models.Model): base_case_name = models.CharField(primary_key=True, max_length=255) version = models.TextField(blank=True, null=True) default = models.IntegerField(blank=True, null=True) -
Using google-search package in Django
Iam trying to make the google-search package work in my Vagrant virtualenv, which runs my Django app. When the package is installed directly in the machine the methods in the package are listed properly when i list them using dir command: FDLMC1716:python prasannab$ python3.6 Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import googlesearch >>> dir(googlesearch) ['BeautifulSoup', 'LWPCookieJar', 'Request', 'USER_AGENT', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'cookie_jar', 'filter_result', 'get_page', 'get_random_user_agent', 'gzip', 'hits', 'home_folder', 'install_folder', 'is_bs4', 'lucky', 'math', 'ngd', 'os', 'parse_qs', 'quote_plus', 'random', 'search', 'search_apps', 'search_books', 'search_images', 'search_news', 'search_shop', 'search_videos', 'sys', 'time', 'url_home', 'url_next_page', 'url_next_page_num', 'url_search', 'url_search_num', 'urlopen', 'urlparse', 'user_agents_file', 'user_agents_list'] >>> I installed the same package in virtualenv all the methods in the package are not listed when i list them using dir command: (success) vagrant@ubuntu-xenial:/vagrant/src/success_project$ python3 Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import googlesearch >>> dir(googlesearch) ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__'] >>> Any thoughts on why this is happening ? -
Django models: where should consistency/integrity of databases stay?
Here again, I’m trying to understand Django philosophy for databases. When dealing about consistency in databases, I understand (or understood?) that it refers to constraints, cascades, triggers, etc. at database level, hence a solid database diagram is (or was) very important. But I don’t feel that with Django, it seems that its philosophy is to bring all that consistency to every app in a Django project, and to leave database with relations only. Because when migrating from models to database, not all rules defined in models are taken to database, example: validators. For a moment, let's accept that all business rules are defined in models only. I could (hardly) accept that if it was not because while I was using the database API, no rule (defined in models) applied on every record saved into database, then danger alarms sounded. Here the dilemma: If consistency and/or business rules were defined at database level, why would I need define rules in models again? is it not redundant? If consistency and/or business rules were defined in models, is the database not exposed to concurrency and data integrity problems? In PHP, you interact with database through connectors, consistency/integrity of database is managed by itself. … -
Runtime error when trying to run a Django app
I'm trying to run a django project I worked on a while ago. Most of what I did I've forgotten. I get a run time error when launching the project. I only just imported these files over to my computer. I'm wondering if i'm missing any dependencies? It's been a very long time since I've programmed in django or python. Any help you can offer would be greatly appreciated. C:\Users\Shadow\Desktop\django_project>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Shadow\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named … -
Using models at a project level
I know that this question has been posted a few times in different variations but I'm not satisfied with the answers I found so I will explain you my problem, which I think will be easily solved by someone used to Django. So, I'm a beginner with Django and my problem is that I'm building a food delivery website and I have lots of models such as User, Meal, Order, ... that will be used in all the applications of my project. But, from my very little experience with Django, I understand that the models are defined at an app level, not at a project level. How can I deal with that ? I tried defining some models in an app and importing them in the other apps but I doesn't work : for example, I defined my Client model in the registering app, and my Order model in the ordering app. But when I write "from registering.models import Client" in the Order.models file in order to have a foreign key between Order and Client I have an error saying that it can't find a model Client in the ordering app. I believe there is some way to define the … -
Django migrating foreign keys django.db.utils.OperationalError: (1005, "Can't create table 'asp052mysqlpy.#sql-6ac_56' (errno: 150)") error
I'm trying to migrate a simple foreign key relation for a model in Django, but this results in a very strange and unsolvable error. Error: python manage.py migrate team Operations to perform: Apply all migrations: team Running migrations: Applying team.0001_initial... OK Applying team.0002_auto_20191127_1643...Traceback (most recent call last): File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 255, in execute self.errorhandler(self, exc, value) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 252, in execute res = self._query(query) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\cursors.py", line 378, in _query db.query(q) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\MySQLdb\connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1005, "Can't create table 'asp052mysqlpy.#sql-6ac_56' (errno: 150)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\Mitch\Desktop\teamwork\teamworkapp\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File … -
Datetimepicker in django changing date format from DD/MM/YYYY to MM/DD/YYYY when the forms comes pre-filled
when i want to update a Date in any form, the datepicker is changing from DD/MM/YYYY format to MM/DD/YYYY. When I print the date in the template is in the correct format, but in the Datetimepicker it change. When the date becomes invalid eg: 27/11/2019 to 11/27/2019,the datepicker shows nothing. Here is the code where i configure the datetimepicker for the forms: def __init__(self, *args, **kwargs): super(BaseModelForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): attrs = field.widget.attrs if isinstance(field.widget, forms.widgets.DateInput): attrs['class'] = 'datetimepicker-input form-control' attrs['data-format'] = 'DD/MM/YYYY' attrs['data-toggle'] = 'datetimepicker' attrs['autocomplete'] = 'off' What could be? -
How can I handle multiple forms in generic view?
I want to handle 3 different forms in one UpdateView and I have method post where I choose which form will be in form_class. First 2 of them are depending on if checkbox is selected. Third form is seperated. class MyUpdateView(UpdateView): model = MyModel form_class = Form1 def post(self, *args, **kwargs): is_cyclic = self.request.POST.get('is_cyclic', None) if 'form1' in self.request.POST and not is_cyclic: self.form_class = Form1 elif 'form1' in self.request.POST and is_cyclic: self.form_class = CyclicForm1 elif 'form2' in self.request.POST: self.form_class = Form2 return super().post(*args, **kwargs) In template: <form id="form1" method="post" class="container" action=""> <input type="checkbox" name="is_cyclic" id="cyclic_switch" checked> ... <button type="submit" name="update_form1" value="form1">Save</button> </form> <form name="form2" id="form2-id" method="post" action=""> ... <button form="form2-id" type="submit" name="update_form2" value="form2">Save changes</button> </form> When I'm submitting Form2, I get Form1. How can I fix that? -
List names of required fields in Django Rest Framework serializer (and ignore parent fields)
What I'm trying to do is get a list of all the fields in a serializer which: Do not contain required=False as a parameter. Do not come from the parent serializer. For example, if I have serializers like: class ParentSerializer(serializers.Serializer): parent_field = serializers.IntegerField class ChildSerializer(ParentSerializer): child_field_required = serializers.IntegerField child_field_not_required = serializers.IntegerField(required=False) I'd like the resulting output to be: ['child_field_required'] I've figured out I can get an ordered list of the declared fields like: self.get_serializer().get_fields() >> OrderedDict([ ('parent_field', IntegerField()), ('child_field_required', IntegerField()), ('child_field_not_required', IntegerField(required=False)), ]) But I haven't been able to move past this step. -
Django - ERR_TOO_MANY_REDIRECTS
I have an accounts app with a UserProfile Model in it, that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE) def get_absolute_url(self): return reverse('profiles:help', kwargs={'pk': self.pk}) accounts / urls.py url(r'^(?P<pk>\d+)/help/$', HelpToggle.as_view(),name="help"), accounts / views.py class HelpToggle(RedirectView): def get_redirect_url(self, pk, *args, **kwargs): url_ = obj.get_absolute_url() return url_ django_project / urls.py url(r'^accounts/',include(('accounts.urls','profiles'),namespace='profiles')), but when I go to /accounts/1/help I get a ERR_TOO_MANY_REDIRECTS Error. Thank you for any suggestion -
django.db.utils.IntegrityError while writing APITestCase for my views?
Here I am writing test cases for my views but the test is failing with the following error. django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint DETAIL: Failing row contains (31, permission_name_1, null, perms1). I am writing my own Role model since I needed to change the default ManyToMany relation of Group and User model . class CreateRoleTest(APITestCase): def setUp(self): self.user = User.objects.create_user(username='username',password='passwprd@321',email='email@gmail.com') self.permission = Permission.objects.create(name='permission_name',codename='perms') self.client = APIClient() def test_create(self): url = reverse('roles:create_role') data = {'user':self.user,'permissions':[self.permission.pk],'name':'role_name'} response = self.client.post(url,data,format='json') print(response.json()) return self.assertEqual(response.status_code,status.HTTP_201_CREATED) class UpdateDeleteRoleTest(APITestCase): def setUp(self) -> None: self.client = APIClient() self.user = User.objects.create_user(username='username1', password='passwprd@3211', email='email@gmail.com1') self.permission = Permission.objects.create(name='permission_name_1', codename='perms1') self.role = Role.objects.create(name='role1',user=self.user,permissions=[self.permission.pk]) def test_update(self): data = {'user':self.user,'permissions':[self.permission.pk],'name':'role_name2'} url = reverse('roles:update_role',kwargs={'pk':self.role.pk}) response = self.client.put(url,data,format='json') print(response.json()) return self.assertEqual(response.status_code,status.HTTP_200_OK) models.py class Role(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) created = models.DateTimeField(auto_now_add=True) views.py class CreateRole(CreateAPIView): serializer_class = RoleSerializer queryset = Role.objects.all() class UpdateRole(UpdateAPIView): serializer_class = RoleSerializer queryset = Role.objects.all() def put(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) -
Django - customized password validator - error in path to my validators.py
I want to add my own password validator in my django project 'MyProject' so I create a validators.py file in my registration app but don't know how to set in my settings? settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, { 'NAME': 'MyProject.registration.MyValidator', }, ] validators.py from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ class MyValidator: def __init__(self): def validate(self, password, user=None): if password == 'banane': raise ValidationError( _("This password must contain at least 2 special characters."), code='invalid_password', params={}, ) def get_help_text(self): return _( "Your password must contain at least 2 special characters." ) -
REMOTE_USER is empty in the django after redirecting
It seems to me that I do not quite understand the REMOTE_USER variable. I have three instances based on different hosts: nginx, django_auth_server, django_app_server. I am trying to implement "single sign on": the user logs on to the django_auth_server via nginx, is redirected to the django_app_server and continues surfing without authentication. In my case after redirection to the root folder (from '/login' to '/') the REMOTE_USER variable is empty. But it does exists in the request headers: Content-Type: text/html; charset=utf-8 Location: / REMOTE_USER: alfabeta X-Frame-Options: SAMEORIGIN Vary: Cookie Content-Length: 0 Set-Cookie: csrftoken=... Set-Cookie: sessionid=... Code from the authorization view (djangoauth instance): if user is not None: login(request, user) r = redirect('/') r['REMOTE_USER'] = username return r I'm not sure if it is correct to set the variable in this way. part of the nginx config server { listen 8080 default_server; server_name localhost; charset utf8; autoindex off; underscores_in_headers on; proxy_pass_request_headers on; ... location / { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgiapp; uwsgi_read_timeout 300; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } location =/login/ { include /etc/nginx/uwsgi_params; uwsgi_pass uwsgiauth; uwsgi_read_timeout 300; uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; uwsgi_param REMOTE_USER $remote_user; } How to … -
Formset using class-based views with multiple instance
I want to use formset to add multiple todo at once, I have been told to use formset, which is exaclty what I am looking for, but all the documentations and video tutorials are using function based view. I have my models.py class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") content = models.TextField(verbose_name="Description supplémentaire",null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) complete = models.BooleanField(default=False, verbose_name="Statut de la Todo") urgence = models.BooleanField(default=False,verbose_name="Tâche urgente") def __str__(self): return self.text def get_absolute_url(self): return reverse('dashboard-home') To me, that should be enough because i have author as foreignkey, of course I import formset_factory at the top. But then it's very not clear for the view Views.py class TodoCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): model = Todo fields = ['text','urgence'] success_message = 'Votre tâche a bien été ajoutée' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) How everything should work ? The purpose of this is just to add multiple todo at once, nothing too difficult, but I struggle. Just an example : This, but with multiple input. Thanks for your help -
Facing issues while integrating "Klarna" Payment Gateway in Django-Oscar
I'm trying to add the klarna javascript SDK into my site in which I need the client_token.and also created the test environment where I got the API key inside this have got the username and password for my test merchant account. Below is my template file: <script> window.klarnaAsyncCallback = function () { try { Klarna.Payments.init({ client_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.dtxWM6MIcgoeMgH87tGvsNDY6cHWL6MGW4LeYvnm1JA' // replace this client_token with your }) } catch (e) { // Handle error. } }; </script> <script src="https://x.klarnacdn.net/kp/lib/v1/api.js" async></script> the client_secret is given in the documentation and also it is mentioned in the document that first, we have to create a session. so I tried to create through API but didn't get the proper solution for creating it. so I have few questions about the integration: How can we get the client_token to integrate the javascript SDK in django oscar ?. Is it necessary to create the session to integrate the klarna payment gateway in django oscar ? How can we use the test account credential for creating the session and client_secret A Mockup example to get me started in the right direction will be helpful. -
how can i send JS data to django?
var typingTimer; var doneTypingInterval = 500; var searchedValue; $("#trackName").focusin(function(){ $(this).keyup(function(){ clearTimeout(typingTimer); if($(this).val()){ typingTimer = setTimeout(doneTyping, doneTypingInterval); } }); }); function doneTyping(){ searchedValue = ($("#trackName").val()); return searchedValue; } actually my aim is to get this searchedValue variable in django so that i can use this variable to access some song name from my django database. for eg: if i type "fad" in input element then searchedValue = "fad" then i want this variable in django so that i can use database query to access all the song with name "fad" thanks for the help in advance -
How i can change name of parameters in url routers DRF?
How i can change name of parameters in url? Like this //, but by default name of parametr is "pk" I make request to "api/product/1/rate/1/" and get {'product_pk': '1', 'pk': '1'}. I want to rename "pk" to "person_id". How to make this? router = routers.SimpleRouter() router.register(r'product', ProductViewSet) rate_router = routers.NestedSimpleRouter(router, r'product', lookup='product') rate_router.register(r'rate', RateViewSet, base_name='rate') -
Redirect to absolute URL
I am trying to redirect to a tenant sub-domain after registering a tenant in my site but I am receiving a namespace error. Views.py: domain = Domain() domain.domain = tenant.schema_name + '.localhost:8000' domain.tenant = tenant domain.is_primary = False domain.save() return HttpResponseRedirect(reverse(domain.domain)) Error: NoReverseMatch at /companies/company_registration/ 'company.localhost' is not a registered namespace How do I add a sub-domain, which I do not currently know, as a URL namespace? Or better yet, how to redirect to an absolute URL? -
language independent query with django-modeltranslation
I currently started to use django-modeltranslation in a Django app and I would like to make a query to retrieve the instance of a model, independent of the language set in the system. For example I have the following model: class Product(models.Model): description = models.CharField(max_length=200) sku = models.CharField(unique=True, null=False, max_length=30) price = models.DecimalField(max_digits=8, decimal_places=2) and the following in translation.py: class ProductTranslationOptions(TranslationOptions): fields = ('description', 'sku') translator.register(Product, ProductTranslationOptions) and the Django setting: gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('de', gettext('German')), ) MODELTRANSLATION_LANGUAGES = ('en', 'de') MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_FALLBACK_LANGUAGES = ('en',) Let's create a product instance: Product.objects.create(description_en='product en', description_de='product de', sku_en='sku-001', sku_de='sku-002', price=10.0) Now I want to find the instance with the sku sku-002, to retrieve the price of a product (which is independent of the language). Product.objects.filter(sku='sku-002') However this returns an empty MultilingualQuerySet. Only the following returns the correct Product instance. Product.objects.filter(sku_de='sku-002') or from django.utils import translation translation.activate('de') Product.objects.filter(sku='sku-002') I guess this is the intended behavior of django-modeltranslation, but sometimes it would be practical to find an instance independent of the language. A solution could be to iterate through all LANGUAGES and try to find the instance for each language: from django.conf import settings LANGUAGES = … -
Handle .envs in docker and gitlab ci without having it in the repository
I am running a dockerized django app that uses Gitlab CI for automated tests. In my .env/ folder I have a .local and a .production file that contains my environment variables that are read in my setup-file with env = environ.Env() env(...). I think that is pretty standard. Up until now my .env/local file was committed in my repository and the tests need it to run because in my docker compose file I have: env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres and I run my tests in gitlab CI using docker-compose -f local.yml run django pytest. Now I do not want my local env file in my repository. Simply because it is bad practice and I would also like to store some secret keys like AWS etc in there. But then it breaks my tests. Is there any recommended way on how to achieve what I want? Or is that not possible? I tried to add another .secret file, but also this one I have to specify in my compose file. This seems to be related How do I add a .env file in gitlab ci during deployment stage? but there is nothing on how to do this with django, docker and … -
Django MEDIA_URL return https instead of http
I'm using Django 2.2.x and DRF. I have a model with FileField file = models.FileField(upload_to=get_media_upload_path) Files are uploading but on access the obj.file, it gives URL without HTTPS http://example.com/media/image.jpg I want it to be https://example.com/media/image.png Redirect is already setup in nginx config. But I want the response URL with https. -
Django how to annotate manytomany field with count
Considger the following: class ModelA(models.Model): pass class ModelB(models.Model): model_as = models.ManyToManyField(ModelA, db_index=True, related_name="model_bs", blank=True) model_bs = model_a_object.model_bs.all() for model_b in model_bs: print(model_b.model_as.count()) 3 2 So far so good. But I want to created an ordered list of model_bs depending on the count of model_as. My understanding is that simply this should do the trick: model_bs = model_a_object.model_bs.all().annotate(count=Count("model_as")).order_by('count') For some reason that doesn't work. When I print to check, the annotated count is wrong!! for model_b in model_bs: print(model_b.model_as.count(), model_b.count) 3 1 2 1 What did I do wrong? -
django-session-timeout: The current path, accounts/login/, didn't match any of these
I try to implement an autologout after user inactivity (lets says 15 minutes) I have read many things and there is as my understanding at least two possibilities: use the django-session-timeout write a personnalized middleware I try first to use the django-session-timeout but got the error: The current path, accounts/login/, didn't match any of these. in my settings.py I have defined LOGOUT_REDIRECT_URL = 'home' here is my project urls.py: from django.urls import path, include from . import views from django.conf import settings urlpatterns = [ path('', views.home, name='home'), path('registration/', include('django.contrib.auth.urls')), path('monitor/', include('monitor.urls')), path('randomization/', include('randomization.urls')), path('admin/', admin.site.urls), ] -
Retrieving images from Django from rest_framework
models.py: from __future__ import unicode_literals from django.db import models class Photo(models.Model): title = models.CharField(max_length=255, blank=True) file = models.FileField() uploaded_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from . models import Photo class imageSerializer(serializers.ModelSerializer): class Meta: model = Photo fields='__all__' views.py: from django.shortcuts import render,redirect from django.http import JsonResponse from django.views import View import time from rest_framework import generics from .forms import PhotoForm from .models import Photo from django.http import HttpResponse from rest_framework.response import Response from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework import status from .serializers import imageSerializer import requests class DragAndDropUploadView(View): def get(self, request): photos_list = Photo.objects.all() return render(self.request, 'UploadMulti/drag_and_drop_upload/index.html', {'photos': photos_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) def clear_database(request): for photo in Photo.objects.all(): photo.file.delete() photo.delete() return redirect(request.POST.get('next')) class ImagesList(APIView): def get(self,request): imagelist=Photo.objects.all() serializer = imageSerializer(imagelist,many=True) return Response(serializer.data) def post(self): pass def backend(request): response = requests.get('http://localhost:8000/images/') api_values = response.json() for values in api_values: print(type(values['file'])) return render(request,"home.html",{'data':api_values}) when I print type of values.file which is the image data I am getting as therefore when sending it to frontend the image is not displayed How to retrieve as …