Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper way to upload an image and metadata to aws using django
I am trying to upload images to aws using django. At first I wanted to use s3. It is fairly simple. However images contain metadata, like title and tags. And I want to be able to search using these things. Is s3 suitable for this kind of job. Another recommendation was upload images to s3 and url and metadata to another db. But I don't know how to do that or is it even possible Note: I want to use django admin. -
how to run a mysql service with local image
I want to wget a dump file hosted on another service. So I created a Dockerfile with the command to run wget the dump file. But somehow my mysql server doesnot run and gives an error Here is my Dockerfile: FROM python:2.7-alpine RUN apk update && apk add bash curl && apk add mysql-server COPY ./compose/local/db/dump_sql.sh /dump_sql.sh COPY ./compose/local/db/getmeashop.sql /getmeashop.sql RUN sed -i 's/\r//' /dump_sql.sh RUN chmod +x /dump_sql.sh CMD mysql start \ Here is my dump_sql.sh file: #!/bin/sh echo "stating the wget" wget https://gmas-core-media.s3-ap-southeast-1.amazonaws.com/getmeashop.sql -O ./getmeashop.sql echo "ending the wget" cp ./getmeashop.sql /docker-entrypoint-initdb.d/getmeashop.sql echo "Running it" mysql start And here is the Service: db: image: mysql:5.7.10 environment: MYSQL_DATABASE: gmas_matrix MYSQL_ROOT_PASSWORD: root ports: - '3306:3306' command: /dump_sql.sh build: context: ./ dockerfile: ./compose/local/db/Dockerfile volumes: - my-db:/var/lib/mysql - ./compose/local/db/getmeashop.sql:/docker-entrypoint-initdb.d/getmeashop.sql Thanks in advance. -
django restframework check permission before function
Im checking permission before the POST method in an APIView like this: class ResultDataApi(APIView): ... authentication_classes = (JWTAuthentication,) permission_classes = ([permissions.IsAuthenticated, CheckReadPermission]) def post(self, request): Now I want to check another permission when executing a function inside of the post methode, something like this: in views.py execute_command_function(...) decorating the function @permission_classes(CheckUpdatePermission, ) def execute_command_function(...) also tried it as in the first step, but not working: permission_classes = ([permissions.IsAuthenticated, CheckReadPermission]) cmd_output_data[cmd_key] = execute_command_function(...) -
how do I print the classes and fields from within a models.py?
In the terminal python manage.py shell I am trying to import django.db.models I want to see what classes and fields are within it I also want to determine which directory location models.py is located in How can I do this? -
Djano query object.values() list as parameter
I currently have a query that looks similar to this: Account.objects.filter(id__in=id_list).values("id", "first_name", "last_name") Is there a way to pass a list into the values? (I've tried this, that's why I'm asking) Sort of like: value_list = ["id", "first_name", "last_name"] Account.objects.filter(id__in=id_list).values(value_list) -
Hosted django app on heroku, how would I go about creating images in models
Hi so I have an app where for every model object I create an image and so far I've made it so you manually create the images for multiple objects through an admin action. When I've run it locally it saves to the media folder but now I've deployed it to Heroku, so right now they're created but disappear into the ether. I want the user to be able to print the images so where do they go? -
I want to insert the data of the students in the database.please elaborate to me and how to show the data in the table specially date-of-birth
I have seven fields for entering the data in the database , e.g(Student id,first name, last name,major,phone, gpa and date-of-birth) But the criteria is that i have to create the Date class containing Day,Month,Year as fields and i'm struggling to do this. I also want know to create the different fields in the models file and how the data will entered from the form. How is this work in the views file. Below the html code for fetching data from the user and i use the input fields in the type of text(type="text") But for date i used the(type="Date") The views file,in this file i just entered the data in the simplest manner cause i don't know how to split the day, month and year for entering the data in the string. The Models File Code,in this file i created the two table classes for entering the data. the first class is Date class which will store the data separately for the day, month and year The another table class is Student, firstly which will use the date class with the forgeinkey to store the data in the table along with the other fields. HTML CODE:- <div class="custom-file"> <input type="Date" … -
How to make django-crispy-forms input field to take the entire available width?
I can't manage to make the input widget in the following form to take all the available width in the page. Any ideas? I am using Django 2.2.5, django-crispy-forms 1.7.2 & Bootstrap 4. Since I am already asking, is it possible to make the input field resizable by the user? In the form, I also tried: Field("name", css_class="w-100") forms.py class ProjectsForm(forms.ModelForm): """ Class to create/edit a new profile. """ name = forms.CharField(max_length = 300, required=True) class Meta: model = Projects fields = ['name',] #--- def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Field("name", style="width: 1000px;") ) #--- #--- template: {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New project</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Create</button> </div> </form> </div> {% endblock content %} -
Redirect to the filtered list in Django Admin
Suppose, I have a modelA and modelB, that has ForeignKey relationship with modelA On the any modelA object page in Django Admin, I would like to have a link to the filtered list of modelB instances that have the relationship with that modelA instance. For example: From /admin/my_app/modelA/1/change/ I would like to access /admin/my_app/modelB/?modelA__id__exact=1 -
What`s the problem of "Instance of 'DateTimeField' has no 'year' member" in python django2?
I am learning web develpoment by django. I am coding according to the book django2byexample. I found a problem that the book hasn't include My VScCode printInstance of 'DateTimeField' has no 'year' member Could someone tell me what` the problem?Thank you. Here is the code: def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) -
How we can use Django CRM?
Please someone help me to know what is use of Django CRM? How we can use it.I know this i can search in Google but i want know it from some real time professionals. Can someone please aware me about Github CRM project?. -
Comment model has replies, but reply cannot have replies
I am creating comments. Each comment can have replies, but replies cannot have replies. I have tried to perform this on serializer and views level, but nothing works. model: class Comment(models.Model): reply_to = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE, related_name='replies') Serializer: class CommentSerializer(serializers.ModelSerializer): episode = serializers.PrimaryKeyRelatedField(read_only=True) user = serializers.StringRelatedField() class Meta: model = Comment fields = '__all__' def validate_reply_to(self, value): if value: comment = Comment.objects.get(pk=value) if comment.reply_to: raise serializers.ValidationError('Cannot reply to reply') Viewset: class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer def perform_create(self, serializer): try: episode = Episode.objects.get(id=self.kwargs.get('episode_id')) except Episode.DoesNotExist: raise NotFound serializer.save(episode=episode, user=self.request.user) -
HTML/Jinja2: Calendar getting displayed below meetings
I am making a web app in Python/Django and I am trying to display a calendar above some meetings on the Dashboard page of the app. I have made a calendar using the HTMLCalendar class, and I have passed both the list of meetings and the calendar as variables to the HTML template to be rendered. These variables are called meetings and calendar respectively. I have the following code for dashboard.html, which has the code for displaying the meetings and the calendar: {% extends 'Project/base.html' %} {% load static %} {% block title %}Dashboard{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "css/calendar.css" %}"> {% endblock %} {% block content %} <body style="width:100%; height:100%"> {% if calendar %} <div id="calendar"> {{ calendar }} </div> {% endif %} {% if meetings|length > 0 %} <div id="gallery" style="width:80%; height: 100%; margin-left:12.5%; margin-top: 3%; padding: 2%;"> {% for meeting in meetings %} <div style="width: 38.5%; height: 400px; border: solid 2px #f4b955; display:inline-block; border-radius: 10px; padding:2%; margin-right: 3%; margin-bottom: 2%; box-shadow: 2px 4px #f4b955"> <div id = "left" style="height: 100%; width: 50%; display: inline-block"> <div id="top-left" style="height: 100%"> <img src="{{meeting.image}}" style="height: 100%; width:100%; object-fit: contain; display: block"> </div> </div> <a href="{% url … -
Unit test failing due to migration error caused by loaddata in django
My unit test are failing with the following error django.db.utils.OperationalError: Problem installing fixture '/Users/vivekmunjal/chargepoint/code/Installer/api/installer/fixtures/country.json': Could not load installer.Country(pk=1): (1054, "Unknown column 'display_order' in 'field list'") Basically one of my migrations is loading data in country model from a fixture, but the model has added some extra fields in them, so when the migrations runs it try to insert a column which is not yet created and fails. Can anyone suggest any remedy for the same? -
I'm not able to run sonnarqube on my project
I've installed both sonarqube server as well as scanner and chnaged the properties file also.But still it's giving the below issue. ERROR: Error during SonarQube Scanner execution java.lang.IllegalStateException: Project home must be an existing directory: C:\Django\webapplication\webapplication\Djangowebapplication I've my project in the C:\Django\webapplication directory.Below is my configuration file for sonar-project.properties file sonar.projectKey=devsonarqube sonar.projectName=webapplication sonar.projectVersion=1.0 sonar.projectBaseDir=C:\Django\webapplication sonar.sources=C:\Django\webapplication -
Post JSON data via API and create a related model in Django Rest Framework
I am performing an API project with the Django Rest Framework. I have a Django model defined in the following way: class Profile(CreatedUpdatedModel, models.Model): owner = models.ForeignKey(Owner, models.CASCADE) start_date = models.DateField(gettext_lazy("Start"), help_text=gettext_lazy("YYYY-MM-DD format")) end_date = models.DateField(gettext_lazy("End"), help_text=gettext_lazy("YYYY-MM-DD format")) category = models.ManyToManyField(OwnerCategory) tags = models.ManyToManyField(OwnerTag) I perform a POST API call from the web page that pass a JSON data like the following : {start_date: '2019-11-20' , end_date: '2019-11-21', owner: '65', category: '[20, 21, 22]', tags: '[]' } I would like to save on the database the model with the parameter I passed with JSON Here is my REST view in views.py: @permission_required() class ProfileViewSet(ViewSet): @action(detail=False, methods=['post']) def new_profile(self, request, pk=None): serializer = serializers.ProfileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here it is my REST serializer in serializers.py class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('owner', 'start_date', 'end_date', 'categories', 'tags', ) The problem is that the statement serializer.is_valid() is False. Where I am wrong with this code ? Can someone help me ? -
How to use sphinx to document django: blacklisting and whitelisting modules in settings?
I am running a django project with multiple apps. I am trying to document it using sphinx. I installed sphinx and configured everything (-I think correctly-). To produce documentation I run sphinx-apidoc -o . .. and then make html. Now what happens is that sphinx creates modules for all my migrations but it doesn't include any views (which I guess is most important). Problem could be all the import errors: (I don't want to install all the imports in my virtual env) WARNING: autodoc: failed to import module 'adapters' from module 'myapp.users'; the following exception was raised: No module named 'allauth' WARNING: autodoc: failed to import module 'admin' from module 'myapp.users'; the following exception was raised: Traceback (most recent call last): .....this keeps going for a while like this WARNING: autodoc: failed to import module 'merge_production_dotenvs_in_dotenv'; the following exception was raised: No module named 'pytest' WARNING: autodoc: failed to import module 'admin' from module 'myapp'; the following exception was raised: No module named 'psycopg2' WARNING: autodoc: failed to import module 'models' from module 'myapp'; the following exception was raised: No module named 'psycopg2' WARNING: autodoc: failed to import module 'urls' from module 'myapp'; the following exception was raised: No module … -
Add ajaxresponse inside a textarea
I have made an ajax call to backend using the following code: <script > var frm = $('#identity'); var textare = $('#textare'); textare.keyup(function() { $.ajax({ type: frm.attr('method'), url: "{% url 'creatd-new' %}", data: frm.serialize(), success: function (data) { $('#some_div').html(data.is_true); }, }); return false; }); </script> backend dumps a "is_true" in the JsonResponse which successfully gets printed but when I try to print the same value of "is_true" inside a text area,it is not working. I have tried the following: $('#some_div').html( <textarea rows="4" cols="50">data.is_true</textarea> ); $('#some_div').val( <textarea rows="4" cols="50">data.is_true</textarea> ); $('#some_div').append( <textarea rows="4" cols="50">data.is_true</textarea> ); but these are not working. -
pyodbc session error when django project is downloaded from gitlab
i have a django project which works fine when not uploaded i have uploaded it to gitlab with following command: 1. git clone ssh://git@gitlab****dcms-api.git 2. git checkout dcms_sso 3.git add . then i took the same code from git lab: 1. git clone ssh://git@gitlab****dcms-api.git 2. git checkout dcms_sso just changed the application name in manifest file. when i tried to run it throws following error: File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect ERR self.connection = self.get_new_connection(conn_params) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/sql_server/pyodbc/base.py", line 307, in get_new_connection ERR timeout=timeout) ERR pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") ERR The above exception was the direct cause of the following exception: ERR Traceback (most recent call last): ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/core/handlers/exception.py", line 34, in inner ERR response = get_response(request) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/utils/deprecation.py", line 93, in __call__ ERR response = self.process_response(request, response) ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response ERR request.session.save() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 81, in save ERR return self.create() ERR File "/home/vcap/deps/1/python/lib/python3.5/site-packages/django/contrib/sessions/backends/db.py", line 51, in create ERR self._session_key = self._get_new_session_key() please let me know if more log to be uploaded or if my backend.py should be uploaded -
Error db.sqlite3 locked when deploying Django using option Continuous deployment in Azure App Service
When i'm deploying a Django project (tried two of them) in Azure App Services (Linux), i always get the error SQLite3 database locked: OperationalError: database is locked,when trying to log in. Has someone an idea or workaround to resolve the problem without changing to another database? I changed the default timeout as mentioned by the official django documentation: https://docs.djangoproject.com/en/2.2/ref/databases/#sqlite-notes, but the problem remain. I want to keep using sqlite database! Thanks for your help. -
Return some variables from a function in views.py to a js file with render and POST - Django
Since some days I'm trying to execute a python function from my js file. I'm doing it with Ajax. For now, I'm executing the function and passing some values with POST but I can recover this info. This is my function inside views.py def vista_sumar(request): ctx = 'none' if request.method == 'POST': a = request.POST['a'] b = request.POST['b'] c = int(a) + int(b) ctx = {'Result':c} print('sss',ctx) return render(request,'main.html',ctx) I know the call to this function is working because in the js file a=3 and b=1 and it always print sss {'Result': 4} but then it never comes back to the js. I try it too with return HttpResponse(c) and the behaviour is better because arrive something to the js but it is undefined. Can't I use render in this situations? Can somebody help me, please? My js is: $('#prueba').click(function() { alert('boton pulsado'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); alert(csrftoken) a =1; b =3; $.ajax({ url: '/../../prueba/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'a': a, 'b': b, }, dataType: "json", cache: true, success: function(response) { console.log(response.Result); alert(response.Result); } }); alert('fin') }); With return HttpResponse(c) the console.log and the alert show undefined. Thank you very much. -
Django templates lookup through list nested in dictionary
I have nested json response, which i have to render in template, but not full output, just selected items. The problem with lookup is that this list have dictionary with another list inside and i need to get value from there. json [ { "type": "part", "id": "TESTA_SSL", "attributes": { "commut": "YES", "imaxtime": "23595999", "imintime": "00000000", "prot": [ "PESITSSL" ], "rauth": "*", "sap": [ "6666" ], "state": "ACTIVEBOTH", "trk": "UNDEFINED", "syst": "UNIX", "tcp": [ { "type": "cfttcp", "id": "1", "attributes": { "cnxin": "2", "cnxinout": "4", "cnxout": "2", "retryw": "7", "host": [ "testa.net" ], "verify": "0" } } ] }, "links": { "self": "https://testa.net:6666/api" } }, { "type": "part", "id": "TESTB_SSL", "attributes": { "commut": "YES", "imaxtime": "23595999", "imintime": "00000000", "prot": [ "PESITSSL" ], "rauth": "*", "sap": [ "6666" ], "state": "ACTIVEBOTH", "trk": "UNDEFINED", "syst": "UNIX", "tcp": [ { "type": "cfttcp", "id": "1", "attributes": { "cnxin": "2", "cnxinout": "4", "cnxout": "2", "retryw": "7", "host": [ "testb.net" ], "verify": "0" } } ] }, "links": { "self": "https://testb.net:6666/api" } }, ] i need to lookup for TESTA_SSL, testa.net and TESTB_SSL, testb.net value from template level. How can I do that? Or is there a possibility to "flatten" lil bit this json? for now … -
Django throwing "app not ready" while calling function in it's AppConfig.ready
I am using django v2.2.6. I am trying to implement my own system checks. I followed the documentation and even StackOverflow: Register system checks in appconfigs-ready. I am still getting an django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. According to the stack trace, it goes back to the first Model declared before calling self.checks_app_ready() and throwing the previous exception. I have only one App, so I do not understand why it is not ready when I try to register a check in my AppConfig.ready(self). -
Django include app urls in my main url.py
I have a django site with 3 application. in my urls.py i try to include the specific app's url in this fashion: url(r'^oferty/', include('oferty.urls', namespace='oferty')), but when i start or migrate my app i get this error: ../site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. How can i include apps urls in my main url.py file? I use django 2.2 so many thanks in advance -
Django Move Project from Windows Host to Linux Host (and Deploy)
I'm trying to Move my Django App to a real Server (or deploy it there, self-hosted) but everything, I have tried so far, does nothing except displaying errors. For Example: If I try to deploy the app on my Windows machine I get security errors he won't pass. py -3 manage.py check --deploy System check identified some issues: WARNINGS: ?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting. If your entire site is served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems. ?: (security.W008) Your SECURE_SSL_REDIRECT setting is not set to True. Unless your site should be available over both SSL and non-SS L connections, you may want to either set this setting True or configure a load balancer or reverse-proxy server to redirect all connections to HTTPS. ?: (security.W018) You should not have DEBUG set to True in deployment. System check identified 3 issues (0 silenced). Even if I set Debug to False he won't pass the last two Security Checks. AND in Debug State False the Website even does not load …