Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the most effective and fastest way to build a one on one messaging system with django channels or any other package
I am trying to implement a chat system where users can send messages to other user who is his/her friend. And can send Messages to other people but they will not in their requests page and user can add his friends to create a group and they can chat there. How to build a real time app like this functionality with real time notifications in it. I know django channels a little bit but I am not really sure how would I go about doing these things as I have never worked with websockets or django channels in real project before.what's the most fastest way to build. Anybody has a step by step clear implementation that can help. -
Emperor: ModuleNotFoundError: No module named 'django'
I am trying to use emperor so I can daemonize my uWSGI as written here. However I am getting a no module error. Below is my log *** Operational MODE: preforking *** Traceback (most recent call last): File "./myapp/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 2905) spawned uWSGI worker 1 (pid: 2906, cores: 1) Tue Jan 7 21:46:41 2020 - [emperor] vassal myapp.ini has been spawned spawned uWSGI worker 2 (pid: 2907, cores: 1) spawned uWSGI worker 3 (pid: 2908, cores: 1) Tue Jan 7 21:46:41 2020 - [emperor] vassal myapp.ini is ready to accept requests spawned uWSGI worker 4 (pid: 2909, cores: 1) spawned uWSGI worker 5 (pid: 2910, cores: 1) spawned uWSGI worker 6 (pid: 2911, cores: 1) spawned uWSGI worker 7 (pid: 2912, cores: 1) spawned uWSGI worker 8 (pid: 2913, cores: 1) spawned uWSGI worker 9 (pid: 2914, cores: 1) spawned uWSGI worker 10 (pid: 2915, cores: 1) Any help is appreciated. -
Django how to configure CDN over azure blob storage
I'm Using with Django for web application and Azure blob storage for asset storage, due to some performance issues of image rendering we added CDN. But i don't know how to configure to django. All other CDN to blob configuration are done and it's working properly. Can someone guide me how to solve this and before that whatever i'm doing is right or wrong. If it's wrong can you guide me. Note: In the existing, it's working properly with Azure blob url and i want to change it to CDN url. -
get csrf token in react native
I have built django server to manage my data, then I have desktop react app where I can create new users/login/post data, it works flawless, It is based on csrf token verification and there is no problem with that. However I have also react-native app which is supposed to let user log in, and GET data which belongs to him. And here is question, how to get CSRF token in react native? In desktop app it looks more or less like this but I have no idea how to login in react native as I can't simply get Cookie with csrf token. componentDidMount() { const csrfToken = Cookies.get('csrftoken') this.setState({csrfToken}) } loginHandler = login_data => { this.setState({ user: login_data.user, password: login_data.password }, () => { const auth = { "username": this.state.user, "password": this.state.password } fetch("http://localhost:8000/data/", { method: 'POST', credentials: 'include', headers: { "X-CSRFToken": this.state.csrfToken, }, body: JSON.stringify(auth) }) .then((res) => res.json()) .then(resp => console.log(resp)) .then(() => this.getData()) .catch(() => this.setState({ user: "", passowrd: "" })) }) }; -
Django Rest Framework - Buyers and seller interface
i'm trying to make a multivendor marketplace where buyers and seller can negociate the price of the service and make a deal, i have no idea how to make this negociation layout in django rest framework, here's what i'm trying to do There's a layout of my idead Could anyone give me some guidance? Thanks in advance -
Django: ask for ideas about realising rotation of timetables
I am trying to use Django to create a rotated timetable: 1) there are lessons with various durations (30 mins, 45 mins, 60 mins etc); 2) there several tutors; 3) the tutor login their account, they will see a timetable; 4) the students should be rotated, for example: Week 1: Student A: 09:00 - 09:30 (a 30 min lesson) Student B: 09:30 - 10:15 (a 45 min lesson) Student C: 10:15 - 10:45 (a 30 min lesson) and so on ... ... Week 2: Student B: 09:00 - 09:45 (a 45 min lesson) Student C: 09:45 - 10:15 (a 30 min lesson) Student D: 10:15 - 10:45 (a 30 min lesson) and so on ... ... Week 3: ... Week 4: ... and so on ... I have created a class in models.py: class Student(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) tutor = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) def __str__(self): return self.first_name + " " + self.last_name The views.py looks like: def index(request): if request.user.is_authenticated: students = Student.objects.filter(tutor=request.user) context = {'students':students} else: context = {} return render(request, 'notes/index.html', context) In the template html, it looks like: {% if request.user.is_authenticated %} <table class="table table-striped"> {% for student in students %} <tr> <td>{{ student.first_name … -
how to post data into database using views in django without template
I want to post data into database using views in django without using templates. Is this possible in Django? here is my code snippet of models.py : class Employee(models.Model): eno = models.IntegerField() ename = models.CharField(max_length=20) esal = models.FloatField() eadd = models.TextField(max_length=40) code snippet of views.py: def emp(request): eno = request.POST[1289], ename = request.POST['siddarth'], esal = request.POST[20190.24], eadd = request.POST['india'], save_data = Employee(eno=eno,ename=ename,esal=esal,eadd=eadd) save_data.save() return JsonResponse Above code snippet of views.py is not working. can anyone help for that. -
Django: how to synchronize 2 db?
I have a Django project which is connected to 2 db. models.py class ModelOne(models.Model): db = "firstDB" attr = someValue class ModelTwo(models.Model): db = "secondDB" attr = {cannot do ForeignKey(ModelOne)} I would like to make them synchronous, such that table/data changed in 1st db, it should also change it in 2nd. As far as I know, Django does not allow to create a model that has an attribute that references another db. I have written the script that goes through 1st db and creates model instances in 2nd db: import os, django, requests os.environ.setdefault("DJANGO_SETTINGS_MODULE", "diary.settings") django.setup() URL = "APIendpointToCreateModelTwo" data = models.ModelOne.objects.all() for school in schools: data = {...} requests.post(url = URL, data = data) It works well, however, I need it to be done periodically (e.g. once in a day) or directly make changes into the 2nd db, when 1st is varied. I was wondering, if I apply the same script logic to other actions, will it be time consuming task? Maybe there are other techniques that allows to implement that, like adding a function that listens for the changes in the 1st db, and implements them directly. I have found technologies such as celery, redis, cron, however I'm … -
How to validate mp4 file or audio files in general with python?
I have a rest API built with Django rest framework, one of its serializers is to accept Base64file which is our audio file, now what I want is simply check and validate the decoded file so I can know if this a valid mp4 or any audio type in general or not. the problem is, sometimes the audio file after upload and save is corrupted and can't be played, so doing this validation is essential to make sure that the file is sent correctly or it was sent corrupted at first place. I have been digging on google and the Internet searching for anything can do this simple task but all I found was how to play audio or manipulate it, I didn't even find something that may raise an exception if the file is not valid when trying to open it. for more info. I'm using django-extra-fields, I use Base64FileField to implement my Audio file field, they provided an example to do so for like PDF's, I'm trying to do this similar way for audio but what is holding me is doing the check for audio. The example of PDF: class PDFBase64File(Base64FileField): ALLOWED_TYPES = ['pdf'] def get_file_extension(self, filename, decoded_file): … -
Is it possible to use a django viewset with two serializers?
I have a model for Articles which has a lot of fields. When someone fetches a specific article by id I want to send almost all of the fields back to the client. However, when the articles list is generated I don't want to send all of the articles with all of that data, but rather limit each article to a few important listing fields, and forgo long fields like content etc.. Can I achieve these with an elegant tweak to the the django_restframework.viewsets module, or should I just build the api methods myself using django_restframwork.generics instead? example: # articles/api/urls.py # # -------------------- # from articles.api.views import ArticlesViewSet from django.urls import path from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ArticlesViewSet, basename='articles') urlpatterns = router.urls # articles/api/views.py # # --------------------- # from rest_framework.viewsets import ModelViewSet from ..models import Article from .serializers import ArticleSerializerFull, ArticleSerializerShort class ArticlesViewSet(ModelViewSet): # Perhaps some conditional code here? serializer_class = ArticleSerializerFull queryset = Article.objects.all() -
Does editable=false apply at the database level?
When fields are set to editable=False, the docs say: If False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. Are any restrictions placed on the database itself, or is this simply restrictions on the client side? If not, is there a way to enforce this integrity of non-editable fields at the database level? -
How to parse request JSON data for DRF Serializer in custom format?
I have DRF serializer that looks like this: class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, attrs): user = authenticate(username=attrs['email'], password=attrs['password']) if not user: raise serializers.ValidationError('Incorrect email or password.') if not user.is_active: raise serializers.ValidationError('User is disabled.') return user When POST request is made to API it sends following JSON: { "email": "user@example.com", "password": "somepassword" } Due to certain project conventions I want that data for deserialization to be included inside request object and sent to API in following format: { "request": { "email": "user@example.com", "password": "somepassword" } } How I can make DRF's serializers (both Serializer and ModelSerializer) automatically fetch data from request block without writing additional serializer with nested LoginSerializer?: class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, attrs): user = authenticate(username=attrs['email'], password=attrs['password']) if not user: raise serializers.ValidationError('Incorrect email or password.') if not user.is_active: raise serializers.ValidationError('User is disabled.') return user class LoginRequestSerializer(serializers.Serializer): request = LoginSerializer() Is there some type of RequestRenderer that I need to implement in my APIView? -
Select Column from Table in Django Not Working
I am trying to access the two specific column from the table in Django it is not Working but When I am trying to access select * it is working I am using postgresql When I am trying to access select all its working this is I am trying to access for particular column def bigdataDatabase(X): engine = sqlalchemy.create_engine('postgresql+psycopg2://postgres:password@localhost/db_name') con = engine.connect() result = con.execute( "Select Orign,Departure From 'table_name' WHERE index = '" + str(X) + "'") This is not working I have also tried with this result = con.execute("Select tablename.Orign,tablename.Departure From 'table_name' WHERE index = '" + str(X) + "'") both the above code is not working But When I am executing all this it is working result = con.execute("Select * From 'table_name' WHERE index = '" + str(X) + "'") -
Are you sure webpack has generated the file and the path is correct
I installed openEDX by documentation official: https://www.google.com/search?q=install+open+edx+devstack&oq=in&aqs=chrome.2.69i59l3j69i61j69i60l2.5255j0j4&sourceid=chrome&ie=UTF-8 I do all steps but he gives me this error : OSError at / Error reading /edx/var/edxapp/staticfiles/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Request Method: GET Request URL: http://localhost:18000/ Django Version: 1.11.27 Exception Type: OSError Exception Value: Error reading /edx/var/edxapp/staticfiles/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? Exception Location: /edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages/webpack_loader/loader.py in _load_assets, line 32 Python Executable: /edx/app/edxapp/venvs/edxapp/bin/python Python Version: 3.5.2 Python Path: ['/edx/app/edxapp/edx-platform', '/edx/app/edxapp/venvs/edxapp/lib/python35.zip', '/edx/app/edxapp/venvs/edxapp/lib/python3.5', '/edx/app/edxapp/venvs/edxapp/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/edxapp/venvs/edxapp/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/edx/app/edxapp/venvs/edxapp/lib/python3.5/site-packages', '/edx/app/edxapp/venvs/edxapp/src/oppia-xblock', '/edx/app/edxapp/venvs/edxapp/src/schoolyourself-xblock', '/edx/app/edxapp/venvs/edxapp/src/concept-xblock', '/edx/app/edxapp/venvs/edxapp/src/audio-xblock', '/edx/app/edxapp/venvs/edxapp/src/animation-xblock', '/edx/app/edxapp/venvs/edxapp/src/ubcpi-xblock', '/edx/app/edxapp/venvs/edxapp/src/xblock-vectordraw', '/edx/app/edxapp/venvs/edxapp/src/xblock-activetable', '/edx/app/edxapp/venvs/edxapp/src/edx-zoom', '/edx/app/edxapp/venvs/edxapp/src/labxchange-xblocks', '/edx/app/edxapp/venvs/edxapp/src/acid-xblock', '/edx/app/edxapp/venvs/edxapp/src/codejail', '/edx/app/edxapp/venvs/edxapp/src/django-wiki', '/edx/app/edxapp/venvs/edxapp/src/done-xblock', '/edx/app/edxapp/venvs/edxapp/src/edx-jsme', '/edx/app/edxapp/venvs/edxapp/src/pystache-custom-dev/build/lib', '/edx/app/edxapp/venvs/edxapp/src/rate-xblock', '/edx/app/edxapp/venvs/edxapp/src/xblock-google-drive', '/edx/app/edxapp/edx-platform/common/lib/capa', '/edx/app/edxapp/edx-platform', '/edx/app/edxapp/edx-platform/common/lib/safe_lxml', '/edx/app/edxapp/edx-platform/common/lib/sandbox-packages', '/edx/app/edxapp/edx-platform/common/lib/symmath', '/edx/app/edxapp/edx-platform/openedx/core/lib/xblock_builtin/xblock_discussion', '/edx/app/edxapp/edx-platform/common/lib/xmodule', '/edx/app/edx_ansible/edx_ansible/docker/plays', Path('/edx/app/edxapp/edx-platform'), Path('/edx/app/edxapp/edx-platform/lms/djangoapps'), Path('/edx/app/edxapp/edx-platform/common/djangoapps')] Server time: Tue, 7 Jan 2020 10:22:44 +0000 Please help me -
How to inherit a model of CustomUser to Different App Module in django?
I want to have a same table as my Custom User which can be used in other apps. I want to create a separate module with same database table. I have created the three groups. 1:- Super User 2:- Company 3:- User I want to enter data from both the modules. -
How to compare user input to corresponding model field django
I'm trying to make learning app for myself and part of my plan is to make a quiz module. My problem is, that I don't know how to compare user answer with the correct answer that's stored in the model. Now, the only thing I've tried (except reading docs and stack overflow) was to inject the related model question inside of my HTML to later use in views.py, but from the beginning I felt like that's not the way it should work, so I guess I have to reorganize my models/forms or inside of views.py there is some way to query database for that specific model instance that I don't know. Here is my code Models: class Question(models.Model): question = models.CharField(max_length=100, unique=True) answer = models.CharField(max_length=100, unique=False) def __str__(self): return self.question Forms: class Answer(forms.Form): answer = forms.CharField() Views: def quiz(request): questions = Question.objects.order_by('question') form = Answer() context_dict = {'form':form,'questions':questions} if request.method == 'POST': form = Answer(request.POST) if form.is_valid(): #Here I want to make the comparison pass return render(request,"quiz_app/quiz.html",context_dict) HTML: <table> {% for q in questions %} <tr> <td>{{ q.question }}</td> <form method="POST"> <td>{{ form.answer }}</td> {% csrf_token %} <td> <input type="submit" value="submit"> </td> </form> </tr> {% endfor %} </table> -
Can we call serializer class using a string in Django rest frame work?
This is the object we are using to get serializer class serializer_obj = {'Check Layout Query': 'ChecklayoutQueryViewSerializer', 'Check Remitter Query': 'RemitterQueryViewSerializer', 'Check Processing Query': 'ProcessQueryViewSerializer'} I want to use the key of above dictionary to get the serializer class: serializer = ProcessQueryViewSerializer(queyset, many=True) -
Django admin custom serarch filter or unicode handling
I put the UTF-8 encoded 'json' in models then I add the search filed to admin screen proj/myapp/models.py class MyJson(models.Model): my_json = models.CharField(null=True,max_length=20000) proj/myapp/admin.py class MyJsonAdmin(admin.ModelAdmin): search_fields = ["my_json"] then I try to search the word but in vain. I guess it is because of text is stored in json with this Unicode Character. \u3054\u81ea\u7531\u306b\uff01\u3044 Is there any way to solve this?? I think I should make custome search_fields callback though, I am not sure how to do this. -
AttributeError: type object 'User' has no attribute 'objetcs'? [closed]
populate.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE",'ProTwo.settings') import django django.setup() from apptwo.models import User as UserModel from django.db import models from faker import Faker fakegen = Faker() def populate(N=5): for entry in range(N): fake_name = fakegen.name().split() fake_first_name = fake_name[0] fake_last_name = fake_name[1] fake_email = fakegen.email() user = UserModel.objetcs.get_or_create(first_name=fake_first_name, last_name=fake_last_name, email=fake_email)[0] if __name__=='__main__': print("populatin database") populate(20) print('complegte') -
Error:'Answer' object has no attribute 'get'?
I'm using Django 1.11. when I'm using this code it works with me but when I'm trying to add new condition besides in this case (else) I get this error: image I want to put a new condition to stop anyone could put (get method) on my page, How can so? favourite.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Favourite Page</title> <style> input {padding: 8px;margin-top: 5px} label {display: inline-block} .input {display: inline-block} </style> </head> <body> {% if form_data %} {{ form_data.question }} {% else %} <form action="{% url 'market:favourite' %}" method="post"> {% csrf_token %} {% include 'market/template-form.html' %} <input type="submit"> </form> {% endif %} </body> </html> views.py def favourite(request): context = {} form = Answer context['form'] = form if request.method == 'POST': form = form(request.POST) if form.is_valid: form.save(commit=False) return render(request, 'market/favourite.html', {'form_data': form.cleaned_data}) else: form = Answer() return form return render(request, 'market/favourite.html', {'form': form}) Please let me know if you want me to show you more files but I think those files that what do you want to see. not the rest of the files because the errors don't emerge unless I use just a new condition. -
Making Async or Parallel Requests with Django 3.0.1
I have as simple view connecting to an API for a number of stocks and saving them in the database: def update (request): if request.method == 'GET': localStocks = Stock.objects.all() output = [] ticker = [] for local_stock in localStocks: api_response = requests.get("https://cloud.iexapis.com/stable/stock/"+ str(local_stock.ticker) + "/quote/?token="+token) ticker.append(local_stock.ticker) try: data = json.loads(api_response.content) output.append (data) dic_data = { "symbol": data['symbol'] , "latestPrice": data['latestPrice'] , "companyName": data['companyName'], "week52High": data['week52High'] , "week52Low": data['week52Low'] , "ytdChange": data['ytdChange'] , "latestTime": data['latestTime'], "changePercent": data['changePercent'] , } for i in dic_data: setattr(local_stock, i, dic_data[i]) print (dic_data[i]) local_stock.save() except Exception as e: api = "%%% DB save Error %%%" print(e) return redirect ("stocks:get_stock") The problem is --even with just 12 stocks -- this code is very slow. I read a tutorial at here but I am not sure if I should try to use parallel requests or async requests in my code and how to implement it. -
How to delete user with confirmation by passing url and username var in django
i have html that show the list of user created in this application in table here's the html <div class="row mt"> <div class="col-md-12"> <div class="content-panel align-content-center"> <table class="table table-striped table-advance table-hover"> <thead> <tr> <th><i class="fa fa-bullhorn"></i> User</th> <th><i class="fa fa-bookmark"></i> Email</th> <th><i class="fa fa-bookmark"></i> Division</th> <th><i class="fa fa-bookmark"></i> Role</th> <!-- <th><i class=" fa fa-edit"></i> Status</th> --> <th></th> </tr> </thead> <tbody> {% for user in users %} <tr> <td class="user_name"> {{user.name}} </td> <td> {{user.email}} </td> <td> {{user.division}} </td> <td> <select id="userroles" class="roleselect" data-username="{{ user.name }}"> <option selected="selected"> {{user.role}} </option> {% if user.role == "Business Analyst" %} <option>Admin</option> <option>Manager</option> <option>Segment Manager</option> {% elif user.role == "Admin" %} <option>Business Analyst</option> <option>Manager</option> <option>Segment Manager</option> {% elif user.role == "Manager" %} <option>Admin</option> <option>Business Analyst</option> <option>Segment Manager</option> {% else %} <option>Admin</option> <option>Manager</option> <option>Business Analyst</option> {% endif %} </select> </div> </td> <td> <button class="btn btn-danger btn-xs" onclick="myFunction()"><i class="fa fa-trash-o "></i></button> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- /content-panel --> </div> <!-- /col-md-12 --> </div> <!-- /row --> </section> </section> i want to make a delete function that need a confirmation , before that i use the onlick = "window.location.href ='{% url 'polls:deleteuser' user_name=user.name %}';", and it works but now i want to make a confirmation … -
Django REST return 404 Not Found by nginx
I have deployed my web app on a server(nginx+uWSGI) and have been able to login through the admin but when I try to use the REST curl http://127.0.0.1:7500/me/DjangoAPI/api/test1/check/ I get a 404 error. Is there sth that I have to do to nginx inorder for the routing to work? default.conf upstream django { server unix:///home/me/DjangoAPI/djangoapp.sock; #file socket } server { listen 8000; server_name example.com; location / { root /usr/share/nginx/html; index index.html index.php index.htm; } location /me/DjangoAPI/ { alias /home/me/DjangoAPI; uwsgi_pass django; include /home/me/DjangoAPI/uwsgi_params; } location /static/ { alias /home/me/DjangoAPI/static/; } DjangoAPI/urls.py urlpatterns = [ path('me/DjangoAPI/admin/', admin.site.urls), #REST FRAMEWORK URLS path('me/DjangoAPI/api/test1/', include('test1.api.urls', 'test1_api')), path('me/DjangoAPI/api/test2/', include('test2.api.urls', 'test2_api' )), ] test1/api/urls.py urlpatterns = [ path('check/', api_retreive_test_view, name='test1'), ] test1/api/urls.py @api_view(['GET',]) def api_retreive_test_view(request): if request.method == 'GET': return Response(status=status.HTTP_200_OK) -
How to post one html form data into two models in django?
I am having an html form consisting of some fields with details and now I want to post the some details of the form to one model and some details to another model how this can be done? my models.py class room(models.Model): id = models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.content # This is the model for goals class goal(models.Model): id=models.IntegerField(primary_key=True) goal = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.goal # This is the model for designs class design(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.content # This is the model for furniture class furniture(models.Model): id=models.IntegerField(primary_key=True) phrase=models.CharField(max_length=60,default='111111') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.phrase # This is the users model class user(models.Model): username=models.CharField(max_length=20) email=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.username class UserRequirement(models.Model): id=models.IntegerField(primary_key=True) user=models.ForeignKey(user,on_delete=models.CASCADE) rooms = models.ForeignKey(room,on_delete=models.CASCADE) goals = models.ManyToManyField(goal) styles = models.ManyToManyField(design) furn = models.ForeignKey(furniture,on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) My views.py for posting: def user_register(request): if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid(): username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] rooms = request.POST['room'] g=goals=request.POST['goal'] … -
Django UNIQUE constraint failed: core_organization.name
So I have a model called Organization inside core/models.py. I am trying to implement CRUD Ajax on a single page. Inspired by this post. Every time I save an object of this model I get this error as shown below. I want to have multiple organizations that are unique. core/models.py class Organization(models.Model): name = models.CharField(max_length=255, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=1000, default=None) is_billed = models.BooleanField(default=False) def __str__(self): return f'{self.name} Organization' core/forms.py class OrganizationForm(forms.ModelForm): class Meta: model = models.Organization fields = ('name', 'address') core/views.py def save_organization_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): stock = form.save(commit=False) stock.user = request.user stock.save() data['form_is_valid'] = True organizations = Organization.objects.all() data['html_book_list'] = render_to_string('core/includes/partial_organization_list.html', { 'organizations': organizations }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) @login_required(login_url="/accounts/login/") def organization_create(request): if request.method == 'POST': form = OrganizationForm(request.POST) else: form = OrganizationForm() return save_organization_form(request, form, 'core/includes/partial_organization_create.html') And when I add a new organization I get the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: core_organization.name How do I fix this?