Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework : Correct way to override perform_create in ModelViewSet ?
In Django Rest Framework when an insert takes place on one model I would like to do updates/inserts on other models. I'm working with a ModelViewSet and I've tried overriding the perform_create method but the original insert is just swallowed, no update takes place and no errors are seen. I've tried doing this def perform_create(self, serializer): serializer.save() but although no error is thrown no update takes place either. Would appreciate an example of overriding perform_create so that the original insert still takes place but there is scope for doing other updates/inserts at the same time. I'm using DRF 3.5.3 . -
Post request send by JQuey was treated as Get Request
I tried to send POST request through JS: <div> <h4>Comments</h4> <form method='POST'> <textarea class="form-control" id="commentContent" rows="5" name='comment'></textarea> <br> <button type="submit" id="commentBtn" class="btn btn-primary">Post Your Comment</button> </form> </div> </div><!--class="col-xs-8 col-md-8"--> </div><!-- row --> <script type="text/javascript" src="/static/js/jquery-3.3.1.min.js"></script> <script type="text/javascript" src="/static/js/jquery.csrf.js"></script> <script> $(document).ready(function(){ var article_id = {{ article.id }}; var page_number = {{ page.number }}; $("#commentBtn").click(function(){ var comment =$("#commentContent").val(); var param = {"article_id":article_id, "content":comment}; $.post("/article/comment/create/", param, function(data){ var ret = JSON.parse(data); if (ret["status"]=="ok") { $("#commentContent").val(""); window.location.href="/article/detail/{{ article.id }}?page_number={{ page.num_pages }}" \\change to the final page }else{ alert(ret["msg"]); } }); }) }); </script> It instantly remind the following error: [13/Jun/2018 18:54:35] "GET /article/detail/16?comment= HTTP/1.1" 200 5085 [13/Jun/2018 18:54:38] "GET /article/detail/16?comment=rr HTTP/1.1" 200 5085 [13/Jun/2018 18:54:42] "GET /article/detail/16?comment= HTTP/1.1" 200 5085 I have created a to handle the csrf token following Cross Site Request Forgery protection | Django documentation | Django However, the post request failed to send and was treated as get request. How could I solve such a problem? -
Unable to get Set-Cookies header from a Django API
I am getting these errors when I am trying to hit a Django API. I have used ReactJS for Frontend and DjangoREST for Backend. When withCredentials is set False, I got this error. Failed to load https://retailo-dot-dogwood-keep-190311.appspot.com/admin/: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. login-form.jsx:58 When True, I got this error. Failed to load https://retailo-dot-dogwood-keep-190311.appspot.com/admin/: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. I have used Axios and this is my code. axios.get('https://retailo-dot-dogwood-keep-190311.appspot.com/admin/',{ // withCredentials: true, headers: { 'Access-Control-Allow-Origin': 'include', 'Content-Type': 'application/json', }, // credentials: 'same-origin', }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); -
Django 1.11: Float in query param in url
TLDR: How can I accept floats as query params in a url? I have written an API view with Django Rest Framework. The API should be able to list houses by their addresses' coordinates using a GET request. Meaning the user should be able to send a query containing the coordinates as a get request and should get back a list of all the houses around these coordinates Here is the view (views.py): class HouseListAPIView(generics.ListAPIView): serializer_class = HouseListSerializer queryset = House.objects.all() def get_queryset(self): qs = self.queryset longitude = self.request.query_params.get('lon', None) latitude = self.request.query_params.get('lat', None) radius = self.request.query_params.get('radius', 1) if radius < 0 or radius >= 1: radius = 1 if longitude is not None and latitude is not None: qs = qs.filter( address__coordinates__latitude__lte=get_lat_max(longitude, latitude, radius), address__coordinates__latitude__gte=get_lat_min(longitude, latitude, radius), address__coordinates__longitude__lte=get_lon_max(longitude, latitude, radius), address__coordinates__longitude__gte=get_lon_min(longitude, latitude, radius) ) return qs Here are the helper functions (utils.py): import geopy from geopy.distance import VincentyDistance def get_lat_lon_values_from_radius(d, lat1, lon1, b): """ given: lat1, lon1, b = bearing in degrees, d = distance in kilometers """ origin = geopy.Point(lat1, lon1) destination = VincentyDistance(kilometers=d).destination(origin, b) lat2, lon2 = destination.latitude, destination.longitude return lat2, lon2 def get_lat_max(lat1, lon1, d=1): # latitude = north / south return int(get_lat_lon_values_from_radius(d, lat1, lon1, 0)[0]) … -
Interprocess communication using django channels is failing after one hour
I have a product an ERP where it needs real-time bidirectional interprocess communication between nodejs and Django. Right now I am using npm WebSocket and Django channels. During development using "python manage.py runserver", it works fine. But during production, django recommends daphne and runworker. I have tested that with nginx. Right now my issue is, connection is getting disconnected after a certain time. In Django(1.9) connection lasts around 24 hr. After I changed to Django2 connection lasts only for 1 hour around. The system didn't show any errors. My configuration is given below. nginx.conf server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; server_name 209.97.166.79; #location /static/ { # alias /<project-static-files-path>/static/; # expires 1y; #} location / { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; }} Project structure . ├── db.sqlite3 ├── django_two_main │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── asgi.cpython-35.pyc │ │ ├── __init__.cpython-35.pyc │ │ ├── routing.cpython-35.pyc │ │ ├── settings.cpython-35.pyc │ │ └── urls.cpython-35.pyc │ ├── routing.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── README.md … -
Overriding django_admin's list_display into cascadingdropdown style
I've been searching this for days, got some progress but something stop me. I'm trying to override the django xadmin's list_display into "Chained Select Boxes"/"Cascading dropdown list" style, like the "country state city". i've add some select javascript into '/xadmin/views/model_list.html' but i do not know how can i transfer the data result from my database into this javascript. Anybody could show me? thanks in advance. -
Celery crontab misbehaves, spawns task every 5 minutes
I am using celery PeriodicTask and it is set via the below code: @periodic_task(name='download_latest_trademarks', run_every=crontab(hour='*/2', minutes=0))` Alos, I have set celery timezone settings as follows: CELERY_ENABLE_UTC = False CELERY_TIMEZONE = 'Asia/Kolkata' My task with eta are running good, but periodic tasks are spawning every 5 minutes. PS: I have already purged the tasks in queue, deleted celerybeatschedule.db file too. -
validate_unique causes RelatedObjectDoesNotExist when calling form.is_valid()
I have a Problem that i just cant understand. Assume we have the following 2 Models: from django.db import models class OtherModel(models.Model): number = models.PositiveIntegerField() class MyModel(models.Model): name = models.CharField(max_length=15) other_obj = models.ForeignKey(OtherModel) deleted_at = models.DateTimeField(blank=True, null=True) and a simple ModelForm based on MyModel: from django.forms import ModelForm class MyForm(ModelForm): class Meta: model = MyModel fields = ['name', 'other_obj'] which is tested by a simple pytest method: def test_myform(): form = MyForm(data={}) assert form.is_valid() is False This works totally fine (test wont fail), until i add a validate_unique method to MyModel: from django.core.exceptions import ValidationError # ... class MyModel(models.Model): # ... def validate_unique(self, exclude=None): super(MyModel, self).validate_unique(exclude=exclude) qs = MyModel.objects.filter(other_obj=self.other_obj) if qs.exists() and qs[0].pk != self.pk: e = qs[0] raise ValidationError('This OtherModel ({}) was already used already exists'.format(e.other)) Which gives me the following Error Message (RelatedObjectDoesNotExist: MyModel has no other_obj): F myapp/tests/test_forms.py:66 (test_myform) def test_myform(): form = MyForm(data={}) > assert form.is_valid() is False test_forms.py:69: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../venv/lib/python3.6/site-packages/django/forms/forms.py:183: in is_valid return self.is_bound and not … -
I'm able to load Static file but css and js not working in Django
I have loaded Css, js in html page but the style was not working. please help me do that. Html Page image 1) Html screen css code image 2) Css code Chrome Console 3) Console screen Here i have mentioned my 3 screen shots of my code. -
Django queryset : how to change the returned datastructure
This problem is related to a gaming arcade parlor where people go in the parlor and play a game. As a person plays, there is a new entry created in the database. My model is like this: class gaming_machine(models.Model): machine_no = models.Integer() score = models.Integer() created = models.DateTimeField(auto_now_add=True) My view is like this: today = datetime.now().date() # i am querying the db for getting the gaming_machine objects where score = 192 or 100 and the count of these objects separately for gaming_machines object which have 192 score and gaming_machine objects which have score as 100 gaming_machine.objects.filter(Q(points=100) | Q(points=192),created__startswith=today).values_list('machine_no','points').annotate(Count('machine_no')) # this returns a list of tuples -> (machine_no, points, count) <QuerySet [(330, 192,2), (330, 100,4), (331, 192,7),(331,192,8)]> Can i change the returned queryset format to something like this: {(330, 192):2, (330, 100) :4, (331, 192):7,(331,192):8} # that is a dictionary with a key as a tuple consisting (machine_no,score) and value as count of such machine_nos I am aware that i can change the format of this queryset in the python side using something like dictionary comprehension, but i can't do that as it takes around 1.4 seconds of time to do that because django querysets are lazy. -
Django: formset errors without li / *
I am using a formset. formset.non_form_errors are displayed exactly the way I need it. However my field specific errors in for dict in formset.errors are always displayed inlcuding the <li> tag. I tried .as_text, however that just added a * (and removed the li). But I don't need the * either. Anyone who can help me with that? {% if formset.total_error_count %} {% if formset.non_form_errors %} {% for error in formset.non_form_errors %} <div class="alert alert-warning" role="alert"> {{ error|escape }} </div> {% endfor %} {% endif %} {% for dict in formset.errors %} {% for error in dict.values %} <div class="alert alert-warning" role="alert"> {{ error|escape }} </div> {% endfor %} {% endfor %} {% endif %} <form method="post"> {% csrf_token %} {{ formset.management_form }} -
Exception: invalid literal for int() with base 10: ''
I am using model for keeping user info like profile picture and bio etc, but when i am signing up this error occurs. Here is the code class UserProfile(models.Model): user = models.OneToOneField(User, on_delete='CASCADE') description = models.CharField(max_length = 500, default='', blank = True) city = models.CharField(max_length = 100, default='', blank = True) website = models.URLField(default='', blank = True) phone = models.IntegerField(default='', blank = True) image = models.FileField() @receiver(post_save, sender = User) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() -
Django REST "A valid integer is required" on updating null=True IntegerField
I followed Django Rest Framework "A valid integer is required."? to setup SpiderSerializer, but seems not working, still getting {"min_word_count":["A valid integer is required."]} Request Payload {..., min_word_count:""} class Spider(models.Model): ... min_word_count = models.PositiveIntegerField( default=100, null=True, blank=True, ) class SpiderSerializer(serializers.ModelSerializer): min_word_count = serializers.IntegerField(default='', required=False) class Meta: model = Spider exclude = ('category',) def validate_min_word_count(self, value): print('value1111111111111') print(value) if not value: return 0 try: value = int(value) except ValueError: raise serializers.ValidationError('You must supply an integer') return value -
how to execute foreign key model in django
i have user model class User(models.Model): first_name = models.CharField(max_length=30) and order model class Order(models.Model): user = models.ForgienKey(User) product_name = models.CharField(max_length=30) creating user hi = User.objects.create(firs_name = 'hi') hi.save() bye = User.objects.create(firs_name = 'bye') bye.save() i created 3 orders Order.objects.create(product_name='nokia',user=hi).save() Order.objects.create(product_name='samsung',user=hi).save() Order.objects.create(product_name='nokia',user=bye).save() so how to count nokia has 2 users and samsung has 1 user in django using filter or aggregate or annotate? and ouput something like this { "nokia":"2", "samsung":"1" } Django 1.8 -
How to prevent multiple login in Django
I'm writing a User system that cannot login at the same time. If the account in login state in somewhere, and someone login the same account in other position. The latter one will be logged in. And the previous will be logged out. I'm using a model with oneToOneField associated to the User model, And save session ids of this user. The code is like below. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from .myModels import JSONField class Profile(models.Model): user = models.OneToOneField(User, models.CASCADE) sessionids = JSONField(null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) The JSONField is a field that using textField to store JSON string. When a user login, I go to get all session ids of this user and delete all the session ids. Then I add current session id to the Profile. By doing this, I can logout in the previous position. the code is like below. def login(request): if request.method == "POST": if request.user.is_authenticated: return HttpResponse("the user session is authenticated.") username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) #remove cur user all … -
How to add multiple python-path in apache default conf file
I want to add multiple entries for python-path in the 000-default.conf apache configuration file. WSGIDaemonProcess my_project python-path=/home/user/Documents/my_project python-home=/home/user/Documents/my_project/virtualenv In the above line, python-path variable contains the path to my django project root directory, I want to specify some other directory path so that I can import those modules from my django project app files. -
data toggling jquery javascript
Please anyone help to write javascript or jquery for making the data to display as upon clicking the flow row the streams should get displayed and upon clicking the each stream ......It's jobs should be displayed??and again click on particular stream it's job data should be hidden and on clicking flow row streams and jobs should be hidden <table style="width:100%"> <tr> <th>Flow ID</th> <th>Flow name</th> <th>Creation Date</th> </tr> {% for flow in all_flows %} <tr class="flowrow" style="background-color: navajowhite"> <td><a href="{% url 'swp:detail' flow.flow_id %}">{{ flow.flow_id }} </a></td> <td>{{ flow.flow_name }}</td> <td>{{ flow.flow_creation_date }}</td> </tr> <tr class="streamrow" style="background-color: black;color: white"> <td>stream name</td> <td>stream start time</td> <td>stream end time</td> <td>status</td> </tr> {% for stream in flow.dimstream_set.all %} <tr class="streamrow" style="background-color: red"> <td>{{ stream.stream_name }}</td> <td>{{ stream.stream_start_time }}</td> <td>{{ stream.stream_end_time }}</td> <td>{{ stream.stream_status }}</td> <td><a href="#">{{ stream.alias }}</a></td> </tr> <tr class="jobrow" style="background-color: black;color: white"> <td>Job name</td> <td>Job start time</td> <td>job end time</td> <td>status</td> </tr> {% for job in stream.dimjob_set.all %} <tr class="jobrow"> <td>{{ job.job_name }}</td> <td>{{ job.job_start_time }}</td> <td>{{ job.job_end_time }}</td> <td>{{ job.job_status }}</td> </tr> {% endfor %} {% endfor %} {% endfor %} -
django or gunicorn can't read linux environment variable
in an Ubuntu 16.04 server, I run following commands in the python shell: >>> import os >>> os.environ and the output is: environ({'DJANGO_DB_USERNAME': 'siteuser', 'DJANGO_DB_PASSWORD': '123456','DJANGO_SECRET_ KEY': 'xvia%9op!4q$%w@o8t9f%pa%sdfsdfbu+sdfsdf', 'DJANGO_DB_NAME': 'some_name', ..., ..., other keys}) it means environment variables have been set correctly. but when I run the sudo systemctl status gunicorn for checking gunicorn status, the os.environ doesn't work properly. this is the output, when gunicorn runs the django: environ({'LANGUAGE': 'en_US:en', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'DJANGO_SETTINGS_MODULE': 'config.settings.production', 'SERVER_SOFTWARE': 'gunicorn/19.8.1', 'USER': 'mojtaba'}) the following keys DJANGO_DB_NAME, DJANGO_DB_USERNAME, DJANGO_DB_PASSWORD, DJANGO_SECRET_KEY are not found. also other variables are not shown. who knows what's the problem?? -
django crispy forms - add field help text?
Looking through the crispy forms I cannot find if help text is supported. im trying to add some help text to the select multiple field as per the below Field('site_types', Title="Site Types", size="15", help_text="Hold down cmd on MacOS or ctrl on windows to select multiple"), is this supported or would I use some other attribute to achieve this? Thanks -
Can I use JavaScript to pass an email to a python file I have in my website? [duplicate]
This question already has an answer here: Execute a python script on button click 2 answers I am using Django for my website and so am more familiar with Python. Because of this I want to send an email to an email address I receive from my HTML and JS form using Python not JavaScript, as I know little JS. Any ideas/suggestions? What is the JS code to use for sending data from a JS program to a Python script? -
How can I know the length of filepath in FileField in Django?
The website I was working on involves uploading of some files and downloading them. But I have to display the path where an uploaded file is stored. So a model FileField named 'bulk_add' is added in models.py to store filepath like this: bulk_add = models.FileField(upload_to=assignment_bulk_upload_path, null=True) So when user has uploaded a file, I have to display the path where the file is stored in my website like this:Please click on link to view image But as FileField by default will allow max_length = 100, whenever the user uploads a file with very long name, the entire length of filepath crosses the default maxlength(since filepath involves filename) and error page is shown. So I want to write a python function to get the number of characters in filepath when a file is uploaded and display error "File name is long" when the filepath length crossses 100. So how to get no of characters in filepath in the FileFIeld? Is there a function like length() so that I'll get the no. of chars in filepath when I do bulk_add.length()? -
Overriding save method of User model with Abstract user in django
Django project with multiple two user types. I followed this tutorial to give two types of flags to the built in User model. When I try to login to django rest_framework_simple_jwt's login endpoint the response. Is there a problem in overriding save method. { "non_field_errors": [ "No active account found with the given credentials" ] } class User(AbstractUser): email = models.EmailField(unique=False,) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_employee=models.BooleanField(default=False) is_manager=models.BooleanField(default=False) def save(self,*args,**kwargs): if self.is_employee: Employee.objects.create(manager=self) super(User,self).save(*args,**kwargs) -
Django Admin verification
Please, am currently working on a project(a modeling agency) where the admin verifies the details of a new model after completing a registration form using python django framework. This is the breakdown; 1. A new model fills a form. 2. The form is send to the administrator's email for notification and confirmation of the data before being added to the database . 3. The new model is then added to the database . I have little understanding about the above problem, I will be very grateful for any kind of help in this, thanks -
Django block of text does not get translated
Like in the subject, I have two strings to translate: <div class="front-quote"> <p> {% blocktrans %} My, ludzie, mamy skłonność doświadczania samych siebie jako czegoś oddzielnego od otaczającego nas Wszechświata. Jest to łudzenie naszej świadomości, jak zamykanie sie w więzieniu. Nasze zadanie to wyzwolić sie z tego więzienia poprzez rozszerzenie naszego współczucia na wszystkie żyjące istoty i Naturę w całym jej pięknie. Staranie się aby to osiągnąć to nasza jedyna ścieżka do wyzwolenia i jedyna podstawa prawdziwego}wewnętrznego spokoju i poczucia bezpieczeństwa {% endblocktrans %}</p> <p class="signature">Albert Einstein</p> </div> <div class="front-1"> {% blocktrans %} Jeśli jesteś <span class="front-emphasis">idealistą</span>{% endblocktrans%} </div> And for some reason the second one gets translated but first not... I tried everything I could think of: changed the template tags from {% trans %} to {% blocktrans %}, put all text as one string in one line... It just does not work... The only unusual thing I noticed is in the .po file, there is repeated and commented out block of code which does not get translated, it looks like that: #: biostrefa/templates/pages/home.html:8 #, fuzzy #| msgid "" #| " My, ludzie, mamy skłonność doświadczania samych siebie jako czegoś " #| "oddzielnego od otaczającego nas Wszechświata. Jest to … -
Datetime not going inside loop
I'm using Celery to do a periodic task for a recurring transaction. I am trying to update a value on my DB each time a certain time has passed. I am using a datetime.now() variable to check if a certain time has reached, say, for example 1 hour, and the code must execute and update the value on the db by 1. My store file correctly updates the value in the DB (but when put in a loop, it doesn't enter the loop). Considerations: Values of times field are stored as strings but I typecast them as int While loop continues to run as long as times_ran is less than times times_ran field defaults to 0 upon creation. ending variable must increment extra time as long as list #2 above is True. (eg. if my repeat_type=hourly, times=2, starting=04:13:25, time_left should be at 05:13:25 (times_ran=1), then 06:13:25 (times_ran=2) and must stop the loop. Here's my code so far: service.py times_ran = self.data['times_ran'] # datetime.timedelta(x, y) format hourly = timedelta(seconds=15) daily = timedelta(days=1) weekly = timedelta(days=7) monthly = timedelta(days=30) quarterly = monthly * 3 semiannually = monthly * 6 annually = monthly * 12 now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Initially add duration …