Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
installing gcc compiler on shared hosting
I have a simple website built using Django. I am trying to deploy it. I have a bluehost shared hosting account. I have successfully accessed the SSH. I'm trying to upgrade Python2 ( defaulton bluehost) to Python 3x. After extracting and decompressing python tar I tried to run this instruction : " ./configure --prefix=$HOME/.local ". I ran into this error : " no acceptable C compiler found in $PATH See `config.log' for more details ". This seems to be standard error because I've seen this question asked here and many other forums but I haven't come across any solution yet. I tried installing gcc complier using yum but that led me into another error : " CRITICAL:yum.cli:Config error: Error accessing file for config file:///etc/yum.conf ". I'm stuck with this for3 nights now. It's depressing. Any help would be appreciated. -
Analogue of {% static %} in pure python
Django 3.0.6 Could you tell me whether there is a way to reverse static path outside any template? For example, we have this: <img src="{% static "my_app/example.jpg" %}" alt="My image"> How can I write a python code to get such src? def example(): img = "my_app/example.jpg" path = ... src = os.path.join(path, img) return src It must work both locally and in the production. -
Django: duplicate key value violates unique constraint with Postgresql not with SQlite -> why?
I have just deploy my project with Postgresql database and get an error unique contraint violates I did not have with my sqlite development database IntegrityError at /randomization_settings/edit/ duplicate key value violates unique constraint "adm_bra_pkey" DETAIL: Key (bra_ide)=(1) already exists. I have a table (adm_bra) prepopulate with 2 lines. I try to INSERT new lines with code using models.objects.create() methods in a view. Why this happen with postgresql and not with sqlite database? I try to DELETE and RESTART SEQUENCE of adm_bra but it doesn't works! thanks for help -
How to edit many to many relationship field that's optional using horizontal filter in django admin
I created "night" field that has m2m relationships with Recipe model in django. I wanted this field to be optional, so added one option like "blank" = True. night = models.ManyToManyField(Recipe, related_name = "night", null = True, blank = True, verbose_name = '加 餐') But when I create in add page of django admin, the form has no horizontal filter like this one. I think because it is optional. I want the horizontal filter to appear even when it's optional, so that I can add some recipes into it if I want, or add nothing otherwise. Could anyone help me? Thanks in advance. -
Making a Stateless and Single Page Application in Django
I have a python based stateless CLI program that queries (making HTTP Requests) a Registry server and gets information about some registered devices like their IP address and UUID and further querying each devices i can PATCH these devices to make them do something. I used python as it is easy to work with JSON data performing the HTTP requests. Now i want to make a GUI that allows the a user to access the Registry server, get the device info and do something in the back-end. My question, to make such kind of Stateless and Single Page Application Is it enough by using only Django (or Flask) Do i need to use React or Vue along with say Django for the front-end. As i am relatively new to Django and Web Applications as a whole, any suggestions like courses/tutorials to learn the stuff required would be much appreciated. P.S. I have added a picture as a reference to what i am trying to do. -
build_absolute_uri with HTTPS behind reverse proxy
I'm serving my django app behind a reverse proxy The internet -> Nginx -> Gunicorn socket -> Django app In the nginx config: upstream my_server { server unix:/webapps/my_app/run/gunicorn.sock fail_timeout=0; } The SSL is set up with certbot at the nginx level. request.build_absolute_uri in views.py generates http links. How can I force it to generate https links? -
Django: TypeError: int() argument must be a string, a bytes-like object or a number, not 'ObjectId'
Im getting this type error when trying to return a JsonResponse. In the code python_serializer is an object that has a instance variable named data containing the results of the JsonParser().parse(request) which is of type dictionary(in python). Later in the code when I try to return a json response my program keep giving me this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'ObjectId' Here is the full traceback: Internal Server Error: /api/products Traceback (most recent call last): File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\alexei\Columns\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\alexei\Columns\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\alexei\Columns\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\alexei\MongoDBClone\DjangoRestApi\Product\views.py", line 29, in product_list return JsonResponse(product_serializer.data, status=status.HTTP_201_CREATED) File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\serializers.py", line 562, in data ret = super().data File "C:\Users\alexei\Columns\venv\lib\site-packages\rest_framework\serializers.py", line 260, … -
Security risk: passing user defined data to Django template (for Vue.js)
I want to use Vue.js to display user-defined data(posts) on my page. In Django I serialize a queryset(transform it into json) with serializer from the rest framework. In the template I`m using something like this: <script type="text/javascript">var posts_in_js={{posts_from_django|safe}};</script> I created a security hole, users can type in javascript code in forms and then it will be executed every time when the page is loaded. By default, Django escapes every tag. Is there a way to auto escape form fields on validation instead? Are there other risks of this method? My json looks like this: [{"id":1, "text": "messages of the user..", "img":"URL of the image"}, ...] Thanks for every help :) -
Ignore settings.py in Git
I want to have different settings.py files on my development pc and production server. I've tried adding settings.py to .gitignore, tried adding it to .git/info/exclude. But i still get it overwritten any time i pull from remote. What is the correct way to achieve this goal. -
Using distinct() order_by() filter() alltogether
I have a query: titles= Entry.objects.filter(created_date__gte=date_from,user__followed__follower=request.user).order_by('-created_date').values_list('title', flat=True).distinct() It works fine except the distinct part which doesn't work and distinct("title") is not supported by the database I'm using. Performing set() on the query object without using distinct() brakes the order. The only solution I came up with is to append every title in a list and check if it already exists there, which probably is an overkill. Thank you for reading. -
Dose Flask have classes like Django's StreamingHttpResponse or FileResponse?
Like title asked, I'm using Flask and requests package to send a GET request to another server to get a file which could be 2G+, thus it caused OOM, so I'm thinking if I could handle the response in some other ways. -
python "not enough arguments for format string"
I am trying to insert multiple rows from dataframe to mysql. I counted arguments numbers and they all are of same number (i.e. 11 here). But still I get this not enough arguments for format string Here's the function: def insert_result_sets_into_db(df, filter_rule_id): cols = "('hash_id', 'filter_rule_id', 'task_id', 'assigned_to', 'human_verdict', 'verdict_date', 'verdict_by', 'created_by', 'updated_by', 'created_at', 'updated_at')" if not df.empty: with connections['frontend'].cursor() as cursor: sql = "INSERT INTO dmf_result_set_assign " + cols + " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" values = [] now = datetime.now() formatted_date = now.strftime('%Y-%m-%d %H:%M:%S') # Insert DataFrame records one by one. for i,row in df.iterrows(): tup = (row['_id'], filter_rule_id, 1, 1, 'Matched', formatted_date, 1, 1, 1, formatted_date, formatted_date) values.extend(tup) cursor.executemany(sql, values) connections.commit() Am I missing anything here? -
how to store the javascript variable value into the DB (python, Django project)
I have a JavaScript variable value and I want to store the value into my DB I will give you path can you provide any ideas how to do that. JavaScript score variable value along with logged in user name value ---> to Django admin(models) I have a score in javascript file username in the DB Models.py class Results(models.Model): username = models.CharField(max_length=50,default='') score = models.IntegerField() Can any one provide the ways or any links or suggestions.Please. -
Best solution to store time series data to show dynamically (Python Django + Highcharts)
My goal is to build a graph similar to this https://www.deribit.com/1.21.0/static/funding_chart.html?instrument=BTC-PERPETUAL that updates every second and that saves previous data up to 1 week. I'm extracting the live data from an API. I'm using django to serve it and Highcharts for the representation. What's the best way to store this data? Would just a pandas dataframe do or do I need to set up a database? I would have a total of 604.800 data points -
Distinc values of items coming from two querysets in Django view/template
I need to output a list of works performed by a performer. The same work can have been performed multiple times, and in two different kind of event (e.g. performanceOfWork and Event models). class Work(models.Model): title = models.CharField(max_length=200) # max_length = required class performanceOfWork(models.Model): solo_performer = models.ManyToManyField(Profile) performed = models.ForeignKey('Work', on_delete=models.CASCADE) class Event(models.Model): solo_performer = models.ManyToManyField(Profile) repertoire = models.ManyToManyField(Work, blank=True) In the view I managed to get the distinct values from each of the two models: context['repertoire_from_works'] = performanceOfWork.objects.filter(solo_performer=self.get_object().id).values('performed__title').distinct() context['repertoire_from_events'] = Event.objects.filter(solo_performer=self.get_object().id).values('repertoire__title').distinct() But then, how do I deal with the same work being performed in both models? I just want to output it once. This is a very wonky attempt (which doesn't work because it checks both values within one nested loop): <ul>{% for work_works in repertoire_from_works.all %} {% for work_events in repertoire_from_events.all %} {% if work_works.performed__title == work_events.repertoire__title%} {% if forloop.first %} <li>{{ work_works.performed__title }}</li> {% endif %} {% else %} <li>{{ work_events.repertoire__title }}</li> <li>{{ work_works.performed__title }}</li> {% endif %} {% endfor %} {% endfor %} </ul> -
Unknown timegap in django + uwgi profile
I'm trying to understand why my website (django + uwsgi + nginx) response is take about 1.5 seconds. I'm using jazzband/django-silk for this purpose, and in it's admin panel I see that request takes about 800ms https://i.stack.imgur.com/SJNaZ.png But when I inspect nginx / uwsi logs I see that execution time is much more from 1.5 to 2 seconds usgi log: => generated 99087 bytes in 1818 msecs (HTTP/2.0 200) 4 headers in 133 bytes (1 switches on core 0) nginx log (time in the end) 10.136.52.100 - - [27/May/2020:14:51:04 +0000] "GET / HTTP/2.0" 200 12250 "https://localhost:4443/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36" 1.819 1.820 . So I'm losing about 500ms on every request. Can somebody help me to understand what is wrong, or this is right behavior ? Config of uwgi bellow: [uwsgi] module = newsletter.wsgi master = true processes = 10 socket = /var/run/newsletter/app.sock chmod-socket = 777 vacuum = true enable-threads = true ignore-sigpipe = true ignore-write-errors = true disable-write-exception = true -
How to add a Django form field through JavaScript?
I have a Django form like this: class CrawlRequest(models.Model): tor_info = models.CharField(max_length=20) And I have my template, where I have a Select that calls a JavaScript function like this when changed: function detailIpRotationType(){ var ipSelect = document.getElementById("ip_type"); const ip_rotation_type = ipSelect.options[ipSelect.selectedIndex].value; var extra_div = document.getElementById("ip_type_div"); if(ip_rotation_type == 'tor'){ extra_div.innerHTML = ` <input class="form-control" name="tor_info" id="tor_info" type="text" required/> ` } This works fine, but I want to change this input element to {{ forms.tor_info }}. When I add it normally just like I do in my main template, it isn't recognized as a Django element, and it becomes a text. Does anybody know how can I do it? Thanks in advance. -
Is there a way to make user given HTML safe?
I am working under Django and made a Rich Text editor for users to type kind of articles. It really looks like your stack overflow answer section. The problem is I think users can find multiple ways of injecting malicious code with this HTML content marked as "safe". The Rich Text Editor is TinyMCE and you can use BBCode, which would be a solution but it has its limits. For example you can't replace code snippets marked as <pre> so its a no-no for me. I know about HTML Purifier in PHP, is there a solution I could use with Django ? Or, as it would not be mission critical being some kind of personal "projects" website I shouldn't care ? -
I cannot email from django
Good afternoon, I am trying to send an email from shell using Django. it is showing me an attribute error, please find here the code EMAIL_BACKEND = "django.core.mail.backends.smtp.emailBackend" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_UNSER = "myemail@gmail.com" EMAIL_HOST_PASSWORD = "Password" and in shell I do from django.core.mail import send_mail send_mail('Asunto', 'Mensaje', 'myemail@gmail.com', 'testemail@outlook.com', fail_silently=False, ) and it is coming with this error Traceback (most recent call last): File "C:\Users\….\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", line 20, in import_string return getattr(module, class_name) AttributeError: module 'django.core.mail.backends.smtp' has no attribute 'emailBackend' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\...\Python\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 51, in send_mail connection = connection or get_connection( File "C:\Users\….\Python\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 34, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "C:\Users\...\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", line 22, in import_string raise ImportError('Module "%s" does not define a "%s" attribute/class' % ( ImportError: Module "django.core.mail.backends.smtp" does not define a "emailBackend" attribute/class I am not really sure why is coming with this error, I have change the security settings in my email. and I have follow the steps from tutorials and I am not sure with my error is. THANK YOU :) :) -
Show value in table from a model with template in django
I want to make a website to manage a bread production but I am facing 2 problems. I have a model bread (Pain) that allows me to create a bread and to give that bread a starting price. (nom_pain = name , prix_HT = price) class Pain(models.Model): nom_pain = models.CharField(max_length=25,primary_key=True) prix_HT = models.DecimalField(max_digits=4,decimal_places=2) pain_decouverte = models.BooleanField(null=False) def __str__(self): return '{}'.format(self.nom_pain) I have a model Group (Groupe) that represents different group of clients. (nom_groupe = name) class Groupe(models.Model): nom_groupe = models.CharField(max_length=30) def __str__(self): return '{}'.format(self.nom_groupe) I wish to match the price of each bread to a group of clients on one page and then display it in a table chart (inserting the bread prices in the blank cells) | Bread 1 | Bread 2 | Bread 3 | Group 1 | 0.5 | 0.6 | | Group 2 | 1 | | 0.5 | Group 3 | 0.5 | 0.4 | 0.7 | My first problem is that I can’t save 2 times a group/bread in my model Price (Prix) (I wanted it in the form of Group / Bread / Price). The second problem is that I don’t know how to display my table chart in my template. I can … -
DRF serializer return translated choice field value
i'm using django-modeltranslation to translate mo models in DRF so i did all that says docs of django-modeltranslation and it work for model fields but i cant get translated value of choicefield from django.utils.translation import ugettext_lazy as _ class Product(models.Model): PRODUCT_TYPES = ( ('food', _('food')), ('wear', _('wear')) ) product_type = models.CharField('Type', choices=PRODUCT_TYPES, blank=True, null=True, max_length=16, default='food') -
How to mock patch the Serializer.is_valid() method when unit testing in Django Rest Framework
I want to be able to unit test a view without connecting to the db, i can mock patch the User.save() method but a don't know how to patch serializer.is_valid() properly. It looks like is_valid method requires db connection to validate fields or something like that. Is there a way we can do this? I'm using django-pytest and pytest-mock here is the view a want to test class RegistrationViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def create(self, request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) here is my serializer class RegistrationSerializer(serializers.ModelSerializer): """Serializers registration request and creates a new user.""" password = serializers.CharField( max_length=128, min_length=8, write_only=True # can not be read by the client ) token = serializers.CharField(max_length=255, read_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'token'] def create(self, validated_data): return User.objects.create_user(**validated_data) Here is my view test so far class TestRegistrationViewSet: """ Test cases for registrating user """ def test_register_user_success(self, rf, mocker): url = reverse('registration-list') data = { "user": { 'username': 'user1', 'email': "email@cookie.com", 'password': 'user1pass' } } request = rf.post(url, data=data, content_type='application/json') mocker.patch.object(User, 'save') response = RegistrationViewSet.as_view({'post': 'create'})(request).render() assert response.status_code == status.HTTP_201_CREATED This is the error traceback i'm getting repostery\authentication\views.py:21: in … -
In admin site users will add template tags: how to enqueue dependencies (JavaScript and CSS files)
Django 3.0.6 models.py class Post(models.Model): body = models.TextField() view_mixins.py class RenderBodyMixin(BaseDetailView): """ Lets using template tags in body field in admin site. """ custom_scripts = set() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post_body = "{% load image %}\n{% load widget %}\n{% load hyper_link %}\n{% load code_sample %}\n" + self.object.body context['body'] = Template(post_body).render(Context()) views.py class PostDetailView(RenderBodyMixin, DetailView): model = Post Task This is all done for users to be able to insert template tags into posts. For example: widget {% n_m n=1 m=2 %} This will show something like "1/5". But the main idea is that it needs a special css file. This is a very basic example, please, don't take it too exactly. This is all about custom resources for particular pages. What resources will be necessary is not known in advance. Users will use template tags. That is enough for them to know. Template tags may need, for example, jQuery, jQuery UI or whatever. I can't append all these scripts and CSS files beforehand as it is highly inefficient. So, I need to enqueue them for each particular page and only if template tags need them. Could you tell whether it is possible to append dependencies automatically to the … -
i run the makemigration code and i receive many errors
i'm new in django i want to create a business_plan application i the step to create my models i have a creating many class in my models.py: from django.db import models from django.contrib.auth.models import * class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"staff")) user_type=models.CharField(default=1,choices=user_type,max_length=10) class Entrepreneur(models.Model): id_models= models.IntegerField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE()) nom_et_prenom=models.CharField(max_length=50) date_naissance=models.DateField() adresse_entr=models.CharField(max_length=20) telephone=models.IntegerField() statut_social=(('ce','celébataire'), ('ma','marié'), ('di','divorcé'), ('ve','veuf'), ) occupation=models.CharField(max_length=50) niveau_scolaire=( ('pri','primaire'), ('sec','secondaire'), ('cap','certificat aptitude professionel'), ('btp','brevet technicien professionel'), ('bts','brevet technicien superieur'), ('lic','license'), ('mai','maitrise'), ('mas','mastere'), ('doc','doctorat'), ) niveau_scolaire=models.CharField(default='ser',choices=niveau_scolaire,max_length=50) annnee_exp=models.IntegerField() email=models.CharField(max_length=255) password=models.CharField(max_length=255) class Projet(models.Model): id_models=models.IntegerField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE()) nom_projet=models.CharField(max_length=30) lieu_implantation=models.CharField(max_length=20) type_projet=( ('ser','service'), ('com','commerce'), ('agr','agricuture'), ('ind','industrie'), ('IT','technologie information'), ('art','artisanat'), ('tor','tourisme'), ) type_projet=models.CharField(default='ser',choices=type_projet,max_length=50) produit=models.CharField(max_length=50) id_promoteur=models.ForeignKey(Entrepreneur,on_delete=models.CASCADE) class Admin(models.Model): id_admin=models.AutoField(primary_key=True) name=models.CharField(max_length=255) email=models.CharField(max_length=255) password=models.CharField(max_length=255) objects=models.Manager() class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"staff")) user_type=models.CharField(default=1,choices=user_type,max_length=10) this is my files manage.py: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() when i run makemigration after creating my classes i have this error: > (business) C:\Users\hp\PycharmProjects\business\oasisconsuting>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, … -
Django Channels, how to set redis docker container ip as host
I am attempting to follow the tutorial at https://channels.readthedocs.io/en/latest/tutorial/part_2.htm I am using docker-compose to run the redis server needed for Django Channels as opposed to the plain docker command. However i am unsure of how to set the ip address in : CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.2', 6379)], }, }, } to that of the redis container. i have the following in my docker-compose.yml: redis: image: "redis:alpine" command: redis-server --requirepass letmein ports: - "6379:6379" volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf environment: - REDIS_REPLICATION_MODE=master networks: node_net: ipv4_address: 127.0.0.2 networks: node_net: ipam: driver: default config: - subnet: 127.0.0.0/16 When i try and test the connection with: async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) i receive the following: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 120, in __call__ return call_result.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 425, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/asgiref/sync.py", line 180, in main_wrap result = await self.awaitable(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 299, in send async with self.connection(index) as connection: File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 835, in __aenter__ self.conn = await self.pool.pop() File "/usr/local/lib/python3.6/site-packages/channels_redis/core.py", line 73, in pop conns.append(await aioredis.create_redis(**self.host, loop=loop)) File "/usr/local/lib/python3.6/site-packages/aioredis/commands/__init__.py", line 175, in create_redis loop=loop) File "/usr/local/lib/python3.6/site-packages/aioredis/connection.py", line …