Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError: <Registration: 749>" needs to have a value for field "id" before this many-to-many relationship can be used
I'm building a race registration application in django and I'm having trouble saving a many2many field of my model in a CreateView generic view. I am excluding the event field from the view because it allows you to select an event rather than having it automatically generated from the slug in the url. I was able to get the event object based on the URL using the slug in the get_context_data method. I have also tried form.instance.event = event in the form_valid method but it doesn't seem to be working here. I haven't worked with many2many fields before and I'm currently at a snag. Any help is greatly appreciated. I am receiving a ValueError: "" needs to have a value for field "id" before this many-to-many relationship can be used. views.py class RegistrationCreateView(CreateView): model = Registration fields = ['car_year', 'car_manufacture', 'car_model', 'race_number', 'race_class'] def get_context_data(self, *args, **kwargs): slug = self.kwargs['slug'] event = Event.objects.get(slug=slug) context = super().get_context_data(**kwargs) context['slug'] = slug context['event'] = event return context def form_valid(self, form): form.instance.driver = self.request.user try: event = Event.objects.get(id=self.request.POST['event']) except: event = None print("test") form.instance.event.add(event) return super().form_valid(form) urls.py from django.urls import path from . import views app_name = "events" urlpatterns = [ path( route='add/', view=views.EventCreateView.as_view(), … -
Get column names where searched value was found in Django
I have query that performs full text search on several columns (including on columns of models related using FK) in Django: from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank class TaskManager(models.Manager): def search_by_text(self, text: str): search_vector = SearchVector( "task_type__name", "order__registration_number", "order__report_number", "car_owner_name", "task_number", "order__customer_order_number", "order__customer_owner", "order__report_type__value", ) search_query = SearchQuery(text) return self.get_queryset().annotate( rank=SearchRank(search_vector, search_query) ).order_by("rank") How can I get not only found records but also column names where searched value was found for each record? Example: >>> Entry.objects.search_by_text("some value")[0].columns_matched ["task_type__name", "task_number"] I'm using Postgresql 10.12 and Django 2.2.10. -
TypeError: __str__ returned non-string (type int), error in Django application
My model is given below. class Year(models.Model): INT_CHOICES = [(x, x) for x in range(1, 14)] year=models.PositiveIntegerField(choices=INT_CHOICES, primary_key=True) student_count= models.IntegerField() assignment_count = models.IntegerField() tutor=models.CharField(max_length=200) def publish(self): self.save() def __str__(self): return self.year When i run the below code in python shell the following error occurs. There are some duplicate data in the Year table. I added those before making 'year' a primary key. >>> Year.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/agusmathew/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 253, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) File "/Users/agusmathew/myvenv/lib/python3.6/site-packages/django/db/models/base.py", line 519, in __repr__ return '<%s: %s>' % (self.__class__.__name__, self) TypeError: __str__ returned non-string (type int) -
Calculate Age in Django Model with database connection
I have seen many examples of calculating age in a django model (such as this question). However, most do not have a connection to a database and are simply empty models to be used in pushing to a database. To simplify my example, I have a django model of records of people connected to a SQL Server. I want to, when I query from the DB, also calculate the current age of the person. If I call age in my view, I get the following error: Cannot resolve keyword 'age' into field How can I do this, even though age is not a current database field? class Person(model.Model) personid = models.IntegerField(db_column='PersonId', primary_key=True) birth_date = models.DateField(db_column='DOB') @property def get_age(self): return relativedelta(self.birth_date.days, datetime.date.now()).years def save(self, *args, **kwargs): self.age = self.get_age() super(Person, self).save(*args, **kwargs) -
Problem with updating the css file used in my Django project
I am creating my first Django project and I want to create a css stylesheet for my project. The css file that I want to use is /static/css/main.css. I load the static file in my base.html template using: {% load static %} <head> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> The problem is that when I edit and save the main.css file, no change is visible on any of the webpages. When I checked the url 127.0.0.0:8000/static/css/main.css, it shows the css file, but only the old version before I edited it. I tried restarting both the development server and my virtualenv and making sure that I have saved the changes, but neither resolved the issue. When I viewed the page source code and clicked on the link to the css stylesheet, it still showed the old version on the url 127.0.0.0:8000/static/css/main.css. When I add styling inside the <style></style> tags, it works just fine. How do I make it so that it shows the new version of the css file? -
Django for loop checkboxes with same 'name', and then wanting to delete multiple instances
So in my Django template I have the following: upload_file.html <tbody> {% for file in files %} <tr> <td><a href="{{ file.file.url }}" download> {{ file.file }} </a></td> <td style="width: 185px;">{{ file.날짜 }}</td> <td style="width: 80px;">{{ file.file.size|filesizeformat }}</td> <td> <form method="POST" action="{% url 'delete_file' file.pk %}"> //want to change part like this<input type="checkbox" class="btn btn-danger btn-sm">Delete</input> {% csrf_token %} <button type="submit" class="btn btn-danger btn-sm">Delete</button> </form> </td> </tr> {% endfor %} </tbody> Which prints out a list of the members on the webpage, each with a submitbutton next to them. When I want to delete members I use a view in views.py def delete_file(request, pk): if request.method == 'POST': file = File.objects.get(pk=pk) file.delete() return redirect('upload_file') in urls.py path('files/'<'int:pk'>'/', views.delete_file, name='delete_file'), -
How to execute a binary file using shell Script inside a Docker Container?
I am running a Django app inside a Docker Container. I am calling a shell script to execute some tasks (I call this shell script using a python function not as docker command). It works fine when I am running it without the container. Both the shell file and Binary files are in the same directory. Following is the Sell script ./dsk -nb-cores 1 -max-memory 300 ./dsk2ascii Error showing was line 16: ./dsk: Is a directory line 17: ./dsk2ascii: No such file or directory -
Pass "form_class" to CreateView from url
It is possible to pass template to a Generic View from URL? path('address/', ListView.as_view(template_name='template.html')) But if I try doing it with form_class I get an error path('address/', CreateView.as_view(form_class='CreateForm')), I understand I can override it inside the class, but is it possible to do from URL? -
Django:SESSION_COOKIE_AGE is not working in Brave browser
settins.py SESSION_COOKIE_AGE = 6 I just set a SESSION_COOKIE_AGE that current log-in user will logout after 6 second.This is working in all famous browsers but in brave browser it is not working.Even after closing the brave browser user is logIn but Why this is only happen in brave browser. -
Difference between current datetime and DateTimeField
I'm been trying to get the difference between a DateTimeField and the current datetime Below is how I currently query objects: comment = Comment.objects.filter(ticket=ticket) The above query returns: comment user date_added I would like to compute the time that has passed since the comment was posted (like this -> ) I tried the code below but I'm getting the following: AttributeError: 'datetime.time' object has no attribute 'split' comment = Comment.objects.filter(ticket=ticket).annotate(duration=Func(F(datetime.datetime.now()) - F('comment_date_added'), function='age')) I'm thinking of extracting the date values as showing in https://docs.djangoproject.com/en/3.0/ref/models/database-functions/ and handle the calculation of the time difference on the frontend but I was wondering if I missed something or if there are better ways to solve this. Any help is much appreciated. -
Multiple language Api
What is the best way to implement a multi language http api with django and django rest framework? we have a client that can be use by people with different languages,in our app we have entities with detail, we want that detail be available in different languages per user by their preferences. Should I use different table for different languages?or there is a framework related solution?or an software architecture for this problem? Thank you. -
Django Rest Framework Email Validation invalid
I want to update a "employee" instance by sending PUT requests to Django Rest Framework. The Put requests fail due to failed email validation. model.py: class Employee(models.Model): Employees_id = models.AutoField('ID', primary_key=True) Employees_acn = models.CharField('Mitarbeiternummer', max_length=10) Employees_first = models.CharField('Vorname', max_length=200) Employees_last = models.CharField('Nachname', max_length=200) Employees_mail = models.EmailField('E-Mail', null=True, blank=True) Employees_deleted = models.BooleanField('Gelöscht', default=False) serializer.py: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' views.py: class Employee(APIView): permission_classes = [IsAuthenticated,BelongsToClient] serializer_class = EmployeeSerializer def put(self, request, pk, format=None): try: employee = EmployeeModel.objects.filter(Employees_deleted= False).get(pk=pk) except EmployeeModel.DoesNotExist: return HttpResponse(status = 404) serializer = EmployeeSerializer(employee, data=request.data) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) print(serializer.errors) return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) The failure doesn't depend on which email address I enter. All request I've tried failed. This is the error message (serializer.errors): {'Employees_mail': [ErrorDetail(string='Enter a valid email address.', code='invalid')]} I have no validation in my serializers class. Why do I get this validation error? Do I have to make any settings? -
Issue while hitting the external domain URL from Ajax
I have an API url http://127.0.0.1:5000/ that inputs image file and return the json value. Following is my HTML code, <form action="" enctype="multipart/form-data" id="myform" method="post"> {% csrf_token %} <br><br> <input type="file" id="file" name="file"/><br><br> <button type="button" class="btn btn-primary" id="add">Add To Table</button> </form> and here my ajax Code, <script> $("#add").click(function () { var files = $("#file")[0].files[0]; var fd = new FormData(); fd.append('file','files'); $.ajax({ url : "http://127.0.0.1:5000/", crossDomain : true, dataType : "jsonp", enctype: 'multipart/form-data', processData: false, contentType: false, cache: false, timeout: 600000, data : fd, success : function (data) { alert(data); } }); }); </script> When I execute the above code, in the console of Chrome, I can find this internal error. jquery-3.1.1.min.js:4 GET http://127.0.0.1:5000/?callback=jQuery31105839558115979158_1587729619868&[object%20FormData]&_=1587729619869 net::ERR_ABORTED 500 (INTERNAL SERVER ERROR) Can any one tell me why this error occuring and how can I resolve this ? Forgive me, I'm new to Ajax and rest APIs. Thanks. -
Django backend sourcecode protection
I have written backend code of a website and running it on cPanel. I need to be sure that nobody is able to access my backend code. What should I do? How can I reach this level of security? The works I have done: I put all my code in a folder with name p1 in my home/mydirectory, I mean it is outside of public_html. public_html just contains static file of css, js, bootstrap, and img. All of the .html templates are in template folder inside my application folder in p1. I changed DEBUG= True into DEBUG= False (to avoid information leakage from potential errors) I am trying to write SECRET_KEY= os.environ.get('SECRET_KEY') inside my settings.py and export it from somewhere else (.bash_profile file or .env) I made a .htaccess file inside my application folder (which nobody must be able to read/save the codes inside it). In this .htaccess I have written Order Allow, Deny Deny from ALL Inside my application folder (which now contains .htaccess) I have only __init__.py, admin.py, apps.py, forms.py, models.py, tests.py, urls.py, and views.py. These are the files which are important for me that nobody from visitors (or visitors as adversaries) must not be able read their … -
Api Root- Detail:Not Found (Django)
I am trying to authenticate user,i can see every detail when i open the api root but i encounter an error called "Detail:Not found" and can't authenticate. Can someone help? class LoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) username = serializers.CharField(max_length=255, read_only=True) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): username = data.get('username', None) password = data.get('password', None) if username is None: raise serializers.ValidationError( 'A username is required to log in.' ) if password is None: raise serializers.ValidationError( 'A password is required to log in.' ) user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError( 'Username and password was not found.' ) if not user.is_active: raise serializers.ValidationError( 'This user has been deactivated.' ) return { 'username': user.username, 'token': user.token } class LoginAPIView(APIView): serializer_class = LoginSerializer renderer_classes = (UserJSONRenderer) def post(self, request): user = request.data.get('user', {}) serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK) urlpatterns = [ url(r'users/login/', LoginAPIView.as_view()), ] I have tried to change things but it didn't work out as i wanted. -
Is there a way override DATA_UPLOAD_MAX_MEMORY_SIZE on one model field only
Is there a way to override the Django DATA_UPLOAD_MAX_MEMORY_SIZE default (2.5mb) on one model field only? I would like to keep the that max value the same everywhere except for one particular field, where it needs to allow for uploading of a much larger file size. I have implemented this solution which works well but I would rather not have to use this custom class for every file upload field in application. I would like to keep DATA_UPLOAD_MAX_MEMORY_SIZE at 2.5mb if possible. -
CMS login redirect to LMS dashboard after add SSL in Open edX
I am trying to add SSL in Open edX (Ironwood). As you know, In the Ironwood version, We can login CMS by using LMS login. Suppose that, LMS URL - https://lms.mydomain.com CMS URL - https://studio.mydomain.com When I click on the CMS login button it redirects to LMS (https://lms.mydomain.com/login?next=https%3A%2F%2Fstudio.mydomain.com%2F) URL. After login, it is redirecting to https://lms.mydomain.com/dashboard. Rather it should have redirected to this URL https://studio.mydomain.com/home It is working properly without using SSL and Domain. -
I got the message 'you have registered' but when I check in database, data is not save in database. When I reload the page the data is gone
Fullcalendar cannot update and save data. I got the message 'you have registered' but when I check in database, data is not save in database. When I reload the (index.html)page the data is gone. When I reload carenda/add_event/, data can be saved in database. In order to get the calendar, I know I need to write something but I don't know what should I write in path:'***' in index.html. I have searched on the internet for few days and tried to manipulate few things but I still cannot get it done. I'm still very new to Django, Javascript, JSON and Sqlite. Please help me. index.html <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'carenda/css/fullcalendar.min.css' %}"/> <link rel="stylesheet" href="{% static 'carenda/css/style.css' %}"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="{% static 'carenda/js/moment.min.js' %}"></script> <script type="text/javascript" src="{% static 'carenda/js/fullcalendar.min.js' %}"></script> <script type="text/javascript" src="{% static 'carenda/lang/ja.js' %}"></script> <script> // ページ読み込み時の処理 $(document).ready(function () { // カレンダーの設定 $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, timeFormat: 'HH:mm', selectable: true, selectHelper: true, navLinks: true, eventSources: [{ path: '***', dataType: 'json', async: false, type : 'GET', error: function() { $('#script-warning').show(); } }], select: function(start, end, resource) { var title = prompt("title:"); var … -
Django dropdown form with multiple/dynamic models
So i got multiple datatables which i transfered to django models. Now i want to build a form(do i need a form for this?) which allows the user to select the desired modelname out of a dropdown menu. Accordingly to the chosen model, the other form fields will adapt accordingly to the model's different attribute fields. Can someone push me in the right direction on how to do this? Do i need forms? Do i load the informations of all the models in the form and change it with javascript? Do i render the page again each time something's picked? I just started with django and webdev so i don't know the best practice -
Django one to many between legacy tables with no PK to FK relation
I am using legacy DB tables that I have no control over the tables design. Table A has an auto_gen ID field as follows: TableA (One Side) id (numeric auto gen, primary key) fld1 (string, unique but not a primary key.) fld2 (String) fld3 (date) TableB (Many side) id (numeric auto gen, primary key) fld1 (string, not unique, but it is the target many side) fld4 (String) fld5 (date) I am trying to use Djano models to establish a one to many relation between Tables A and B using fld1. I have done same in Java, but so far, it seems that Django won't allow it. Django seems to expect that one side must be a PK? I do realize that Django has many to one (instead of one to many) and followed the documentations ... but it is not working. Please advise if there is a way to do this in Django models framework. -
Modifying Sign Up tab created using django framework
I have made a sign up tab that registers new users and log in page that allows the registered users to continue with the site. I want if any registered user (having a registered email) tries to sign up again , an error message should pop up saying 'You are already having an account. Please Log in'. I stored the data(s) of registered user(s) in a table created in models.py named SignedUpUsers. Please help me achieve my task. models.py # Create your models here. class SignedUpUsers(models.Model): email = models.EmailField(max_length=122) name = models.CharField(max_length=122) username = models.CharField(max_length=122) password = models.CharField(max_length=122) date = models.DateField() def __str__(self): return self.name views.py from Home.models import SignedUpUsers from django.contrib import messages from datetime import datetime def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') cont = SignedUpUsers(name=name,email=email,username=username,password=password,date=datetime.today()) cont.save() messages.success(request,"\t\tYour account has successfully been created . Kindly Log In\t\t") return render(request, 'signup.html') signup.html <!--Form--> <form method="post" action="/signup" style=" position: absolute; top: 260px; left: 500px; font-size: larger; "> {%csrf_token%} <!--Email--> <div class="form-group" > <label for="email">Email address</label> <input type="email" size="25" class="form-control" id="email" name="email" placeholder="name@example.com" style="block-size: 25px; position: absolute; left: 120px;"> </div> <!--Name--> <div class="form-group" > <label … -
How to specify filepath for celery task logs?
I have created some REST APIs using Django and I am using Celery to run some asynchronous jobs. The API is defined in api.py and the asynchronous job functions are in actions.py Here is what my api.py looks like: from myproject import actions def sample_api(request): actions.sample_job.delay() return HttpResponse('success') Here is what my actions.py looks like: from celery.utils.log import get_task_logger from celery.decorators import task logger = get_task_logger(__name__) @task(name="sample_job") def sample_job(): logger.info("start operation") <some operations> logger.info("stop operation") Now the problem is that I don't know where the logs are getting written. I've tried searching in the project directories and I dont see it anywhere. I want to provide a path to the log file where these logs should be written. How do I provide a path to the logfile in celery? (I know there are multiple questions in StackOverflow regarding this. But none really mention how to specify a filepath for the logfile) -
How to get cookie after login on a same domain login system?
I am creating a MiddleWare to authenticate the user (using a 3rd party login system of same domain) before accessing any view. In process_view method I am checking request.cookies to see the cookies and check whether cookie has user_id which will be set after a user login on the 3rd part login system having same domain if yes then I allow it to access the views otherwise I redirect It to the login page. Now the issue is that my Django app redirects to the login page and when I log in the login system, I see developer tools and I notice cookie is being set successfully but no cookie is returned in request. I searched the solution to this problem I got this solution on stack overflow - Python Requests get cookies values after authentication but sadly this only return user_data is authenticated in cookie and that is set to flash even after login into the system successfully.Here is a rough code of my Middleware- import json from django.http import HttpResponseRedirect import requests class UserAuthMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_fund, view_args, view_kwargs): r = requests.get("https://example.com/login/") print(r.cookies) … -
Issue with admin static files in Django 3 (Ubuntu, Nginx, Gunicorn, SSL)
I using Django 3.* for my project and everything works fine since i've installed SSL from Let's Encrypt by Certbot and sinse then i have an iisue with serving static files in my admin. My Nginx config: server { server_name casekam.ru www.casekam.ru; client_max_body_size 100M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/gleb/casekam/django_shop/django_shop/static/; } location /media/ { alias /home/gleb/casekam/django_shop/django_shop/media/; } location / { include proxy_params; proxy_pass http://unix:/run/casekam.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/casekam.ru/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/casekam.ru/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.casekam.ru) { # return 301 https://$host$request_uri; return 301 https://casekam.ru$request_uri; } # managed by Certbot if ($host = casekam.ru) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name casekam.ru www.casekam.ru; return 404; # managed by Certbot } Can't figureout where am i wrong. Will be appriciate for any hints and tips. -
Django Date Filter with REST with Prefetch / How to make a date range?
Now, in my CoincostFilterSet class, the start date for the result filter is set. And how to set the end date in my code? now i have this url http://example.com/api/v1/CoinCost/?symbol=MNST&timestamp=2020-04-20T09:17:34 but need http://example.com/api/v1/CoinCost/?symbol=MNST&timestamp=2020-04-20T09:17:34&timestamp=2020-04-23T05:17:34 To get the results from April 20 to 23. filters.py class DateTimeGteFilter(filters.IsoDateTimeFilter): def filter(self, qs, value): if value != None: return qs.prefetch_related(Prefetch('coincosts_set', to_attr='filtered_coincosts', queryset=CoinCosts.objects.filter(timestamp__gte=value) ) ) else: return qs views.py class CoinCostFilterSet(filters.FilterSet): timestamp = DateTimeGteFilter() class Meta: model = Coins fields = { 'symbol': ['exact'], } serializers.py class CoinSerializer(serializers.ModelSerializer): class Meta: fields = ('symbol', 'crr', 'costs') model = Coins costs = CoinCostsSerializer(source='filtered_coincosts', many=True) Help.Thanks!