Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Form does not prevent duplicate creation of a compound primary key
I'm trying my first Django project right now and have encountered the problem that my app reacts strangely when I try to create an object with duplicated compound primary keys. The following starting situation: In order to be able to clearly determine my result, I use a composite primary key consisting of a unique student id (matriculation_number) and a unique exam id (exam_id). Here is the corresponding model in my models.py file: class Result(models.Model): # No student should be able to be deleted as long as there are still results to show. matriculation_number = models.ForeignKey(Student, on_delete=models.PROTECT, verbose_name='Matrikelnummer') # No student should be able to be deleted as long as there are still results to show. exam_id = models.ForeignKey(Exam, on_delete=models.PROTECT, verbose_name='Prüfungsnummer') grade = models.DecimalField(max_digits=3, decimal_places=2, default=None, validators=[MaxValueValidator(6), MinValueValidator(1)], verbose_name='Note') # Workaround for composite primary-key # Get Data using Result.objects.get(matriculation_number=”10”,exam_id=”125”) class Meta: unique_together = (('matriculation_number', 'exam_id'),) verbose_name = 'Ergebnis' verbose_name_plural = 'Ergebnisse' To get a composite primary key at all, I use the workaround with unique_together. The following views.py and forms.py parts also belong to it: views.py class ResultCreateView(generic.CreateView): form_class = CreateResultForm template_name = 'studentmanager/result/result_create_form.html' success_url = reverse_lazy('studentmanager:result') forms.py class CreateResultForm(forms.ModelForm): class Meta: model = Result fields = ['exam_id', 'matriculation_number', 'grade'] widgets … -
What to use django restful api
I want to know if i use django restful api in existing project inorder to use serializer i have to remove django default forms or not? even though it sounds stupid but i'll be grateful if you help me out -
Django Admin List Filter Remove All Option
As you can see from the screenshot bellow, When using and customizing django admin filters like so: class DealExpiredListFilter(admin.SimpleListFilter): title = 'expired' parameter_name = 'expired' def lookups(self, request, model_admin): return ( ('yes', 'yes'), ('no', 'no'), ) def queryset(self, request, queryset): if self.value() == "yes": return queryset.filter(end_date__lt=timezone.now()) elif self.value() == "no": return queryset.exclude(end_date__lt=timezone.now()) Django will insert an "All" option at any case (which is great for %99 of the times). I want to rename or remove that "All" option as can bee seen in the screenshot -
Django - count up timer
Hey I want to implement a timer which starts if I go to this template: {% block content %} <h3>C-Test</h3> <p>In the following text, some of the word endings have been replaced by a gap. The gap is approximately half of the word, e.g. if you see 3 letters, you need to add another 3-4 letters to complete the word. Try your best.</p> <form action="results" id=results method="POST"> <input type="hidden" name="cTestFormat" value="{{ text }}"> <div class="ctest"> {% csrf_token %} {{ forms }}{{ ende }} </div> <div class="command"> <button type="submit" name="ctest_submit">Submit solution</button> </div> </form> {% endblock %} and ends if I click on the Submit solution button. I want it saved into the POST request so I can return the time in my results.html. This is my results.html: {% block content %} <h3>C-Test</h3> {% csrf_token %} <p>You got {{ richtige }} right!!!!!!</p> <p>But {{ falsche }} wrong :(</p> <p> {{ testresult|safe }}</p> {% endblock %} Ive read that you need some scripting language for a timer but I dont have any experience with it. Is there any other method with django to do this or do I need something like javascript? -
How to deploy a Django app locally on a windows xp machine?
I've got a small python 3 application which I'd like to use on a Windows XP machine. Now, the python shell is not that user-friendly, so I decided to build a GUI for it. I've tried using PyQt (with Qt designer) and TkInter, but I don't like working with them. In search for alternatives, I thought about Django. I've worked on a project with Django once and I like the fact that I can use HTML to format the way the app looks. Oh, and I'm in love with how easy it is to implement the admin functionality. However, it looks like deploying a Django application locally on a Windows XP machine isn't even possible. I've read the most recent Django documentation and it states nothing about doing such a thing. If my question is still vague: I'd like to deploy a Django web app locally to use in a browser like Internet Explorer on a Windows XP machine. The installation should be 'plug-and-play'. The application relies on a csv database, so nothing too fancy there. I don't want the user to have them install Python or other dependensies himself. Ultimately, the user should only have to click on the … -
Django Getting User based on AuthToken
I am setting up friend relationships on a social-media style project. When a user goes to the /add_friend endpoint I want Django to automatically know who the user is trying to add a friend based on the AuthToken they are using. I cannot figure out how to do this. Models: class Friend(models.Model): #static variables for friend_status attribute FORMER_FRIENDS = 0 FRIENDS = 1 A_REQUESTS_B = 2 B_REQUESTS_A = 3 friend_A = models.ForeignKey(User, related_name='friend_A') friend_B = models.ForeignKey(User, related_name='friend_B') friend_status = models.IntegerField def __str__(self): return '%s and %s friendship' % (self.friend_A, self.friend_B) class Meta: unique_together = (('friend_A', 'friend_B'),) URL: url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'), Class-Based View: class AddFriend(APIView): def get(self, request, username): user = Token.objects.get(key='token string').user friend = User.objects.get(username=username) #check for friendship instance new_friend, created = Friend.get_or_create(friend_A=user, friend_B=friend) I'm almost certain the trouble is this line: user = Token.objects.get(key='token string').user I don't know what value to enter for the key. The key is unique for each token, and I obviously don't want to hard code a key in there. I have tried removing the key entirely like this: user = Token.objects.get.user But in that case I get the error: AttributeError at /friend_request/brian 'function' object has no attribute 'user' Can someone please advise … -
Unable to Escape \? in Python Regex
This question has been asked many times before. And the answer is all the same: If searching for a literal question mark r'?' then the question mark should be escaped with a backslash r'\?' The problem is that I keep getting this Django Error when I run the command: nothing to repeat at position 0 (line 1, column 1) What have I done wrong in my code? rawcontent = "Im Ron Burgandy? I saw that! Brick killed a guy. Did you throw a trident? San Diego..." # This line works fine. rawcontent = re.sub('!\r\n([a-zA-Z])',r"!\r\n#Stuff-To-Insert#\1", rawcontent) # This line causes the error, although it should catch the ? on the 1st and 2nd lines rawcontent = re.sub('?\r\n([a-zA-Z])',r"\?\r\n#Stuff-To-Insert#\1", rawcontent) I've tried: Googling like crazy, multiple backslashes \? & \\? & \\\?, and cursing & squinting really hard at the screen, but nothing works. Note: I'm using Python 3.7 & Django 2.1 - Similar Posts Question1, Question2, Question3 - -
How to define a foreign key based on name when extending a django-oscar model?
I have forked the django-oscar catalogue app to have an additional model, Collection. This is for a furniture site, so the idea is that several products will be part of a collection, which has a name in common with all products. For example, a Bedroom collection might have a nightstand, chest of drawers and bed, all named 'Denver'. My goal in doing this is so that I can display a page showing different collections, and for each collection show all the products associated with that collection. Also that when deleting a collection all associated products are deleted, but not the other way around. This is the model I am using in my forked version of the django-oscar catalogue app: from django.db import models class Collection(models.Model): name = models.CharField(max_length=50) prod_category = models.CharField(max_length=50) description = models.TextField() manufacturer = models.TextField() num_products = models.PositiveIntegerField() image_url = models.URLField() from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) multiplier = models.DecimalField(max_digits=2, decimal_places=1, default='2.2') from oscar.apps.catalogue.models import * My concern is that, by setting the foreign key as I have, django automatically creates a collection_id field, but each product is not tied to a collection based on any criteria. I would like to use the … -
Is it possible to pass an argument to a celery task in django settings?
I have the following entry in my settings.py file: CELERYBEAT_SCHEDULE = { 'exec-task-every-hour': { 'task': 'app1.tasks.task1', 'schedule': crontab(hour='0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23', minute='0') } } And int works perfectly. Is it possible to add an argument, and pass it through this settings entry, to the task being called (task1)? -
How to add emotion detection to Django website?
I want to add machine leaning(like emotion detection or face recorgination) to my python(django) based website.Do I need to use Rest Api for it? How this gonna work? I am new to it so help please! How Json can help?? -
Where is django installed windows?
I am trying to find the file Django admin but I can't find it. What command can I use to find where this is located? Thanks. P.S I am using windows 10 -
POST Request Method not working in Django Rest Framework
Whenever I try a post request, this is the error I get: TypeError at /api/ Direct assignment to the forward side of a many-to-many set is prohibited. Use project_team.set() instead. Request Method: POST Request URL: http://127.0.0.1:8000/api/ Django Version: 2.0 Exception Type: TypeError Exception Value: Direct assignment to the forward side of a many-to-many set is prohibited. Use project_team.set() instead. Exception Location: C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related_descriptors.py in set, line 509 Python Executable: C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.3 Python Path: ['C:\Users\Siddhesh\Desktop\TechForSocial\backend', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\python36.zip', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages', 'C:\Users\Siddhesh\AppData\Local\Programs\Python\Python36\lib\site-packages\pytz-2018.5-py3.6.egg'] Server time: Mon, 17 Dec 2018 17:57:57 Code: Models.py class DummyPeopleModel(models.Model): person_name = models.CharField(max_length=45) def __str__(self): return self.person_name class ActiveProject(models.Model): project_name = models.CharField(max_length=30) project_abstract = models.CharField(max_length=1000) project_paper = models.CharField(max_length=1000) project_team = models.ManyToManyField(DummyPeopleModel, help_text='Team that works on this Project' ) project_join_us = models.CharField(max_length=1000) def __str__(self): return self.project_name serializers.py from rest_framework import serializers from .models import ActiveProject class ActiveProjectSerializer(serializers.ModelSerializer): class Meta: model = ActiveProject fields = ('id', 'project_name', 'project_abstract', 'project_paper', 'project_team', 'project_join_us',) def create(self, validated_data): return ActiveProject.objects.create(**validated_data) views.py class ProjectList(generics.ListAPIView): queryset = ActiveProject.objects.all() serializer_class = ActiveProjectSerializer def post(self, request): serializer = ActiveProjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ProjectDetail(generics.RetrieveUpdateDestroyAPIView): queryset = ActiveProject.objects.all() serializer_class = ActiveProjectSerializer -
celery workers unable to connect to dockerized redis instance using Django
Currently have a dockerized django application and intended on using Celery to handle a long-running task. BUT Docker-compose up fails with following error: [2018-12-17 17:25:59,710: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379//: Error -2 connecting to redis:6379. Name or service not known.. There are some similar questions concerning this on SOF but they all seem to focus on CELERY_BROKER_URL in settings.py, which I believe I have set correctly as follows CELERY_BROKER_URL = 'redis://redis:6379' CELERY_RESULT_BACKEND = 'redis://redis:6379' My docker-compose.yml : db: image: postgres:10.1-alpine restart: unless-stopped volumes: - postgres_data:/var/lib/postgresql/data/ networks: - dsne-django-nginx django: &python restart: unless-stopped build: context: . networks: - dsne-django-nginx volumes: - dsne-django-static:/usr/src/app/static - dsne-django-media:/usr/src/app/media ports: - 8000:8000 depends_on: - db - redis - celery_worker nginx: container_name: dsne-nginx restart: unless-stopped build: context: ./nginx dockerfile: nginx.dockerfile networks: - dsne-django-nginx volumes: - dsne-django-static:/usr/src/app/static - dsne-django-media:/usr/src/app/media - dsne-nginx-cert:/etc/ssl/certs:ro - /etc/ssl/:/etc/ssl/ - /usr/share/ca-certificates/:/usr/share/ca-certificates/ ports: - 80:80 - 443:443 depends_on: - django redis: image: redis:alpine celery_worker: <<: *python command: celery -A fv1 worker --loglevel=info ports: [] depends_on: - redis - db volumes: postgres_data: dsne-django-static: driver: local dsne-django-media: driver: local dsne-nginx-cert: networks: dsne-django-nginx: driver: bridge init.py : from .celery import fv1 as celery_app __all__ = ('celery_app',) celery.py : from __future__ import absolute_import, unicode_literals import os from celery … -
No display list of products django
After login we should see a list of products. But the list didn't display. models.py from django.db import models from django.urls import reverse class Product(models.Model): name = models.CharField(max_length=50, db_index=True) price = models.DecimalField(max_digits=10, decimal_places=2) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return self.name def get_absolute_urls(self): return reverse('shop:product_list') -
Getting formula while fetching data from excel sheet in python
I am using openpyxl to deal with the excelsheets on my app. I have a case where I have to manipulate row data for the number of scenarios. e.g:- =SUM(2,4) whose value is 6 for the perticular row. I want to get data from this row. But when I am using:- wb = load_workbook(filename = 'new_1.xlsx') x = wb['Sheet1'] x['A1'].value _________________ Output:- '=SUM(2,4)' But I am expecting output to be 6 not the formula of the cell. -
Deploy django with Heroku issue, ERR_CONNECTION_REFUSED
I deployed with Heroku, and I can see my template and everything. But when I register/login.. it gives me Failed to load resource: net::ERR_CONNECTION_REFUSED I believe it is a problem with wsgi.py not doing manage runserver because when I run manage runserver on my VS code, and refresh the website.. then I have connection to the database. I am stuck as to where the error is coming from. Is it gunicorn,settings.py, or something I'm missing in Procfile? wsgi.py import os import sys from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() application = DjangoWhiteNoise(application) Profile release: python manage.py migrate web: gunicorn mysite.wsgi:application --log-file - Settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = ['django-react-.herokuapp.com', '127.0.0.1'] INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'corsheaders', 'rest_auth.registration', 'rest_auth', 'rest_framework.authtoken', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'form', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = … -
Wagtail streamfield on frontend (architecture question)
I'm about to start a little side project and discovered wagtail cms. The main idea is to create a web project which is about sharing information with others. I thought i could use the wagtail streamfield on the frontend, to make it easy for all users to create content. But it appears to me that streamfields were not designed for this purpose. The alternative would be a text area with tinymce. Users would hand in submissions for review. In the wagtail backend I would convert the submitted text to streamfield input. But this would generate too much overhead. Would it be wise to use plain django for this? The site is going to rely heavily on user generated content. Maybe I'm missing something but is wagtail designed for what I intend to do? Any advice would be much appreciated. -
Displaying images as MultipleCheckBox in django
I am currently working on project in which user can select Category and Industry and based on these two condition i want to show related images, then user select some images and these images are associated with order.SampleImages model has following code. class SampleImages(models.Model): image = models.ImageField(upload_to='images/tile_images/') category = models.ManyToManyField(Category) industry = models.ManyToManyField(Industry) order_detail = models.ForeignKey(OrderDetail, on_delete=models.SET_NULL, null=True, blank=True) class Meta: verbose_name_plural = 'Sample Images' def __str__(self): return '{}'.format(self.id) Can any one suggest how to show images as multiple select checkbox? -
Replace in a string with unicode dango and python3.7
so i have this charfield in django: class Rue(models.Model): created = models.DateTimeField(null=True, blank=True, editable=False) modified = models.DateTimeField(null=True, blank=True) name = models.CharField(blank=True, null=True, max_length=200) Here is my script : print(rue.name) rue.name = rue.name.replace("Ã%Coles","Ecoles") print(rue.name) rue.save() I want to correct the error of an imported file, and clean the database. I would like to replace the "Ã%Coles" by "Ecoles". but the output is : Rue Des Ã%Coles Rue Des Ã%Coles How to clean this ? i want to replace "Ã%Coles" by "Ecoles" -
Can't connect to /home/ubuntu/env/Project/Project.sock
Am trying to host a we application using gunicorn and nginx. But I cant start the gunicorn service. everytime am getting the error message. This is the error am getting (env) root@ip-172-31-21-54:/home/env# sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2018-12-17 14:59:42 UTC; 488ms ago Process: 14160 ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - -- workers 3 --bind unix:/home/ubuntu/env/Project/Project.sock Project.wsgi:application (code=exited, status=1/FAILURE) Main PID: 14160 (code=exited, status=1/FAILURE) Dec 17 14:59:36 ip-172-31-21-54 systemd[1]: Started gunicorn daemon. Dec 17 14:59:37 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:37 +0000] [14160] [INFO] Starting gunicorn 19.9.0 Dec 17 14:59:37 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:37 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:38 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:38 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:39 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:39 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:40 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:40 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:41 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:41 +0000] [14160] [ERROR] Retrying in 1 second. Dec 17 14:59:42 ip-172-31-21-54 gunicorn[14160]: [2018-12-17 14:59:42 +0000] [14160] [ERROR] Can't connect to /home/ubuntu/env/Project/Project.sock Dec 17 14:59:42 ip-172-31-21-54 systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Dec 17 14:59:42 ip-172-31-21-54 systemd[1]: gunicorn.service: Failed … -
Redirect LoginView to user specific account/profile URL
New to Django and running into a problem. I'm trying to configure my project so that when a user logs in, they are redirected to account/profile/ + username + / . I'm assuming I'm missing something fundamental but haven't been able to nail it down yet. My appreciation in advance for any help. models.py class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return '@{}'.format(self.username) class Meta: db_table = 'users' urls.py app_name = 'accounts' urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'), path('profile/<slug:slug>/', views.Profile.as_view(), name='profile') ] views.py class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' class Profile(DetailView, LoginRequiredMixin): model = models.User slug_field = 'username' def get_context_data(self, request, **kwargs): context = super().get_context_data(**kwargs) context['username'] = request.user.username return context def get_success_url(self): return reverse_lazy('accounts:profile', kwargs={'slug': self.username}) login.html {% extends 'base.html' %} {% load bootstrap4 %} {% block bodyblock %} <div class="container"> <h1>Header Here</h1> <form class="login-form" method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Log In"> </form> </div> {%endblock%} profile.html {% extends 'base.html' %} {% block bodyblock %} <div class="container"> <h1>Welcome {{user.username}} !</h1> </div> {% endblock %} -
Laravel View Composer equivalent in Django
I'm learning django 2.1 is their any method in django which is equivalent to Laravel View::composer() method share data into specific templates. secondly how can i share data across different templates in django project which are frequently used. Note You might advise storing data in session but i'm looking for other solutions Thank You. -
Django APIView to log out of a user session
I have a Django module which is called from an SSO service. The service has a single signout function which makes a single GET request to a URL given to it during login. I'm trying to set up an APIView in Django to handle this logout. The origin service never checks the response; it only calls the GET URL once. I'm trying something like this for the APIView but keep getting session.DoesNotExist exceptions: class LogoutApi(APIView): def get(self, request, *args, **kwargs): s = Session.objects.get(session_key=kwargs.get('sk', '')) s.delete() return Response({'result': True}) I know I have a valid session but even when I try iterating through the Session.objects I can't find it. I also tried pulling the key from the SessionStore: class LogoutApi(APIView): def get(self, request, *args, **kwargs): sk = request.GET.get('sk', '') try: s = SessionStore(sk) del s[sk] return Response({'result': True}) except: self.logger.error(sys.exc_info()[0]) return Response({'result': False}) It still wasn't successful. Is there a way I can set up a GET API call to terminate a specific session? -
Django not saving immediately on new row entry?
I've got a django project set up as follows: myapp.models.py from django.db import models class BaseModel(models.Model): id = models.IntegerField(primary_key=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Source(BaseModel): name = models.CharField(max_length=32, unique=True) base_url = models.ForeignKey('URL', on_delete=models.CASCADE) class URL(BaseModel): url = models.TextField(max_length=512, unique=True) url_source = models.ForeignKey('Source', on_delete=models.CASCADE, null=True, blank=True) In a separate functions.py file, I've got the following script which is intended to populate the database with some initial known data that will be referenced by all new data. i.e. indexing unknown number and target URL links found from a number of known Source websites. functions.py # Create non-runtime db access import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MY_PROJECT.settings") import django django.setup() sources = { 'website-one': {'base_url': 'https://www.website-one.com'}, 'website-two': {'base_url': 'https://www.website-two.com'}, 'website-three': {'base_url': 'https://www.website-three.com'}, } for name, meta in sources.items(): new_url = models.URL.objects.create(url=meta['base_url']) print(new_url.id) When this runs, the print function returns None, None, None which I interpret as meaning the new URL objects haven't been saved. If I inspect the database afterward I can see that each object is successfully created and has an id field as expected. My intent is to use this: new_url = models.URL.objects.create(url=meta['base_url']) To add a reference to a new Source in the next line as such: … -
with drf-yasg, how to supply patterns?
I have installed drf-yasg, and it's working great. The problem I've got is that it's a big app, and has a huge amount of endpoints for each type of frontend client, i.e. /admin/v1, /app/v1, ... So I thought it would be a good idea to separate documentation for each type, i.e urlpatterns += [ url(r'^/admin/swagger/$', admin_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^/app/swagger/$', app_schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] So it looks as though drf-yasg supports this, via supplying patterns into the get_scheme_view: admin_schema_view = get_schema_view( openapi.Info( title="API", default_version='v1', description="The set of API endpoints used.", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@me"), license=openapi.License(name="BSD License"), ), patterns=?????, validators=['flex', 'ssv'], public=True, permission_classes=(permissions.AllowAny,), ) Now my guess was to supply a string, the same way as the first string when defining urls, such as patterns=r'^admin/v1/', which results in: File "/usr/local/lib/python3.6/dist- packages/rest_framework/compat.py", line 55, in get_original_route return urlpattern.regex.pattern AttributeError: 'str' object has no attribute 'regex' So with the documentation at drf-yasg docs: patterns – if given, only these patterns will be enumerated for inclusion in the API spec Exactly what type of object is needed here in order for to process patterns? I've tried looking around the django-rest-framework and Django source code on github, but couldn't find what type is actually needed, they are both …