Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Docker MySQL docker-compose up error
I am dockerizing my existing Django rest project which uses MySQL as database. I already have an exiting database with some data in it. my dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt My docker-compose: version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root web: build: . command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #django.db.backends.mysql 'NAME': 'libraries', #local: libraries #server: 'USER': 'root', #localhost:root #root 'PASSWORD': 'root', #local: root #server: 'HOST': 'db', #docker: db #local: localhost #server: 'PORT': '3306', } } My docker-compose build was successful. However, docker-compose up gives me error with following log: D:\Development\Personal projects\library_backend>docker-compose up Creating librarybackend_web_1 Creating librarybackend_db_1 Attaching to librarybackend_db_1, librarybackend_web_1 db_1 | Initializing database db_1 | 2018-01-15T09:33:20.031132Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). db_1 | 2018-01-15T09:33:20.225632Z 0 [Warning] InnoDB: New log files created, LSN=45790 db_1 | 2018-01-15T09:33:20.259942Z 0 [Warning] InnoDB: Creating foreign key constraint system tables. db_1 | 2018-01-15T09:33:20.304181Z 0 [Warning] No existing UUID has been … -
How to verify password if use rest-auth?
I use the rest-auth to login my User. But there is a new function there, I want user can lock the screen( user have been login), and then if the user want to unlock the screen, he must type in the password, then the backend should verify the password whether is correct. You know this is not login, this is compare the encrypted password to the database, I don't know the django-rest-auth encrypted type. How to verify the password in this scenario? -
Do I really need to put my website inside an app with Django?
I am trying to build a new big project using Django. Thing is, I want most of the content on the main page 127.0.0.1:8000 and not 127.0.0.1:8000/myapp. I know I can build everything also outside of an app, but is it a good practice ? Or what to do here ? Thanks. -
How a server handles requests asynchronously
I understand this is basic but was not able to connect. Suppose a django-server(hosted on a linux system with 3gb ram and 1vCPU) is serving a request (say R1) which takes around 1700ms. and during this execution at 100ms a request R2 comes in. Here, the server is already busy handling R1. So will R2 have to wait for 1700ms - 100ms = 1600ms? How is this handled? Is there something like instances(as in aws) which solves this? -
Django Response Middleware: Get name of view which created the response
I have simple middleware which checks if the HTML in the response is valid or not. If the HTML is not valid an html is not valid" exception gets raised in development systems. Up to now the xception contains the URL and the validation error. Then the developer sees the URL in the well known yellow and gray django debug page. Maybe I am blind, but if I look at the django debug page, I can't see which of my methods/views created the content with the broken html. Is there a way to add more information to the "html is not valid" exception, to assist the developer? The developer should find the relevant method/view easier. -
Django Python3 End-of-central-directory signature not found
I am able to run the following code (from this tutorial) via my local python3 installation and it works (creates a zip file that I can unzip on my mac using unzip file.zip) import zipfile zip = zipfile.ZipFile(‘Python.zip’, ‘w’) zip.write(‘file1.txt’) zip.write(‘file2.gif’) zip.close() However when I run the following code within a django view: zipped_file = zipfile.ZipFile("csvOutput{}.zip".format(timestamp), 'w') zipped_file.write(sms_file_path) zipped_file.write(mail_maga_file_path) zipped_file.close() I am left with a file that throws the following error when attempted to be unzipped: Archive: csvOutput2018-1-15.zip End-of-central-directory signature not found. Either this file is not a zipfile, or it constitutes one disk of a multi-part archive. In the latter case the central directory and zipfile comment will be found on the last disk(s) of this archive. unzip: cannot find zipfile directory in one of csvOutput2018-1-15.zip or csvOutput2018-1-15.zip.zip, and cannot find csvOutput2018-1-15.zip.ZIP, period. T_T -
python - ImportError: cannot import name 'path'
So, i'm learning django and trying to deploy my first project to pythonanywhere.com. Upon trying to migrate the database, I get the error: ImportError: cannot import name 'path' I've read elsewhere that this a feature of dgango 2.0, but i don't get this error on my local machine that's still using 1.11.2. Any help with this would be most appreciated. -
TypeError: unsupported operand type(s) for -: 'str' and 'str' + ValueError: can only convert an array of size 1 to a Python scalar
i have a code here which is working perfeclty fine but when i add another .csv file to compile it these two errors are showing Traceback (most recent call last): File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1202, in na_op result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\computation\expressions.py", line 204, in evaluate return _evaluate(op, op_str, a, b, **eval_kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\computation\expressions.py", line 64, in _evaluate_standard return op(a, b) TypeError: unsupported operand type(s) for -: 'str' and 'str' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 505, in <module> fTrain, lTrain = preprocessKNN(trainSet) File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 70, in preprocessKNN normalizedDataset = normalizeData(dataSet, normalizeColoumns) File "C:/Users/Dawood/Desktop/ML-PredictElections-master/MLAlgorithms.py", line 19, in normalizeData col_norm = int(col - col.min()) / int(col.max() - col.min()) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1262, in f return self._combine_series(other, na_op, fill_value, axis, level) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3944, in _combine_series try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3958, in _combine_series_infer try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\frame.py", line 3981, in _combine_match_columns try_cast=try_cast) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 3435, in eval return self.apply('eval', **kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 3329, in apply applied = getattr(b, f)(**kwargs) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 1377, in eval result = get_result(other) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\internals.py", line 1346, in get_result result = func(values, other) File "C:\Users\Dawood\AppData\Local\Temp\MLAlgorithms.py2\venv\lib\site-packages\pandas\core\ops.py", line 1216, in na_op yrav.fill(yrav.item()) … -
Use Logging SocketHandler with Django
I've configured my logging as so: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'cute':{ 'class': 'logging.handlers.SocketHandler', 'host': '127.0.0.1', 'port': 19996 }, }, 'loggers': { 'django': { 'handlers': ['cute'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } But when I try and log out I get an error in the console: TypeError: an integer is required (got type socket) This seems to be happening within an attempt to pickle the log message, I think. What is going on, and how can I get the SocketHandler to work? -
Look up for a Key in a list of dict and retrieve Value in HTML
How can I lookup for a particular key in a list of dict and return the value in my HTML ? for example my list of dict is : [{44:50},{45:67},{46:68}] and I would like to look up in the dict if the key = i.id then print the value How can I do it ? <tbody> {% for i in app_with_resp %} <tr> <td>{{i.first_name}}</td> <td>{{i.last_name}}</td> <td>17/06/86</td> <td>{{appli_score_list[i.index][i.id]}}</td> <td>{{team_score}}</td> <td> <a href="{% url 'website:CandidateDetails' pk1=current_project_id pk2=i.id %}"> Details</a></td> </tr> {% endfor %} </tbody> -
When defining a new resize rule in wagtail, when the run method it is called?
I'm defining a new resize rule in wagtail for the image tag. class FocalAreaOperation(Operation): vary_fields = ( 'focal_point_width', 'focal_point_height', 'focal_point_x', 'focal_point_y' ) def construct(self, size): # Get width and height width_str, height_str = size.split('x') self.width = int(width_str) self.height = int(height_str) def run(self, willow, image, env): // DO SOMETHING return window When I add or modify the focal area of the image the run method is called, but if I remove the focal area the run method is not called. Does anyone know something about it? Thanks a lot, best regards, nifel87 -
Django chatterbot response is not showing in chat window
i am trying Django chatterbot. when i want to interact with bot, bot's response is not showing in chat window. please check the attached image. There is no error in code when i am running it. i also tried python manage.py makemigrations python manage.py migrate python manage.py migrate django_chatterbot python manage.py train i am unable to figure out the problem. Please help. Thanks. -
Django Page not rendered and not visible
I have cloned a project from Git on my laptop. After the installation of all the requirements, while running the server I found out that a page is not rendered correctly, therefore I can't see the body. More precisely the body is not shown on the webpage. Does anyone know why this happened? This is the code: {% block content %} <section id="consultanta_totala"> <div class="pricing_div" id="consultanta"> <div class="container" id="container_consultanta" > <div class="row" id="text1"> <div class="col-xs-12 offset-xs-0 col-sm-10 offset-sm-1 risk_management"> <br><br> <h4> Risk management </h4> <p> • Crearea structurii de securitate a firmei Dvs.</p> <p>• Verificarea antecedentelor penale ale angajatilor</p> <p>• Verificarea compatibilitatii angajatilor</p> <p>• Verificare loialitatii angajatilor</p> <p>• Norme interne de protectie a firmelor</p> <p>• Profiling</p> </div> <br> </div> <br> <div class="row"> <div class=" col-xs-12 offset-xs-0 col-sm-10 offset-sm-1 verificare"> <h4>Verificarea partenerilor de afaceri</h4> <p> Din punct de vedere al:</p> <p>• Solvabilitatii si seriozitatii persoanei</p> <p>• Corectitudinii obligatiilor contractuale</p> <p>• Intentiilor reale si ale concurentei neloiale</p> <br> <br> </div> </div> </div> </div> </section> {% include 'navbar_bottom.html' %} {% endblock %} PS before posting the item on git it worked properly. Thank you! -
django datetime declaration error
I added the following code in models.py : class Conference(models.Model): conf_name = models.CharField(max_length=250) location = models.CharField(max_length=500) note = models.TextField(max_length=500) note2 = models.TextField(max_length=500) date_from = models.DateField() date_to = models.DateField() time_from = models.TimeField(default='HH:MM:ss') time_to = models.TimeField(default='HH:MM:ss') After that I ran migration commands and I got the following traceback : WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'appadmin' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/1.11/ref/databases/#mysql-sql-mode ?: (urls.W005) URL namespace 'dev_app' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: admin, auth, contenttypes, dev_app, sessions Running migrations: Applying dev_app.0016_auto_20180112_0630...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, … -
Showing and hiding menu items in django based on a non-permissions criteria?
I have a field on a Company called leave_approvers which is a ManyToManyField to Users. The leave_approvers can approve leave of other users in the company they are a leave approver for. They also receive an email when leave is requested. I would now like to show or hide the Approve Leave tab in the main layout based on whether the user is a leave_approver. Is the decision to have a leave_approver field flawed as I should be using the built in authorisation or something like django-guardian. Note that I am sending an email to the leave_approvers and that would mean Can I just make a query in the base.html to check if a user is a leave_approver. How can this be done and surely there is a performance hit? -
get absolute url based on requesting namespace
I have a model in one of my apps. The model returns an absolute url based on the namespace i have specified e.g news as below. @models.permalink def get_absolute_url(self): return 'news:detail', (), {'slug': self.slug} whenever i want to get the url i just call {{ article.get_absolute_url }} and it works perfectly. my trouble comes when i try to access the url while on a different namespace e.g sports. The url redirects me to what i have specified in my get absolute url function. (Below is how i have named my namespaces). urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^news/', include('news.urls', namespace='news')), url(r'^sports/', include('sports.urls', namespace='sports')), ] My question is, how do i dynamically get absolute url of the current namespace? -
Why python3.4 is trying to import module form python2.7
I have this weird problem. I have Django1.11 project using Python 3.4. I wonder why it is trying to import pandas from Python 2.7 File "/usr/local/lib/python3.4/dist-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in _gcd_import File "<frozen importlib._bootstrap>", line 2237, in _find_and_load File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked File "<frozen importlib._bootstrap>", line 1129, in _exec File "<frozen importlib._bootstrap>", line 1471, in exec_module File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed File "/home/ubuntu/workspace/powrbot/company/models.py", line 3, in <module> import pandas as pd File "/usr/local/lib/python2.7/dist-packages/pandas/__init__.py", line 19, in <module> "Missing required dependencies {0}".format(missing_dependencies)) ImportError: Missing required dependencies ['numpy'] FYI: python --version is Python 3.4.3 I run project like: python manage.py runserver 0:8000 Numpy is already installed in 3.4 Requirement already satisfied: numpy in /usr/local/lib/python3.4/dist-packages -
Django set default for Date field to timezone date
I am trying to use my timezone date as the default for DATE Field but I am unable to do so. For DateTime filed setting the default=timezone.now works perfectly but for Date field I can't figure out any way. time = models.DateTimeField(default=timezone.now) This Works date = models.DateField(default=timezone.now) But this does not work date = models.DateField(default=timezone.now().date) And even this doesn't work. -
django_mongokit 0.2.6 not working in Django 1.11
I installed django_mongokit 0.2.6, but it's not working in Django 1.11. While run server shows below error, $ python manage.py runserver Try using 'django.db.backends.XXX', where XXX is one of: u'base', u'mysql', u'oracle', u'postgresql_psycopg2', u'sqlite3' Error was: cannot import name BaseDatabaseOperations Django : (1.11) Pymongo : (2.5) django-mongokit : (0.2.6) pymongo : (2.8) PyMySQL : (0.8.0) settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example', }, 'mongodb': { 'ENGINE': 'django_mongokit.mongodb', 'NAME': 'example', }, } -
Call a method that is set to use a specific argument, that is not available
I have a question that I do not know how to solve. I have a list view where I list user in a table with on each row some informations such as first_name last_name and a link to the user detail page. the URL for both page are in the form, list view : .../pk1/, detail view : .../pk1/pk2 where pk1 is project_id and pk2 is user_id On that detail page I make some calculation in order to get a user score and I would like to show that user score on each row in my list view. The problem is that in order to calculate that score it extracts data using pk2 which is not available on my list view since the URL contain only pk1 here is an example of one of the method used to calculate the user score: def get_applicant_team_list(self, format=None, *args, **kwargs): current_team_member = list(Project.objects.get(id = self.kwargs['pk1']).team_id.members.all()) current_applicant = MyUser.objects.get(id =self.kwargs['pk2']) current_team_member.append(current_applicant) applicant_response_list = [] for member in current_team_member: applicant_id = member.id applicant_response = get_user_response(applicant_id) applicant_response_list.append({applicant_id:applicant_response}) return applicant_response_list def get_applicant_info_array(self, format=None, *args, **kwargs): response_list = get_applicant_team_list(self) info_array = get_info_array(response_list) return info_array How can I call my methods for each user in the context of my … -
Django startup error on IIS
When I try to start my Django app on IIS I have the error such below: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\inetpub\wwwroot\ddr\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\Python27\lib\site-packages\django\core\wsgi.py", line 14, in get_wsgi_application django.setup() File "C:\Python27\lib\site-packages\django__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 48, in getattr self._setup(name) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 44, in setup self._wrapped = Settings(settings_module) File "C:\Python27\lib\site-packages\django\conf__init__.py", line 92, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python27\lib\importlib__init__.py", line 37, in import_module import__(name) File ".\config\settings\production.py", line 21, in SECRET_KEY = env("DJANGO_SECRET_KEY") File "C:\Python27\lib\site-packages\environ\environ.py", line 117, in call_ return self.get_value(var, cast=cast, default=default, parse_default=parse_default) File "C:\Python27\lib\site-packages\environ\environ.py", line 250, in get_value raise ImproperlyConfigured(error_msg) ImproperlyConfigured: Set the DJANGO_SECRET_KEY environment variable StdOut: StdErr: Django secret key is written in handler mappings. Maybe someone had the such error and know what I should do? Thank you all. -
How to convert this javascript code to python
I have this code in Python, actually my views.py of an app in Django project: import json from django.shortcuts import render from django.http import HttpResponse from rest_framework.views import APIView from panel.serializers import UserSerializer from panel.models import Caseworker # Create your views here. class UserAPI(APIView): serializer = UserSerializer def get(self, request, format=None): list = Caseworker.objects.all() response = self.serializer(list, many=True) return HttpResponse(json.dumps(response.data), content_type='application/json') That returns me this JSON: [{"name": "John", "last_name": "Caseworker", "telephone": "+38168999456", "email": "john@caseworker.com", "organization": "Organization 1"}] What I need to do is adapt this javascript into my python code app.get('/jokes', function(request, response) { const requestOptions = { uri: 'https://icanhazdadjoke.com/', headers: { Accept: 'application/json' }, json: true }; requestPromise(requestOptions) .then(function(data) { response.json({ messages: [ {text: data.joke} ] }); }); }); Because I have to adapt the JSON that python gives to me with this specific structure response.json({ messages: [ {text: data.joke} ] }); But actually I don't know how to do it without break my python code. -
django M2M Field issue
Django M2M problem, i am trying to get QoutID selected in the form template and then save it in the Selected Field M2M The createview is working fine with null value but in the UpdateView i would like to update SELECTED field based on selection in the form template views.py class QoutationAttachUpdateView(SuccessMessageMixin, UpdateView): template_name = "ePROC/Acquisition/qoutation_update_attach.html" model = QoutationSelection form_class = QoutationSelectForm context_object_name = 'qoutupdate' success_message = 'Record updated successfully and Requestor is notified by mail' #def dispatch(self, request, *args, **kwargs): # self.AcqID = QoutationSelection.objects.get(id=self.kwargs['pk']) # return super(QoutationAttachUpdateView, self).dispatch(request, *args, **kwargs) success_url = reverse_lazy('ePROC:ePROCHOME') def form_valid(self, form): instance = form.save(commit=False) data =QoutationSelection.objects.get(QoutID=form.instance.QoutID) instance.Selected.set(data) instance.save() return super(QoutationAttachUpdateView, self).form_valid(form) Models.py class QoutationModel(models.Model): REF=models.CharField(max_length=40,default='BKB-Q-') RequestItem=models.ForeignKey(CreateACQModel,on_delete=None,related_name='CreateRID') RequestQuantity=models.PositiveIntegerField(validators=[MinValueValidator(1)]) VendorID=models.ForeignKey(VendorModel,on_delete=None,related_name='VendorID') ccy=models.CharField(choices=ccych,max_length=40) amount=models.PositiveIntegerField(validators=[MinValueValidator(1)]) date=models.DateTimeField(auto_now_add=True) status=models.CharField(max_length=40,choices=QouteCH,default='Received') descr=models.TextField(null=True, max_length=200) qoute=models.FileField(upload_to='documents/',validators=[FileExtensionValidator(['pdf','zip','rar', 'txt', 'jpg', 'gif', 'doc', 'docx', 'xls', 'xlsx'])],blank=True, null=True) def __str__(self): return '%s' %(self.REF) class Admin: pass def get_absolute_url(self): return reverse('qoutation-list', kwargs={'pk':self.id}) class QoutationSelection(models.Model): AcqID=models.ForeignKey(CreateACQModel,on_delete=None) QoutID=models.ManyToManyField(QoutationModel) Selected=models.ManyToManyField(QoutationModel,related_name="Selected") def __unicode__(self): return '%s' %(self.REF) def __str__(self): return '%s' %(self.REF) forms.py class QoutationSelectForm(forms.ModelForm): QoutID = forms.ModelChoiceField( queryset=QoutationSelection.objects.all(), required=False,empty_label=None ) class Meta: model = QoutationSelection labels = { "Status":"Status", "AcqID":"Acquisition ID", "qoutid":"Qoutation ID", } exclude=['AcqID','Selected',] def __init__(self, *args, **kwargs): super(QoutationSelectForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['QoutID'].queryset = self.instance.QoutID.all() -
How to extend users from other db in django?
I am joining two Django apps and they will have "users" in common both Apps are in different databases. I was using a routers and everything was working fine but the problem appeared when I was trying to import User from the other db. My users model looks like this: class Company(models.Model): company_name = models.CharField(max_length=250, null=True) active = models.BooleanField(default=True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" def __str__(self): return self.company_name class CompanyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company) token = models.TextField(null=True,blank=True) class Meta: verbose_name = "Users - Company" verbose_name_plural = "Users - Company" In my view I have this: from users.models import Company, User company = request.user.username #This is fine company = request.user.companyuser.company This gives error I am getting this error **User has no companyuser** -
How to POST data from a multiple select box in Django Rest Framework
I am trying to use AJAX to make a POST request to DRF. One of my fields is a multiple select box. I can't seem to find a way to make the request work properly. I have tried posting the entire select box like below. var roles = $('#roles').val(); I have also tried posting an array of the values. var roles = $('#roles').find('option:selected').map(function(){return $(this).val()}).get(); My AJAX call looks like this: $.ajax({ method: "POST", url: "/v1.0/relationships/" + url, data: {roles: roles} ) My API view looks like this: class RelationshipSingle(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): """ /relationship/{id} Method Action GET Return details of relationship with ID {id}. POST Invalid option. PATCH Edit the relationship. DELETE Delete the relationship. """ queryset = Relationship.objects.all() serializer_class = RelationshipSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) My serializer looks like this: class RelationshipSerializer(serializers.ModelSerializer): class Meta: model = Relationship fields = '__all__'