Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csv File in Django Server
The following line gets saved in the CSV file alongwith form data onn every submission. csrfmiddlewaretoken,p3amPwSQ2WGU5KfxMWlc9vzumfBqoc9xmnBT6VrK3dNoo00mZRIlq9OnwbFt04qu How to correct this ? -
FOREIGN KEY constraint failed with Custome Model in Django
I customed the User in Django following the code providing by the Documentation (for the models.py and the admin.py) I have a custom User using his email to auth (and not the username) I can create new user but I cannot delete them in the django admin panel. When I try i go this error message: FOREIGN KEY constraint failed models.py from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class MyUserManager(BaseUserManager): def create_user(self, email, date_of_birth, password=None): """ Creates and saves a User with the given email, date of birth and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), date_of_birth=date_of_birth, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( email, password=password, date_of_birth=date_of_birth, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return self.email def has_perm(self, perm, obj=None): "Does the user have a specific permission?" # Simplest possible answer: Yes, always return True … -
Retrieving user details using username from extended User Model in Django
I'm trying to retrieve the details of a user using the username test from an extended User model in Django. But I am unable to do it. It's giving me the error: ValueError at / invalid literal for int() with base 10: 'test' Following is my code: models.py class DocchainUser(models.Model): docchainuser_name = models.OneToOneField(User, on_delete = models.CASCADE, default='x') address = models.CharField(max_length=64,unique=True) def __str__(self): return self.address views.py def my_users(request): if request.method == 'POST': username = request.POST.get('username') user = authenticate(username=username) if user: if user.is_authenticated: signBool = signatureAuth(username) if signBool == 'AUTHENTICATED': login(request, user, backend=settings.AUTHENTICATION_BACKENDS[0]) return HttpResponseRedirect('/dashboard') .... And the signatureAuth() now: def signatureAuth(username): userModel = DocchainUser.objects.filter(docchainuser_name=username) address = userModel.address print(address) ... I'm retrieving the user details using username: test in signatureAuth() method. test is already present in my User as well as DocchainUser model. -
django tutorial: testcase failed to create testuser on oracle express database
I am following the tutorial from django a link. When i trying to test the testcase using "py manage.py test polls" i get this: C:\Users\user\Documents\user_django_projects\mysite>py manage.py test polls Creating test database for alias 'default'... Failed (ORA-01543: tablespace 'TEST_SYSTEM' already exists) It appears the test database, test_system, already exists. Type 'yes' to delete it, or 'no' to cancel: yes Destroying old test database for alias 'default'... Creating test user... Failed (ORA-65096: invalid common user or role name) Got an error creating the test user: ORA-65096: invalid common user or role name django can't seem to create a temp user on my local oracle express database. Can someone help me sort it out? -
Settting up logger to send emails to address different than admins
In the settings file I have a logger set up to send any errors to ADMINS which is the default behavior. Here: LOGGING = { 'handlers': {'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler'} 'loggers': {'django.request': {'handlers': ['mail_admins'], 'propagate': True}} } But I would like to set up a second logger to log a different type of errors and email should be sent to a different address. I have my own logging function which writes to a file. Basically I want to send an email to that other address instead. How can I do this? -
How to override the db_table in model for a 3rd-party packages?
I want to override the "db_table" in models.py for 3rd-party packages. Therefore, the database table name could display what I need. models.py from admin_honeypot.models import LoginAttempt as oldLoginAttempt_Model class LoginAttempt_Model(oldLoginAttempt_Model): oldLoginAttempt_Model._meta.db_table = 'NEW-TABLE-NAME' class Meta: proxy = False app_label = 'admin_honeypot' db_table = 'NEW-TABLE-NAME' admin.py from admin_honeypot.admin import LoginAttemptAdmin as oldLoginAttempt_Admin from admin_honeypot.models import LoginAttempt as oldLoginAttempt_model from .models import LoginAttempt_Model admin.site.unregister(oldLoginAttempt_model) @admin.register(LoginAttempt_Model) class LoginAttempt_Admin(oldLoginAttempt_Admin): pass then, I do python manage.py makemigrations database table name still on the old version. -
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 )