Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use prismjs in django?
can someone tell exact how to use prismjs in django blog app. I tried but not working. I just want step by step guidence from very start to end. Thanks in advance ! -
Docker: User localhost instead of db to connect to PostgresDatabase
I'm running into problems when using Docker. To connect from Django application to the Postgres database I have to use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } However to run tests via pytest in my Pipenv shell I have to change 'Host': from db to localhost. Is there a way that I can always use localhost? Docker-Compose: version: '3' services: db: image: postgres ports: - "5432:5432" web: build: . env_file: .env volumes: - .:/code ports: - "8000:8000" depends_on: - db container_name: test Dockerfile: # Pull base image FROM python:3 # Set environment varibles ENV PYTHONUNBUFFERED 1 # Set work directory RUN mkdir /code WORKDIR /code # Install dependencies RUN pip install --upgrade pip RUN pip install pipenv COPY ./Pipfile /code/Pipfile RUN pipenv install --deploy --system --skip-lock --dev # Define ENTRYPOINT COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] # Copy project COPY . /code/ -
Saving files in a S3 subfolder
If I'm not mistaken, there are no real folders in S3. But there seems to be a possibility to save files with path's so it looks like a folder (when navigated through the AWS console, the folders are even visible). Having a FileField in Django, how would I append a folder name to it? E.g. the below works but is being put in the root bucket, which becomes cluttered very quickly. I'd love to put all those files in a 'subfolder' class presentation(models.Model): """ Holds the presentation themselves""" author = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField( null=False, blank=False, help_text='PPT or other presentation accessible only to members', storage=protected_storage, ) protected_storage = storages.backends.s3boto3.S3Boto3Storage( acl='private', querystring_auth=True, querystring_expire=120, # 2 minutes, try to ensure people won't/can't share ) -
Does django 1.11 orm support using group in regexp_replace postgresql function?
So I use django 1.11 and postgresql 9.6.6 which support regexp_replace function. I want to make such query: from django.db.models import Func, F, Value from customsite.models import CustomSite CustomSite.objects.all().update(site_field=Func(F('site_field'), Value('(foo)(bar)'), Value('\\1-\\2'), Value('gm'), function='regexp_replace')) Can I do it? Does orm of django support this syntax? In my case, there is a simple replacement with a hyphen. But I want use groups \\1 and \\2. Could you help me, please? -
OperationalError : FATAL: no pg_hba.conf entry for host "127.0.0.1", user "fibzadmin", database "fibz", SSL off
I have been struggling with this issue for a few days now. I have read numerous other SO threads and it seems like my django app is having difficulty connecting to the postgres database. I am not sure why that is happening though. I am hoping some of the experts out there can take a look and tell me why this might be happening. I have pasted some of my configuration here. This is what my settings.py contains DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'fibz', 'USER':"fibzadmin", "PASSWORD":"fibzadmin", "HOST":"localhost", "PORT":"5432", } } This is what my pg_hba.conf and postgresql.conf look like sudo vim /var/lib/pgsql9/data/pg_hba.conf Output: local all all trust # IPv4 local connections: host all power_user 0.0.0.0/0 md5 # IPv6 local connections: host all other_user 0.0.0.0/0 md5 host all storageLoader 0.0.0.0/0 md5 host all all ::1/128 md5 following are the main uncommented lines listen_addresses = '*' port = 5432 max_connections = 100 and this is from the psql (fibzVenv) [admin]$ sudo su - postgres Last login: Fri Nov 23 07:13:53 UTC 2018 on pts/3 -bash-4.2$ psql -U postgres psql (9.2.24) Type "help" for help. postgres=# \du List of roles Role name | Attributes | Member of ------------+------------------------------------------------+----------- postgres | … -
Django: Search Multiple Fields of A Django Model with Multiple Input field (with Drop Down) in HTML
How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement. class SecondHandCar(models.Model): brand = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) colour = models.CharField(Category, on_delete=models.CASCADE) year = models.IntegerField(blank=False) I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django. -
calcul time between 2 hours in django
I try to calculate the time elapsed between 2 hours but also to make a sum for the day and the week. I tried several methods but none was congruent and I dry completely, no more ideas. class Timesheet(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 64, verbose_name = _("Title")) start = models.DateTimeField(verbose_name = _("Start time")) end = models.DateTimeField(verbose_name = _("End time")) allDay = models.BooleanField(blank = True, default = False, verbose_name = _("All day"), help_text = _("If it's a full day work, just click 'Now' for start/end")) week = models.IntegerField(verbose_name = "working week") def __str__(self): return "{}".format(self.title) def save(self, *args, **kwargs): if not self.pk: self.week = datetime.datetime.now().isocalendar()[1] if self.allDay: self.start = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=8, minute=00) self.end = datetime.datetime(year = datetime.datetime.today().year, month = datetime.datetime.today().month, day = datetime.datetime.today().day, hour=17, minute=30) super(Timesheet, self).save(*args, **kwargs) In the hope that you can help me. Regards, -
Django Rest Framework custom error messages
I am trying to add custom field error messages for SlugRelated field as follows: class Test(serializers.ModelSerializers): team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name', error_messages={"does_not_exist": "Team not found"}) Works as expected. My query is how do I pass the team name dynamically in the error message. I tried the following but it did not work: class Test(serializers.ModelSerializers): team = serializers.SlugRelatedField(queryset=Team.objects.all(), slug_field='name', error_messages={"does_not_exist": f"Team {team} not found"}) -
Unable to send django emails using localhost on cloud server
Setting.py --- Email is not working and not giving any error on cloud server ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'localhost' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 25 EMAIL_USE_SSL = False EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'webmaster@healthondemand.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' Thanks in advance -
Passing django user as redirect request header
I have a (non-django) application A that requires a username to login. This app allows for pre authorization, which I want to provide from my django application B. However app A requires that the username is set as a remote_user request header. What I tried to do is create a view in django app B that redirects to app A passing a remote_user header. urls.py url(r'^{0}to_app_a$'.format(DJANGO_BASE), 'app.views.to_app_a') views.py def to_app_a(request): response = redirect('http://app_a') response['remote_user] = request.user return response The problem with that is that the header is lost on redirect and never reaches the request to http://app_a external app. It has been suggested to use cookies instead, but unfortunately app A won't accept anything else than a remote_user request header. Has anyone come up with a solution to such issue? Thank you -
Django rest framework pass field errors in the extra_kwargs dictionary
I am customizing the does_not_exist error message for a SlugField in my serializer as follows: class PolicyCreateUpdateSerializer(serializers.ModelSerializer): source_ip_group = serializers.SlugRelatedField(queryset=IPGroup.objects.all(), slug_field='name', error_messages={"does_not_exist": "Custom"}) enabled = serializers.BooleanField() class Meta: model = Policy fields = ['id', 'name', 'source_ip_group', 'enabled'] This works as expected.However, when I try to add this in the Meta attribute of the class, it does not work. class PolicyCreateUpdateSerializer(serializers.ModelSerializer): source_ip_group = serializers.SlugRelatedField(queryset=IPGroup.objects.all(), slug_field='name') enabled = serializers.BooleanField() class Meta: model = Policy fields = ['id', 'name', 'source_ip_group', 'enabled'] extra_kwargs = {'source_ip_group': {"error_messages": {"does_not_exist": "Custom"}}} What am I doing wrong ? -
VSCode: "Go to definition" from JS url (view url) to the Django view
I am using sublime now and want to switch to the vscode but one functionality of sublime holding me so far. In the posted image below left side is test.js and right side is view.py having simple test_view definition. If I use go to definition on the "test_view" (at line url: "/test_app/test_view/"+$routeParams.id) in the JS, sublime redirects to the test_view definition of the Django view. I am looking similar functionality/configuration in the VSCode. -
OpenCv Python Django, How can save the image path to my database after resizing it
I have a model which need to hold image path and all my image is being saved to the specifics dir, but i want resize the image with OpenCv because i needs all images to save the same width and height but when i resize it is being is being saved in my project root dir img = OpenCV.imdecode(NP.fromstring(getMainFile.read(), NP.uint8), OpenCV.IMREAD_UNCHANGED) print("w & h before resize: ", img.shape) default_h = 3264 default_w = 4896 resizeImg = OpenCV.resize(img, (default_w, default_h)) print("w & h before resize: ", resizeImg.shape) OpenCV.imshow("The Images", resizeImg) print(resizeImg) genInt = random.randint(1,3445565632) """ after imwrite the image is being saved in project root dir, in this point i want to take the variable "storeImg" and save to models and saved to my database so when i print the variable type is a "class bool" type but i want get the path of image and send it to models """ storeImg = OpenCV.imwrite('{}.jpg'.format(genInt), resizeImg) print(type(storeImg)) print(storeImg) OpenCV.waitKey(0) OpenCV.destroyAllWindows() print(img) print(type(img)) -
how can i run spesefic migration sector in django
now im trying to migrate empty django project. when enter this command python manage.py showmagrations result is admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name myapp [ ] 0001_initial sessions [ ] 0001_initial is this situation how can i migrate all of 0001_initial? or how can i run spesific migrtaion step? ex) admin 0001_initial only -
Azure web app Error during WebSocket handshake
I am building a web app that uses web sockets , it is running just fine offline , but when hosted online on azure , it returns , if i am using port 443 failed: Error during WebSocket handshake: Unexpected response code: 302 or if i am using any other port (8080 , ...) failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT I have tried solutions like websockets connection does time out but with no success so far , in my azure account i have enabled websocekts and added * in cors the problem occurs when i write in my jaavscript $(document).ready(function(){ var socket = new WebSocket('wss://mywebsiteonazure.azurewebsites.net:443/chat/'); socket.onopen = websocket_welcome; ... ... -
Prompt auth (request.user) for password again before saving in Django admin
I'd like to prompt an auth user in Django admin to enter their password to verify it matches before saving a model (using save_model override). I thought this would be something simple to do, but can't find any documentation or threads on this. Thanks in advance. -
how to convert pdf file to Excel file using Django
I am trying to convert pdf file to Excel using Django, please anyone can please how to convert pdf to excel. I am trying, but the format does not working properly. -
How to integrate Django server with Nodejs SocketIO server
Im finding a solution in integrate Client, Django and NodeJS. My task is building a server which user can message to each other. I have 2 solutions: From Client send request to Django server. Django server will create Message in Database and push a notification to NodeJS server(SocketIO), then Client will get change from NodeJs server. With this solution, I want to ask how can I push request socket from Django to Node? From Client send request to Socket server. Socket server will create Message in Database, then send it to Client. This solution is good or bad? Need improved? I really need a solution to work. Please help me if your guys have experience! Thanks in advance! -
Cant render Objects and a Form in a CreateView class Django
I'm simply trying to render objects and a form with a Create view class. Whenever my page loads it renders the objects or the form but not both at the same time. Is There any way of doing that? Heres my code. Hopefully, I provided enough information urls.py - views.py - html template or file - models.py (if needed) - And The Page: -
how to load tasks in redis-server
I have created a celery file and task file but when I run Redis server, I cannot see my tasks loading. below is my celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EmailBot.settings') app = Celery('Emailbot',broker='ampq://localhost',backend='ampq: //localhost', include=['EmailBot']) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_url = 'redis://localhost:6379/0' # Load task modules from all registered Django app configs. app.autodiscover_tasks() CELERYBEAT_SCHEDULE = { 'every-day': { 'task': 'Bot.tasks.add', 'schedule': crontab(minute=1), }, } @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from celery import task @task def add(): print("hiiiii") below is my init.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) I added the following lines in settings.py CELERY_RESULT_BACKEND = 'django-db' CELERY_RESULT_BACKEND = 'django-cache' -
Exception value error: takes 1 positional argument but 2 were given
When I run my code I am getting this errors: In my URL patterns, if I write like this: path('', views.home, name='home'), I'm getting "init() takes 1 positional argument but 2 were given" error. If I write like this: path('', views.home.as_view, name='home'), I'm getting this error: as_view() takes 1 positional argument but 2 were given. Below is my class view: class home(ListView): template_name = 'home.html' model = Pull_Requests def get_queryset(self): return Pull_Requests.objects.all() And below is my home.html file {% block body %} <div class="container"> {% for field in object_list %} <table> <tr> <th>{{ field.pr_project }}</th> <th>{{ field.pr_id }} </th> <th>{{ field.nd_comments }} </th> <th>{{ field.nb_added_lines_code }}</th> <th>{{ field.nb_deleted_lines_code }}</th> <th>{{ field.nb_commits }}</th> <th>{{ field.nb_changed_fies }}</th> <th>{{ field.Closed_status }}</th> <th>{{ field.reputation }}</th> <th>{{ field.Label }}</th> </tr> </table> {% empty %} <strong> There is no pull request in the database. </strong> {% endfor %} </div> {% endblock %} Thanks for your help -
How to display data with value '0' in chart with chart.js?
I have a chart of 3 data-Chinese Book, English Book, Malay Book. Chinese book has 300, English Book has 400, Malay Book has 0. It works fine when I only display Chinese Book and English Book. When I add in Malay Book for display, it doesn't return errors but displays nothing. Here is my function for bar chart, function setChart(){ var ctx = document.getElementById("avgPageCount"); var avgPageCount = new Chart(ctx, { type: 'bar', data: { labels: {{ chartdata_labels|safe }}, datasets: [{ label: '# of votes', data: {{ chartdata_data }}, backgroundColor: {{ chart_bg | safe }} , borderColor: {{ chart_bd | safe }}, borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } } }); } window.onload = setChart; Malay book will return 0 since there is no new register book for this month. malay_book= Book.objects.filter(reg_date__range(current_month_first_day,today)).aggregate(Sum('total'))['total_sum'] _out_label.append('Malay Book') _out_data.append(malay_book) Is the chart won't display value with '0'? -
DRF: Cannot create a new object through admin interface
I am getting the following error when I try to create a new object through the admin interface: TypeError: unsupported operand type(s) for %: 'ImproperlyConfigured' and 'tuple' I have the following models: class CustomUser(AbstractUser): def __str__(self): return self.email class Meta: ordering = ('id',) verbose_name = 'user' class Address(models.Model): """Address contains information about location. Address can be own by any kind of model.""" content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True ) object_id = models.PositiveIntegerField(null=True) owner = GenericForeignKey("content_type", "object_id") CATEGORIES = Choices('billing', 'shipping') category = models.CharField(choices=CATEGORIES, max_length=16) address_1 = models.CharField("address line 1", max_length=128) address_2 = models.CharField("address line 2", max_length=128, blank=True) city = models.CharField(max_length=64) state_province = models.CharField('state/province', max_length=128) country = CountryField(blank_label='(select country)') zip_code = models.CharField(max_length=10) def __str__(self): return ( f'{self.address_1}, {self.city}, {self.state_province}, ' f'{self.country.name}, {self.zip_code}' ) class Meta: ordering = ('id',) class Company(Group): """An abstract base class that inherits Group.""" addresses = GenericRelation(Address) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)ss', related_query_name='%(class)s') logo = CloudinaryField('image', default='your_logo_here', null=True, blank=True) description = models.TextField('description', max_length=3000, blank=True) facebook_url = models.URLField('facebook url', blank=True) twitter_url = models.URLField('twitter url', blank=True) instagram_url = models.URLField('instagram url', blank=True) pinterest_url = models.URLField('pinterest url', blank=True) portfolio_url = models.URLField('portfolio url', blank=True) phone_number = PhoneNumberField('phone number', blank=True) class Meta: abstract = True ordering = ('id',) class Brand(Company): """A Brand can have … -
How can I create a database model in django and retrieve the data to display in listed menu?
I want to create the database table as shown in figure. After creating database table, I want to retrieve the data in table and display as checkbox type listed menu form to be submitted as shown in figure. And then display the selected item in admin page. -
I have React with MobX function not working in the order I expect. Any Ideas?
I am working on a React project the I am using Mobx for stores. I am getting the store to work right I am saving data without any problems. The one problem I am running into is I call a couple of functions and it seems to be they are being run backwards and I can not figure it out. I will list the code below, if someone could look at it with fresh eyes and tell me what I am missing. Main .js file componentDidMount(){ const query = parse(location.search); if (query.slug !== undefined) { this.props.IftaStore.getTruck(query.slug); this.props.IftaStore.load(); } else { this.props.IftaStore.setLimitByTruck(false); this.props.IftaStore.load(); } } I basically have a url get that I am getting called slug. I parse that then if it is not undefined I call a function called getTruck in my store (see below). Once getTruck is run then the function load should be called (also in the store). What seems to be happening is load is running then getTruck. store code: getTruck = async user => { const thisConst = this; let endpoint = '/api/equipment/truck/?driver=' + user; let lookupOptions = { method: "GET", headers: { 'Content-Type': 'application/json' } }; let data = []; try { const response …