Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Please help me with my skill recommendation system by machine learning code?
https://github.com/rishabhrana54/skillrecommendation hey!! i have a some issue with this skill recommendation in Views.py. you can check in by running this project In 'submitPofile(Req)' of views.py its not able to recommend me right language. please help me if anyone can -
Data not saving in models sequentally
Want to save data in sequence I am using react as front and I am trying to save data from an array to django backend model.Suppose I have array of length 5, I am saving 5 indexes separately in django model, but the problem is data is not saving in model in sequence, e.g: arr[0]=data1 arr[2]=data2 arr[3]=data3 but in model, It displays : id=1 data=2, id2=2 data=3, id3=3 data=1, I want to save in sequence,like data1,data2,data3 or data3,data2,data1 can also work,below is my code: for (let i=0;i<rowdata.length;i++){ console.log("rows",rowdata[i]); //1,2,3,4,5,6 payload={ product:this.state.productid, row_name:rowdata[i] // indexes data is 1,2,3,4,5,6 }; axios.post('http://127.0.0.1:8000/pharmacy/create_row/',payload) .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) } django rest Response: { "id": 43, "row_name": "4", "product": 17 }, { "id": 44, "row_name": "1", "product": 17 }, { "id": 45, "row_name": "5", "product": 17 }, { "id": 46, "row_name": "2", "product": 17 }, { "id": 47, "row_name": "3", "product": 17 }, { "id": 48, "row_name": "6", "product": 17 } whereas it should be 1,2,3,4,5,6 (row_name) from top to bottom,but they are not in sequence How can I resolve it should save in like 1,2,3,4,5,6 or 6,5,4,3,2,1 both will work. -
Can anyone explain or suggest a tutorial to create a listView in android?
Can anyone explain or suggest a tutorial to create a listView in android? Here are my requirements: I should be able to dynamically add new elements by pressing a button. Should be simple enough to understand (possibly without any performance improvements or convertview, for instance) -
How to display field text instead of the ID for a model connected by a foreign key in Django?
I have a simple model (kit) connected by another model(client_id) with a foreign key, and also by a ManyToMany field. I have a form view for the kit model, in which user can create new kits, by selecting a few products, and then choosing which client it is made for. Problem is, the fields are being displayed correctly, but with only ID displayed, instead of their names. User does not know what is he selecting as he does not know the ID of all products or clients. How should I approach this ? I searched on SO but found nothing useful. Code models.py # Parent model connected with both models class Kit(models.Model): kit_name = models.CharField(max_length=255, default=0) kit_info = models.CharField(max_length=255, default=0) components_per_kit = models.IntegerField(default=0) product_id = models.ManyToManyField(Product, related_name='kit_product') quantity_per_kit = models.IntegerField(default=0) kit_client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='kit_owner') # connected by foreign key class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_company = models.CharField(max_length=255, default=0) client_name = models.CharField(max_length=255, default=0) # connected by many to many field class Product(models.Model): product_id = models.IntegerField(default=0) product_name = models.CharField(max_length=255, default=0) product_short_code = models.CharField(max_length=255, default=0) product_description = models.CharField(max_length=255, default=0) Current output -
Data Table functionalities are not working
I have tried all the orders of my css and js cdn files but still my data tables search option,entries and pagination functions are not working and this project is in django for dynamic data Base.html file <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Makerobos json data</title> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css"> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css"> <script> $(document).ready( function () { $('#Robos').DataTable(); } ); </script> </body> </html> my another table file where i have created table according to the datatable using thead and tbody {% extends 'robosapiapp/base.html' %} {% load dateformat %} {% block content %} <div class="container"> <table id="Robos" class="display"> <thead> <tr> <th>Username</th> <th>Email</th> <th>First Name</th> <th>Last Name</th> <th>Plan</th> <th>Date Joined</th> <th>Contact</th> </tr> </thead> <tbody> <tr> {% for x in data %} <td>{{x.username}}</td> <td>{{x.email}}</td> <td>{{x.first_name}}</td> <td>{{x.last_name}}</td> <td>{{x.plan}}</td> <td>{{x.date_joined|dateformat|date:"d/m/Y"}}</td> <td>{{x.profile.contact}}</td> </tr> </tbody> {% endfor %} </table> </div> {% endblock %} -
Static files not loading while using python3 manage.py runserver 0.0.0.0:8000 in my server
ive added the static root file in my setting.py and also done collectstatic but while loading using bind in my virtualenv and if try to access my page using ipaddress:8000 the static files is not loading it is showing "GET /static/images/image1.jpg HTTP/1.1" 404 77" error for all static files im attaching my settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static") before i was able load all static file without using any port by directly accesing ip address coz i have given the static directrey enter code herein my nginx conf file but now im not able to acces to that also please comment if any clarification -
I want to publish post in django interactive console
Hi I was using django interactive shell and I wanted to create new post as this code. post = Post.objects.get(title="Sample title") post.publish() but It doesn't work. actually, I was following tutorial I have already check code. It's definitely same and I've already imported timezone module. I can check whatever work or not as this code. Post.objects.filter(published_date__lte=timezone.now()) and this is my error message post.publish() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/cosmian/myvenv/my_site/blog/models.py", line 13, in publish self.published_date = timezone.now() TypeError: 'NoneType' object is not callable this is my manage.py file from django.db import models from django.conf import settings from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title -
Detecting line breaks within Python/Django textarea fields
I have a textarea field in Django from which I want to detect line breaks. I can see that the line breaks are stored as reloading the page with the user input shows the breaks that the user inputted, but I can't detect them in Django/Python. When I look at the output from PostgreSQL I can see \r characters, but these don't seem to show up within the Python environment. I'd like to do something like this: text_blocks = text_area.split("\r") But this doesn't work and I suspect is naive. How can I detect these seemingly invisible line breaks within Python/Django? -
How to override the renderer_classes to send extra information in REST API
I have created the rest api for authentication of user, and in the response I am getting the token. I also want to add whether the user has staff permission or not, I have already got the information is serializers but I am not able to pass to the view. And I need to authentication whether user is active or not This part is not working at all. My serializer code : class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): """Validate and authenticate the user""" email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) #This part I am trying to authenticate whether the account is active or not if user is not None: if not user.is_active: msg = _('The password is valid, but the account has been disabled! ') raise serializers.ValidationError(msg, code='not_active') if not user: msg = _('Unable to authenticate with provided credentials') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user attrs['is_staff'] = user.is_staff #Here I am getting the user has permission of staff or not. return attrs And the views.py is : class CreateTokenView(ObtainAuthToken): """Create a new auth token for the user""" serializer_class = … -
remove default order by?
str(CertificationWorkItem.objects.values ('certification_id','identity_id').annotate(c=Count('identity_id',distinct=True)).query) 'SELECT "CERTIFICATION_WORK_ITEM"."certification_id", "CERTIFICATION_WORK_ITEM"."identity_id", COUNT(DISTINCT "CERTIFICATION_WORK_ITEM"."identity_id") AS "c" FROM "CERTIFICATION_WORK_ITEM" GROUP BY "CERTIFICATION_WORK_ITEM"."certification_id", "CERTIFICATION_WORK_ITEM"."identity_id" ORDER BY "CERTIFICATION_WORK_ITEM"."identity_id" ASC' this code is showing order by but idon't want it remove order by how can i do it str(IdentityAccountRelation.objects.values('account_id__application_id').annotate(ck=Count('identity_id')).query) 'SELECT "ACCOUNT"."application_id", COUNT("IDENTITY_ACCOUNT_RELATION"."identity_id") AS "ck" FROM "IDENTITY_ACCOUNT_RELATION" INNER JOIN "ACCOUNT" ON ("IDENTITY_ACCOUNT_RELATION"."account_id" = "ACCOUNT"."uuid") GROUP BY "ACCOUNT"."application_id"' like this code -
Django's AppConfig.ready() seems to be called once per thread in Apache wsgi
I have the following code in apps.py: class Pqawv1Config(AppConfig): # ... def ready(self): env_run_main=os.environ.get('RUN_MAIN') print('IS_PRODUCTION=%s, RUN_MAIN=%s' % (settings.IS_PRODUCTION, env_run_main)) if (not settings.IS_PRODUCTION) and (env_run_main != 'true'): print('Exiting because detected running in reloader.') return print('Starting up for PID=%s, argv=%s...' % (os.getpid(), sys.argv)) # Initialization of a singleton object from a C++ DLL # Raise an exception if this library was already initialized in this process In the evening I restarted the server and it printed the following in the log as expected: [Sun Sep 15 22:50:34.928549 2019] [wsgi:error] [pid 11792:tid 1176] Starting up for PID=11792, argv=['mod_wsgi']...\r However, in the morning I noticed that something strange has happened. It looks like Apache started a new thread for the web application: [Mon Sep 16 04:10:41.224464 2019] [wsgi:error] [pid 11792:tid 1160] Starting up for PID=11792, argv=['mod_wsgi']...\r And later: [Mon Sep 16 07:16:21.028429 2019] [mpm_winnt:error] [pid 11792:tid 2272] AH00326: Server ran out of threads to serve requests. Consider raising the ThreadsPerChild setting I think it's not the issue of calling AppConfig.ready() method twice because there were requests to the website in between and they were handled well. It rather looks like Django's AppConfig.ready() method is called once per worker thread of Apache process. Is this … -
How to display foreign key value instead of pk in django?
Here I am filtering staffs which has OnetoOne relation with the django User model.And the below code of function def filter_staff_users(request): also works fine as I wanted but the problem what I get is while displaying the organization name in message.I tried doing organization.name but it didn't worked. I got 'str' object has no attribute 'name' and when I tried converting int organization = int(request.GET.get('organization')) then it again throws 'int' object has no attribute 'name'. How can I display the organization name here ? models.py class Organization(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Staff(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='staff') While adding the staff_user i added the organization as below <select name="organization"> {% for organization in organizations %} <option value="{{organization.pk}}" >{{organization.name}}</option> {% endfor %} </select> views.py def filter_staff_users(request): year = request.GET.get('year') month = request.GET.get('month') # month_name = calendar.month_name[int(month)] organization = request.GET.get('organization') print('org', type(organization)) if year and month and organization: staffs = get_user_model().objects.filter(Q(staff__joined_date__year=year) & Q(staff__joined_date__month=month) & Q(staff__organization=organization)) messages.success(request, '{} staffs found for {} {} and {}'.format(staffs.count(), year, calendar.month_name[int(month)], organization)) -
API in django with response as data stream
I need to write an API in Django 2.2. It will be consumed by a google data studio connector. As a response I am fetching records from MariaDB. The size of the response causes the memory error on my production machine. So I am trying to stream it and this is what I did. Here is the code for iterator object. (Generation is model class) class Data(object): def __init__(self): self.paginator = Paginator(Generation.objects.get_queryset().order_by('id'), 100000) self.pagenum=1 def __next__(self): data="" if self.pagenum > self.paginator.num_pages: raise StopIteration if self.pagenum==1: data="[" data += serializers.serialize('json', self.paginator.get_page(self.pagenum))[1:-1] if self.paginator.num_pages == self.pagenum: data+="]" self.pagenum+=1 return data def __iter__(self): return self and here is the code for API response data = Data() response = StreamingHttpResponse(data,content_type="application/json") return response Problem: It seems connector does not wait for the entire stream to end and returns an invalid json error. -
How to send text client to server django channel
Hi all I'm trying send data js to django with websocket but not working Could you help me where am I doing wrong? ps: I was able to send data from the server to the client error: raise ValueError("No text section for incoming WebSocket frame!") No text section for incoming WebSocket frame! WebSocket DISCONNECT /ws/ [127.0.0.1:64282] js document.addEventListener('DOMContentLoaded', function () { let webSocketBridge = new WebSocket("ws://127.0.0.1:8000/ws/"); webSocketBridge.onopen = function(action) { console.log(action); webSocketBridge.send(JSON.stringify({ "id": "client1" })); }; webSocketBridge.onmessage = function(event) { let message = event.data; as += message + "\r\n"; $('#messages').html(as); }; consumer.py import asyncio from channels.generic.websocket import AsyncJsonWebsocketConsumer class TickTockConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() while 1: await asyncio.sleep(0.1) await self.send_json("tick") await asyncio.sleep(0.1) await self.send_json(".......tock") await self.receive() -
Backup/restore of auth.permission table
I have a Django model schema that contains an external model pointing to the auth.group_permissions (and therefore auth.permission) table. As part of my system I run backups using ./manage.py dumpdata to dump to a JSON file - and restore using the corresponding ./manage.py loaddata. I've seen advice in the Django docs and the community (see this warning) suggests that backing up the auth.permission table is not advised - and so this table is not backed up (along with contenttypes and session). Of late I have been running into some issues - if I add a new table to the database then migrate, then new rows are added to the end of the auth_permission tables. However if I rebuild the database and run a migration from scratch, then the new rows are not always placed at the end of the table - they are sometimes getting added in a different order. This means that my backups - which do not include auth.permission - can sometimes point to incorrect row IDs, as the IDs will now be in a different order. This is obviously not ideal as it means my database can potentially not be correctly restored in case of catastrophic failure. … -
How combine the temporary link with the real link on Django 2.2
I ran into such a problem. I created temporary links on the site. I can’t combine the temporary link with the real link (video link). How is this possible? So that a person can access the video only through a temporary link. -
Django AJAX form error message to be displayed on the same page index.html
In urls.py urlpatterns = [ path("contact-form/", contact_form, name="contact-form"), ] In views.py def contact_form(request): form = ContactForm(request.POST or request.GET) if form.is_valid(): data = { 'success': True, } status = 200 else: data = { 'success': False, 'errors': form.errors.get_json_data(), } status = 400 return JsonResponse(data, status=status) In index.html {% block js %} {{ block.super }} <script src="{% static 'app/js/contact-form-script.js' %}"></script> {% endblock %} In template index.html, there is a form: <form id="contactForm" method="get" action="{% url 'contact-form' %}"> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" id="name" name="name" placeholder="Name"> <div class="help-block with-errors"></div> </div> </div> <div class="col-md-6"> <div class="form-group"> <input type="text" placeholder="Subject" id="msg_subject" class="form-control" name="subject"> <div class="help-block with-errors"></div> </div> </div> ... <div class="submit-button"> <button class="btn btn-common" id="submit" type="submit">Submit</button> <div id="msgSubmit" class="h3"></div> </div> </div> </div> </form> When the form is submitted I want to display error messages to #msgSubmit. Right now when the form is submitted it gets redirected to http://localhost:8000/contact-form/?name=&subject=&email=&budget=&message= and this is dumped to the page {"success": false, "errors": {"name": [{"message": "Please enter your name", "code": "required"}], "subject": [{"message": "Please enter your subject", "code": "required"}], ...}} provided for example, if Name and Subject in the form are not filled in. The requirement says, form needs to be converted to AJAX and server … -
Django Model preventing create if any of Enum item already exist
I am writing a cinema ticket booking apps. I am going through the trouble to design my models! What I want: A person can buy/book one or more than one seats in one ticket If any seats already booked in a show, those seats can't be booked again later in the same show and show an error (But in a different show, it can be booked if available) I have only issue with Seats, I am not getting how to achieve this Can anyone please help me to make this model perfect? The models is given below from django.db import models from enum import Enum class ShowType(Enum): MORNING_SHOW = 1 NIGHT_SHOW = 2 class Person(models.Mode): name = models.CharField(max_length=20) class Seats(models.Model): seat_id = models.IntegerField(primary_key=True, editable=True) name = models.CharField(max_length=2) is_available = models.BooleanField(default=True) class Show(models.Model): show_name = models.CharField(choices=ShowType, default=ShowType.MORNING_SHOW) movie = models.CharField(max_lenght=50) date = models.DateField() seats = models.OneToManyField(Seats) class Ticket(models.Model): buyers = models.ForeginKey(Person, on_delete=models.CASCADE) show = models.ForeignKey(Show,on_delete=models.CASECADE) I want a any number of seats can be booked in a ticket of a show and later those seats can't be booked again for the same show and show an error. Can anyone please help me to achieve this? -
Django MSSQL Database Query to Django ORM
I need help translating this query into Django ORM: Select * from LabelFormat A where A.LabelFormatKey in (select B.LabelFormatKey from SyncTable B where B.LastModified < A.LastModified and B.LabelFormatKey = A.LabelFormatKey and B.Site = a.Site ) -
Filter annotate When Case with foregin key
i have 2 models: class ServiceRequest(models.Model): post_time = models.DateTimeField(default=timezone.now) service = models.IntegerField(default=102) class RequestSession(models.Model): request = models.ForeignKey(ServiceRequest) post_time = models.DateTimeField(default=timezone.now) If service have value 102, it will have one or more RequestSession. I have queryset get all ServiceRequest : ServiceRequest.objects.all() My question is : How to order_by post_time if service!=102, if service=102 i want order by greatest post_time of requestsession_set? i tried annotate but i dont know how to get greatest post_time in requestsession inside When then My query: queryset.annotate(time_filter=Case( When(service_id=102, then=('requestsession_set__post_time')), default=Value('post_time'), output_field=DateTimeField(), ), ).order_by("-time_filter") -
How do i host django website through webmin/virtualmin in hostinger?
I am trying to host a django website using webmin/virtualmin.I uploaded django file, but can't access the website using domain?How can i do this? -
docker does not installs the updated pipfile
I am using docker in my project. Initially there was following packages in Pipfile [packages] django = "*" djangorestframework = "*" celery = "*" whitenoise = "*" redis = "*" django-celery-beat = "*" flower = "*" django-environ = "*" django-redis = "*" "flake8" = "*" coverage = "*" gunicorn = "*" sentry-sdk = "*" django-storages = {extras = ["boto3"], version = "*"} django-anymail = {extras = ["mailgun"], version = "*"} pillow = "*" "psycopg2-binary" = "*" django-money = "*" django-phonenumber-field = "*" phonenumbers = "*" "argon2-cffi" = "*" jsonfield = "*" future = "*" django-contrib-comments = "*" tzlocal = "*" [dev-packages] werkzeug = "*" "autopep8" = "*" "flake8" = "*" I then build my project and it worked fine. But soon after building an image, i installed following packages in my local environment using pipenv install pylint-django pylint-celery django-debug-toolbar django-extensions --dev Now that i have updated my packages list, I tried to rebuild the image using docker-compose -f local.yml build which i guess did not installed those packages so I am getting issue `ModuleNotFoundError: No module named 'debug_toolbar'. Here is my docker configuration FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps … -
Unresolved import models Django + Docker
I have a few simple classes in my Django app that are not loading/importing properly. I know that the code works as I am Dockerizing over an existing app. I am fairly sure this is a similar issue to this but I do not know how to update this to use the Python inside my Docker container. I am following this guide (so all settings/configuration is the same). I have 2 classes: a custom user class and a Company model, and I am trying to add a foreign key on the user that links it to a particular Company. On the other side, I will have a many to many relationships (a company can have multiple users). from core.models import Company VS Code says "unresolved import" when I hover on core.models -
Forbidden (CSRF cookie not set.): /paypal/ | Django
I am having problems with django-paypal, the problem occurs at the moment of receiving the paypal IPN when the payment is successfully completed. Error: Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:04] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:19] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:42] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:54:24] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:55:45] "POST /paypal/ HTTP/1.1" 403 2896 I don't know what is happening, I started to investigate the error but I did not achieve much, investigating I put in the file settings.py CSRF_COOKIE_SECURE as True, and even then it did not work, any solution ?. -
Create postgresql command based on DELETE REST call within Django
So I have roughly the following: class exampleSerializer(serializers.ModelSerializer): def delete(self, request, *args, **kwargs): //Custom code The goal is to access the data of the row that the delete function is gonna delete. Based on this information I need to make some extra PostgreSQL commands before the functions finishes. How can I access this data?