Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
To add GET parameters in Swagger
Use django rest framework and django-rest-swagger in documentation of the methods it is not showing available GET parameters and the question is how can I set? ru version. -
Django add form on every page
In my application i need to add a form in base.html, which I've done. For this i used context_processors, now my problem is everytime i'm trying to post, i'm getting a blank page and this error: Method Not Allowed (POST) In this form i want just to add a button where it will mark all current users notifications as read. I know that you can use context_processors like this: def my_context(request): data = dict() if request.user.is_authenticated: data['notifications'] = Notification.objects.filter(user=request.user, read=False) data['form'] = NotificationForm() return data But instead of adding the form i need these lines: def my_context(request): data = dict() if request.user.is_authenticated: data['notifications'] = Notification.objects.filter(user=request.user, read=False) if request.method == 'POST': if 'read-notifications' in request.POST: for notification in data['notifications']: notification.read = True notification.save() next = request.POST.get('next', '/') return redirect(next) return data The form in base.html: <form action="" method="POST">{% csrf_token %} <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit" class="btn m-btn--square btn-primary" name="read-notifications">Mark as read</button> </form> urls.py url(r'^orders/create/$', views.admin_order_document, name='create_order'), url(r'^orders/waiting/$', views.OrdersWaitingListView.as_view(), name='order_waiting_list'), url(r'^orders/unallocated/$', views.OrdersUnallocatedListView.as_view(), name='order_unallocated_list'), url(r'^orders/working/$', views.OrdersWorkingListView.as_view(), name='order_working_list'), How can i show this form on every page without getting the above error? -
Django full text search: TrigramDistance not working
I am using Django 2.0 and postgresql 9.6. I have installed pg_trgm extension in the postgresql I am trying to understand how triagram works: I am trying the following. I want words nearer to "sridam" to be matched using triagram from django.contrib.postgres.search import TrigramDistance from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('title',config='english_unaccent', weight='A') + SearchVector('description',config='english_unaccent', weight='B') query = SearchQuery('sridam',config='english_unaccent') Article.objects.annotate(distance=TrigramDistance(vector, query)).filter(distance__lte=0.7).order_by('distance') ProgrammingError: operator does not exist: tsvector <-> tsquery LINE 1: ...SCE("articles_article"."description", '')), 'B')) <-> plaint... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. -
Make one select field depend to another in Django admin
I have Django model as follows: class UserBusinessUnit(models.Model): company = models.ForeignKey(to=Company, limit_choices_to={'is_dealership': True}) user = models.ForeignKey(to=User) brands = models.ManyToManyField(to=Brand) business_unit = models.ForeignKey(to=BusinessUnit) active = models.BooleanField(default=True) class Meta: ordering = ('user__username',) def __unicode__(self): return self.user.email + ' - ' + self.business_unit.name In Django admin panel it look like this: I want to be able to populate User and Business unit field depending in Company field. Thus if I change company field I want that the User and Business field are instantly populated. Any idea how to do that? -
How to run a Django management command as a cron in a Docker container?
I just wanted to run a Django management command as a cron inside a Docker container. Dockerfile: FROM python:3 MAINTAINER DAWN ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install -y vim RUN apt-get install -y nginx RUN apt-get install -y gdal-bin RUN apt-get -y install cron RUN mkdir /code WORKDIR /code RUN mkdir /code/logs ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./my_project /code COPY ./docker-entrypoint.sh /code/my_project/ COPY ./django_nginx.conf /etc/nginx/sites-available/ RUN rm -f /etc/nginx/sites-available/default RUN ln -s /etc/nginx/sites-available/django_nginx.conf /etc/nginx/sites-enabled RUN echo "daemon off;" >> /etc/nginx/nginx.conf ADD crontab /etc/cron.d/my_cron RUN chmod 0644 /etc/cron.d/my_cron RUN touch /var/log/cron.log ENTRYPOINT ["/code/my_project/docker-entrypoint.sh"] RUN /usr/bin/crontab /etc/cron.d/my_cron crontab: 1 * * * * root python /code/manage.py my_management_command >> /var/log/cron.log 2>&1 This cron is not getting executed even though I can see it in the crontab inside the container by connecting to the container using docker exec -it my_container /bin/bash crontab -l Where am I going wrong? -
Django ORM filter nested
how do I make a django nested query, for instance to filter all products that has an attribute with (length > weight / 4000) ? Here's roughly the 3 models I'm working on Product(models.Model): name = models.CharField('name') # code for example: 'length', 'weight' Attribute(models.Model): code = models.CharField('code') AttributeValues(models.Model): product = models.ForeignKey( 'Product', related_name='attribute_values', verbose_name=_("Product") ) attribute = models.ForeignKey( 'Attribute', verbose_name=_("Attribute") ) value = models.FloatField() I hope that my model is enough to explain what I'm asking. Thanks in advance -
Django: Accessing model fields from form widget in template
I have a ModelForm which uses a CheckboxSelectMultiple widget to represent data from a ManyToManyField. By default this will render a list of checkboxes with the label being set to the return value of the __str__ method of the related model. However, I wish to display data from other fields in the related model in addition to the choice_label provided by the widget. For example consider the implementation below: models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.name class Order(models.Model): items = models.ManyToManyField('Item') forms.py from django import forms from .models import Order class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['items'] widgets = {'items': forms.widgets.CheckboxSelectMultiple} template.html {% for item in form.items %} <tr> <td>{{ item.tag }}</td> <td>{{ item.choice_label }}</td> <td>{{ item.category }}</td> </tr> {% endfor %} The problem here is the {{ item.category } part of the template.html, is there a way to access this information from the template? -
Django rest-framework getting number of registered users in a given date range
I am learning Django, I wanted to get the number of registered users in a given date range grouped by the registration date here is my code profiles = Profile.objects.filter(date_joined__gte=datetime.date(2011, 1, 1), date_joined__lte=datetime.date(2018, 2, 28)).annotate(count=Count('id')).order_by('date_joined') I want it to return as a JSON in the form { 'date': '2018-01-01', 'user_count': 14264 }, I have created a Profile Serializer but I do not think the two are compatible, the fields in Profile are not the ones I want to return Person model class Profile(User): department = models.CharField(max_length=100) def __str__(self): return self.username + " (" + self.department + " )" Person Serializer class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' -
How do I stop Django development server from restarting?
I want Django development server to exit when an error happens. But whenever the server exits, it restarts. I tried to kill the process using os.kill(os.getpid, 9) which does not work. I tried sys.exit, os._exit, and raised errors and none of them works. Notes: Since the program doesn't only run on Linux, so ideally I wish not to use anything like bash. Also I don't want to disrupt other processes. -
Django clean_email function returning "enter a valid email"
I made a clean_email function in my forms.py to check if the email the person is signing up with is part of a registered school. This is the form: class StudentRegister(UserCreationForm): email = forms.EmailField(required = True) def __init__(self, *args, **kwargs): super(StudentRegister, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs['placeholder'] = 'example@example.com' self.fields['first_name'].widget.attrs['placeholder'] = 'First Name' self.fields['last_name'].widget.attrs['placeholder'] = 'Last Name' self.fields['password1'].widget.attrs['placeholder'] = 'Password' self.fields['password2'].widget.attrs['placeholder'] = 'Password' class Meta: model = get_user_model() fields = ( 'email', 'first_name', 'last_name', 'password1', 'password2' ) def clean_email(self): email = self.cleaned_data.get('email') email = email.split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: raise forms.ValidationError('School not found, check your email') return email def save(self): user = super(StudentRegister, self).save() student = Student(user = user) student.save() return user, student This is the view for the student registration: def student_registration(request): #Student Registration if request.method == 'POST': form = StudentRegister(request.POST) #Gets school object from email domain. email = form['email'].value().split('@')[1] try: school = School.objects.get(email_domain = email) except ObjectDoesNotExist: pass if form.is_valid() and school: user, Student = form.save() Student.school = school Student.save() user.groups.add(Group.objects.get(name='Student')) #user.is_active to stop users logging in without confirming their emails user.is_active = False user.save() #Sends confirmation link. send_confirmation_email(request, user) args = {'email': user.email, 'link': user.Student.school.email_website,} return render(request, 'email/token_sent.html', args) else: args = {'form': form,} return render(request, … -
Django restframework import data from another table?
I'm using Django rest framework with MySQL. Let me explain my two tables. [article] - articleNo(Primary key) - content [comment] - articleNo(FK to article) - userkey - comment I want to import comment data to artice table. class articleDetailSerializer(serializers.ModelSerializer): userkey = userSerializer(read_only=True) likeCount = serializers.IntegerField(source='like_set.count', read_only=True) commentCount = serializers.IntegerField(source='comment_set.count', read_only=True) comment = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = article fields = ('articleNo', 'userkey', 'content', 'likeCount', 'commentCount', 'comment') class commentSerializer(serializers.ModelSerializer): class Meta: model = comment fields = ('articleNo', 'content', 'userkey') When I visit /article, Current output is: { "articleNo": 26, "userkey": { "userkey": "121212", "username": "Da" }, "content": "test", "likeCount": 3, "comment": [ 1, 2, 3 ] }, What I would like instead as output is something like: { "articleNo": 26, "userkey": { "userkey": "121212", "username": "Da" }, "content": "test", "likeCount": 3, "comment": [ { articleNo: 26, userkey: "12345", content: "first comment" }, { articleNo: 26, userkey: "23456", content: "second comment" }, { articleNo: 26, userkey: "33333", content: "third comment" }, ] }, Can it be implemented with Rest framework? Thanks. -
Django URL dispatcher - it calls the same view to the different URL(regular expression)
Hello thank you very much for reading my question post. I have different url path patterns in urlpatterns, but Django URL dispatcher(re-path) calls the same view( views.selected_verb) for the different URL expressed by Regular expression. These urls call the same view(views.selected_verb) http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/ http://127.0.0.1:8000/arabic/verbs/%D9%83%D8%A7%D9%86/quiz/ Would love to know how to fix it(calls different views) here is urlpatterns urlpatterns = [ path('', views.index, name='index'), path('verbs', views.verbs, name='verbs'), re_path(r'^verbs/(?P<verb>.+)/$', views.selected_verb, name='selected_verb'), re_path(r'^verbs/(?P<verb>.+)/quiz/$', views.quiz, name='quiz'), ] Thank you very much again! -
How to see Nginx log?
When I want to see the Gunicorn log to see if I have any errors, I do gunicorn --log-file=- <my_app>.wsgi:application - what command do I use to see the Nginx log? -
Django app not being served with Python3.5 and httpd
I have a Django app hosted on: Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2017 20:39:16 here's my django.conf file: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python3.5/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py My application was working when I had python 2.7 installed in my virtual environment and had django.conf like this: Alias /static /home/faizan/myproject/static <Directory /home/faizan/myproject/static> Require all granted </Directory> <Directory /home/faizan/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/faizan/myproject:/home/faizan/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/faizan/myproject/myproject/wsgi.py -
Invalid syntax error while running unit test in django
my sample django project works fine and i get result but the problem is that whenever i run unit test on my project i get syntax error as follows in test.py. i have tried using .format() still it shows up error .why cant i use f'this is my text' to format my string ? error log ERROR: blog.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: blog.tests Traceback (most recent call last): File "/usr/lib/python3.5/unittest/loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/home/blog/tests.py", line 28 self.assertEqual(f'{self.post.title}', 'Content') ^ SyntaxError: invalid syntax -
Why does Jenkins starting my django server give me 404, but manually running the same script work properly?
This is my fabric script that runs on the jenkins server. sudo('/home/myjenkins/killit.sh',pty=False) sudo('/home/myjenkins/makedir.sh',pty=False) sudo('/home/myjenkins/runit.sh',pty=False) This kills the old server, creates a virtualenv, installs the requirements and restarts the server. The problem is the with the script that starts the server - runit.sh :- nohup /home/myjenkins/devserver/dev/bin/python /home/myjenkins/devserver /workspace/manage.py runserver --noreload 0:80 >> jenkins.out & When the jenkins server that starts the server and I navigate to the homepage, it gives me a 404 Page Not Found. It says /static/index.html not found. But the file exists. When I run 'sudo bash runit.sh' and I access the homepage, It works fine. Please ask me for more details if you need it. -
Python - Django -Tastypie - How to run code after reutrningt
For the below code the return statement seems to execute only after the function has completed def runJob(objects,bgJob): """DO SOME DJANGO STUFF" try: return prepareResponce(status=202) finally: runJob(objects, bgJob) Basically I need to execute runJob after the return statement -
500 error when uploading files with Filer to S3 using boto3 and django-storages on Elastic Beanstalk
I receive the following 500 http error when attempting to upload a file via the django-cms Filer admin in my app deployed to Elastic Beanstalk: In browser console, coming from fileuploader.min.js:26: POST http://app-staging.us-east-1.elasticbeanstalk.com/admin/filer/clipboard/operations/upload/1/?qqfile=example.jpg 500 (Internal Server Error) I am using django-cms (and therefore easy-thumbnails), django-storages and boto3. When deploying, the collectstatic command in my .ebextensions config file works great, and the files are all nicely stored in the S3 bucket in /staging/static/. Removing the DEFAULT_FILE_STORAGE assignment works fine, but is obviously untenable as each eb deploy of any changes to beanstalk results in a new instance and erases previous file uploads. Stack trace: Internal Server Error: /admin/filer/clipboard/operations/upload/1/ Traceback (most recent call last): File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/admin/clipboardadmin.py", line 114, in ajax_upload file_obj.save() File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/imagemodels.py", line 53, in save super(Image, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/abstract.py", line 74, in save super(BaseImage, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/filer/models/filemodels.py", line 194, in save super(File, self).save(*args, **kwargs) File "/opt/python/run/venv/local/lib/python3.6/site-packages/polymorphic/models.py", line 74, in save … -
Getting an error while following django tutorial
I am completely new to both django and python and currently I am following https://docs.djangoproject.com/en/2.0/intro/tutorial01/ tutorial. Getting the following error while running the command python manage.py runserver. Can anyone please help? Performing system checks... Unhandled exception in thread started by <function wrapper at 0x102cf8140> Traceback (most recent call last): File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/poojadeole/Desktop/venvs/env1/lib/python2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/poojadeole/Desktop/projectdjango/mysite/mysite/urls.py", line 16, in <module> from django.urls import include, path ImportError: cannot import name include -
Django model.py models.ForeignKey()
I am a newbie on Django framework and a bit confused on the models. When a "class" in the model.py, can I just understand it as "table" in database? For example, in the code below, "Test", "Contact", and "Tag" are all tables in the database used by Django? from django.db import models class Test(models.Model): name = models.CharField(max_length=20) class Contact(models.Model): name = models.CharField(max_length=200) age = models.IntegerField(default=0) email = models.EmailField() def __unicode__(self): return self.name class Tag(models.Model): contact = models.ForeignKey(Contact) name = models.CharField(max_length=50) def __unicode__(self): return self.name In the class Tag, it is using models.ForeignKey(Contact), based on my understanding, the foreignkey should be established on one specific column of a table, but why the ForeignKey is establish on a table directly, i.e. Table Contact? Any guidance is highly appreciated. -
Can't figure out why Django not saving model field
I have some code found elsewhere on SO to get django-rest-auth to work with social login when there is an existing email account: def pre_social_login(self, request, sociallogin): """ Invoked just after a user successfully authenticates via a social provider, but before the login is actually processed (and before the pre_social_login signal is emitted). We're trying to solve different use cases: - social account already exists, just go on - social account has no email or email is unknown, just go on - social account's email exists, link social account to existing user """ # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: return # some social logins don't have an email address, e.g. facebook accounts # with mobile numbers only, but allauth takes care of this case so just # ignore it if 'email' not in sociallogin.account.extra_data: return # check if given email address already exists. # Note: __iexact is used to ignore cases try: email = sociallogin.account.extra_data['email'].lower() id = sociallogin.account.extra_data['id'] email_address = EmailAddress.objects.get(email__iexact=email) # if it does not, let allauth take care of this new social account except EmailAddress.DoesNotExist: return # if it does, connect this new social login to the existing user user … -
CKEditor - Django Admin Panel - use of extraPlugins makes text body disappear
I've got CKeditor up and running in my django project, however when I try to add imagerotate_1.1 to the plugins section within my settings.py, when I go into the admin panel to edit my blog post, the body field becomes blank. When I remove the imagerotate_1.1 it comes back again. Can anyone explain why? My project (shortened version) looks as follows: - blogproject - posts - media - static - ckeditor - ckeditor - plugins -imagerotate_1.1 - icons - lang - plugin.js - templates - posts - base.html - getAllPosts.html - blog - urls.py - settings.py - models.py SETTINGS.PY BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' MEDIA_DIR = os.path.join(BASE_DIR, 'posts/media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' CKEDITOR_UPLOAD_PATH = MEDIA_ROOT CKEDITOR_IMAGE_BACKEND = 'pillow' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #provides access to the provided authentication systemm 'django.contrib.contenttypes', # used by the auth app to track models installed in your database. 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts', 'social_django', 'ckeditor', 'ckeditor_uploader', ] CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', # 'skin': 'office2013', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, … -
Cannot add data into database in django rest api
I am trying to create a employee management system api with the given model, serializers and views. I am able to add data through django admin and it works fine there, but i am unable to add department and employees to the company through api. I the api is able to add company. I think its due to foreign key usage in the department and employee. model from django.db import models class Company(models.Model): company=models.CharField(max_length=100, blank=False) area=models.CharField(max_length=100, blank=False) about = models.CharField(max_length=100, blank=True, default='') class Meta: ordering=['company'] class Department(models.Model): company = models.ForeignKey(Company, related_name='departments', on_delete=models.CASCADE) department=models.CharField(max_length=100, blank=False) about = models.CharField(max_length=100, blank=True, default='') class Meta: ordering=['department'] # Create your models here. class Employee(models.Model): department = models.ForeignKey(Department, related_name='employees', on_delete=models.CASCADE) employee_id=models.IntegerField(primary_key=True,auto_created=True) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=False) emailid = models.EmailField() active = models.BooleanField(default=False) class Meta: ordering=['name'] with serializer from rest_framework import serializers from .models import * #HyperlinkedModelSerializer class CompanySerializer(serializers.HyperlinkedModelSerializer): departments = serializers.HyperlinkedRelatedField(many=True, view_name='company-detail', read_only=True) class Meta: model = Company fields = ('url','company', 'area', 'about', 'departments') class DepartmentSerializer(serializers.HyperlinkedModelSerializer): employees = serializers.HyperlinkedRelatedField(many=True, view_name='department-list', read_only=True) company = serializers.ReadOnlyField(source='company.company') class Meta: model = Department fields = ('url', 'department', 'about', 'employees','company') class EmployeeSerializer(serializers.HyperlinkedModelSerializer): department = serializers.ReadOnlyField(source='department.department') company = serializers.ReadOnlyField(source='department.company.company') class Meta: model = Employee fields = ('url', 'name', 'emailid','active','department','company') and … -
django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log»
I am currently developing a project in Django 2.0.2, but when migrating my models I get the following error: django.db.utils.ProgrammingError: ya existe la columna «user_id» en la relación «django_admin_log» This is all that the console shows: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\migration.py", line 122, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 421, in add_field self.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\aleja\Documents\GitHub\proyectoHelping\Proyecto\proyectoHelping\lib\site-packages\django\db\utils.py", line 89, in … -
How to organize REST-API versioning the right way?
I'm building a website's backend on Django-REST-FrameWork, and currently I have the following structure (below is only a part of it obviously): project_root: apps: app1: models.py serializers.py views.py urls.py app2: models.py serializers.py views.py urls.py urls: urls.py - (Main project urls file) An endpoints: http://localhost:8000/api/app1/ http://localhost:8000/api/app2/ How to add versioning ? should I just add an "v2" folder to each app ?