Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django collectstatic does not collect media files from react npm build folder
I have a frontend react app, after using npm run build it creates build folder with: build favicon.ico index.html service-woker.js static After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work. In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" /> In my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build/static') ] STATIC_ROOT = '/var/www/web/home/static/' STATIC_URL = 'home/static/' In chrome inspect in the headers element: <link rel="icon" href="./home/favicon.ico"> How do I get it to display my web icon. Thankyou! -
How to serve Static Folder files in script tag - Django
I am creating a project where i create a files dynamically and store those file in staticfiles folder But when i am accessing this file it is showing file in browser http://localhost:8000/static/rest_framework/css/bootstrap.min.css But when i trying to access file which i have created and stored in staticfiles/bot_js http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js It is showing Page not Found I want this file to hosted on my website serve as script file for different website, like this <script src="http://localhost:8000/static/bot_js/cfe96a9a-dc84-4127-9b00-0411b7b3288e.js"></script> But it is giving me Page not found (404). How can i serve this file for different website. settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, '../frontend/build/static/'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') -
How to request a user response in the middle of a django view?
I have an html page, where a user sees information about an employee, on that page I have a query button, when I click on that button I open a modal with the information needed for the query such as Name, record, date of birth. In this modal I have a continue button, when the user clicks on that button I make an ajax request for a django view, in this view I create a Query type object, my query is performed on a page external to my code, and it follows the following steps: Consult.add_page () (basically inserts the user's data in a section). Consult.capcha () (at this point I make a post request on the page with the section data to obtain a captcha), here is my problem, I need to render the captcha on the screen, I need the user to answer it, and after that I need to continue the view flow to make a Consulta.consulta_page (). Following the commented code for better understanding obs: Consult is a class Obs2: I validate codes using Tkinter to render image for user and get response, but i cant use Tkinter in server Production, and i cant return HttpResponse … -
AllAuth allowing login from users.email and account_emailaddress tables
Allauth is allowing me to log in from email addresses in account_emailaddress.email and from user.email. How can I keep these both consistant so it only allows login from one table or another? Considering updating account_emailaddress.email in views but not sure if thats the best way to go about it. models.py class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) secondary_email = models.EmailField(max_length=254, unique=False, null=True, blank=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) settings.py ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = 'email' LOGIN_REDIRECT_URL = 'dashboard' ACCOUNT_LOGOUT_REDIRECT_URL = 'home' LOGIN_URL = 'signin' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None -
Reverse for 'editar_arvore' with arguments '('',)' not found. 1 pattern(s) tried: ['arvore/editar_arvore/(?P<id>[0-9]+)/$']
I am having this error when I try to click to edit a form already submitted, it is as if I was not passing the arvore.id in the template ver_arvore. When I change arvore.id to a number(eg. 1) I can see all my records in the database, otherwise I have the NoReverse Match error. It is as if the view ver_arvore is not saving my dictionary, as shown in the traceback My models: class Arvore(models.Model): tag = models.CharField(max_length=255) nome = models.CharField(max_length=255) nivel = models.CharField( default='Planta', max_length=50, choices=( ('Planta', 'Planta'), ('Sistema', 'Sistema'), ('Equipamento', 'Equipamento'), ('Peça', 'Peça'), ) ) criticidade = models.TextField() requisitos = models.TextField(blank=True, null=True) descricao = models.TextField(blank=True, null=True) fabricante = models.CharField(max_length=255, blank=True, null=True) modelo = models.CharField(max_length=255, blank=True, null=True) pai = models.CharField(max_length=255, blank=True, null=True) localizacao = models.CharField(max_length=250,blank=True, null=True) link_historico = models.CharField(max_length=255, blank=True, null=True) link_pm = models.CharField(max_length=255, blank=True, null=True) link_foto = models.ImageField(blank=True, null=True) def __str__(self): return self.nome class Meta: managed = True db_table = 'arvore' class FormArvore(forms.ModelForm): class Meta: model = Arvore my url: app_name = 'arvore' urlpatterns = [ path('', views.ver_arvore, name='ver_arvore'), path('cadastro_arvore/', views.cadastro_arvore, name='cadastro_arvore'), path('editar_arvore/<int:id>/', views.editar_arvore, name='editar_arvore'), path('deletar_arvore/<int:id>/', views.deletar_arvore, name='deletar_arvore'), ] My views: def cadastro_arvore(request): if request.method != 'POST': form = FormArvore return render(request, 'arvore/cadastro_arvore.html', {'form': form}) form = FormArvore(request.POST, … -
Input redirect me on the wrong view
Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough) When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help Thanks :) Templates of "create comment" : <div class="create-comment"> <h2>Write a comment</h2> <form class="site-form" action="{% url 'usercomments:create' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Create"> </form> </div> Urls.py : from django.conf.urls import url from . import views app_name = 'usercomments' urlpatterns = [ url(r'^$',views.comments_list, name="list"), url(r'^create/$', views.comments_create, name="create"), url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"), ] Views of create comment : @login_required(login_url="/userprofile/login/") def comments_create(request): if request.method == 'POST': form = forms.CreateComment(request.POST) if form.is_valid(): # save article to db instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('usercomments:list') else: form = forms.CreateComment() return render(request, 'usercomments/comments_create.html', { 'form': form }) Views of log out : def logout_view(request): if request.method == 'POST': logout(request) return redirect('/') <--- Where i get redirected when i press "create" else: pass Urls of … -
Django server is not running after added a new path function
I have created an app name 'calc' in Django and in the app, I have edited two files codes. urls.py from django.urls import path from . import views urlpattern = [ path('', views.home, name='home') ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello Django!") and finally, I have changed my directory folder's file urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ] now I am running the command on terminal: python manage.py runserver and it's giving me these below errors and not connecting to the server. terminal errors: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\shuvra\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Shuvra\Envs\docu\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File … -
Elastic Beanstalk - django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17)
Elastic Beanstalk with Python 3.6 and Amazon Linux 1. Django 3.0.7. Trying to create environment using eb create django-env, I get: Command failed on instance. Return code: 1 Output: (TRUNCATED)...backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). container_command 01_migrate in .ebextensions/02_setup.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Have read that downgrading django would solve the issue, but I need a recent django version so that it works with django channels. Any straightforward way to upgrade SQLite? -
How to give permission to some user which allow only view one instance by one time?
I always want allow to check for all users view one instance by one time. But another function like get(list)\post\patch\update\delete only for user which have got general perm for this actions. class IsCardAccess(BasePermission): def has_permission(self, request, view): has_perm = False if request.user and request.user.is_authenticated: if request.user.has_perm_extended(PERM_CARD_ACCESS): has_perm = True elif request.user.has_perm_extended(PERM_CARD_SUPER_ACCESS): has_perm = True return has_perm In this way user without PERM_CARD_ACCESS and PERM_CARD_SUPER_ACCESS can't do anything, but when PERM_CARD_ACCESS user can do all of this actions (get\post\patch\update\delete). I don't understand what I need to do. Anyone have any ideas? -
How to store Advance Python Scheduler Job on my database
I am trying to create various scheduling tasks to manage objects and store these jobs as a Django model on postgres and manage them through admin panel. Could anybody please help me. Thanks in advance. -
Django pagination not showing links to other page links
I am following a django book to learn django.I tried implementing pagination on a differnt website,it worked.But it's not working in my fyp.Each page has 3 objects as specified by me but the links to change pages are not appearing. My views.py:- from django.shortcuts import render from .models import song_thumb from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.views.generic import ListView # Create your views here. class SongListView(ListView): model=song_thumb context_object_name='artists' paginate_by=3 template_name='home.html' my template: {% block content %} <form class="" action="mediaplayer.html" method="get"> <div class="data-content"> {% for artist in artists %} <div class="container"> <div id="img-1" class="tabcontent"> <div class="blog-content"> <div class="row"> <div class="col-sm"> <div class="card" style="width: 18rem;"> <div class="img"> <img class="img-thumbnail" src="{{ artist.img.url }}" alt=""> </div> <div class="card-body"> <div class="title"> <p>{% trans 'Artist:' %} {{artist.artist}} </p><br> <p>{% trans 'Title:' %} {{artist.song_title}}</p><br> <p>{% trans 'Album:' %} {{artist.album}}</p><br> <p>{% trans 'Duration' %} {{artist.song_duration}}</p><br> </div> <audio controls> <source src='{{ artist.song.url }}' type="audio/mpeg"> Your browser does not support the audio element. </audio> </div> </div> </div> </div> </div> </div> </div> {% endfor %} </div> </form> {% include "pagination.html" with page=page_obj %} {% endblock %} my pagination.html: <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page.number }} of {{ page.paginator.num_pages … -
What's the best DRY way to repeat a class based view in Django?
I have an app that acts as a booker for the end-user; it's basically a form that calls various apis (BookerApp). It uses two main APIs but in different ways; It calls Google to get geo-location (retrieving lat-long data) to pass through the second api. The issue is I need to use this app in main WebsiteApp and its subsequent templates but with slight modification to the appearance (templates). I know I can repeat the CBV in the website app and modify the leading rendered template file; but was wondering if there was a better DRY method for this? Here is the current structure Project folder > |___ MainProject |__ settings.py |__ urls.py |__ settings.py |___ WebsiteApp |__ Templates |__ views.py <----- repeat the same CBV (found in booker) to here with DRY method |__ urls.py |__ etc.. |___ BookerApp |__ Templates |__ views.py <--- CBV held here |__ etc.. |___ Static I hope this makes sense; I know my project is all over the place and any recommendations would be welcome. In essence the app in Booker is basically a complicated form that I want to be able to use in other templates (mostly held in the WebsiteApp folder … -
Django/inlineformset: override clean method but validation error is not displayed
I try to override clean method in my inlineformset (2 fields app_app_nom and app_dro) but failed I need to test that same app_app_nom is not selected twice To test raise error in clean method (I will code logic after), I try to raise error each time form is submitted (if True: raise error) data are not registered but message error is not displayed and I am redirected...? forms.py class ApplicationInlineFormSet(BaseInlineFormSet): def clean(self): super().clean() # example custom validation across forms in the formset for form in self.forms: # your custom formset validation # app_app_nom = form.cleaned_data.get('app_app_nom') if True: raise ValidationError('You select the same app twice') else: # update the instance value. form.instance.app_app_nom = app_app_nom NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, formset=ApplicationInlineFormSet ) template.html <form id="utilisateureditform" method="POST" class="post-form"> {% csrf_token %} {{ form|crispy }} <a style="margin-right: 40px" data-target="" class="" href="{% url 'project:edit_utilisateur' %}">Nouvel utilisateur</a> <br> <br><div class="dropdown-divider"></div><br> <h2>Applications</h2><br><br> <!-- {{ application|crispy }} --> <!-- curieusement si j'enlève cette ligne le style crispy disparait --> {{ application.management_form|crispy }} <div class="row"> <div class="col-6"><p>Nom de l'application</p></div> <div class="col-5"><p>Droits</p></div> <div class="col-1"><p></p></div> </div> {% for application_form in application %} <div class="row link-formset"> {% … -
Django: how to get a javascript value from template to view?
I am currently using Django framework. I would like to get the value of a javascript value wrote in an html file. I would like to be able to display it in my view file Here is my html file from the folder templates: <script> var toto = "javascript"; document.write(toto) </script> This is my view file: def javascript(request): # print the javascript value here return render(request, "rh/javascript.html") Thank you for your help ! -
Newletter Views not sending Emails after being saved with no error showing
I have created a newsletter app to send emails to subscribers. After adding a new newsletter and setting it to be equal to published it should send the email, but instead, the newsletter is saved with no emails sent. I am sure that the email setting is correct as I am receiving an email after a successful subscription for testing. Here is the complete views.py def newsletter_signup(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): messages.warning( request, 'Your email is already exists in our database') else: instance.save() messages.success( request, 'Your email has been added in our database') subject = "Thank you for Joining our Newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_signup_email.txt") as f: signup_message = f.read() message = EmailMultiAlternatives( subject=subject, body=signup_message, from_email=from_email, to=to_email) html_template = get_template( "newsletter_signup_email.html").render() message.attach_alternative(html_template, "text/html") message.send() context = {'form': form} template = "newsletters_signup.html" return render(request, template, context) def newsletter_unsubscribe(request): form = NewsletterUserSignupForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if NewsletterUser.objects.filter(email=instance.email).exists(): NewsletterUser.objects.filter(email=instance.email).delete() messages.success( request, 'Your email has been removed from our database') subject = "You have been removed from our newsletter" from_email = settings.EMAIL_HOST_USER to_email = [instance.email] with open(settings.BASE_DIR + "/templates/newsletter_unsubscribe_email.txt") as f: signup_message = f.read() message = … -
Rq worker failed job
I am running a python Django app. It runs rq worker in background to perform additional longer tasks. Every time the call to worker is made it exits with the message Moving job to 'failed' queue (work-horse terminated unexpectedly; waitpid returned 11) The environment setup is redis==2.10.6, rq==0.12.0, python 3.6.10 My system has more than sufficient memory to run the worker thread. When I run the same worker in a docker, it works fine. ------------------------------ ------------ amqp 2.4.2 appdirs 1.4.3 appnope 0.1.0 asgi-redis 1.4.3 asgiref 1.1.2 atomicwrites 1.3.0 attrs 19.1.0 autobahn 19.3.3 Automat 0.7.0 awscli 1.18.69 Babel 2.6.0 bandwidth-sdk 3.0.3 beautifulsoup4 4.7.1 billiard 3.5.0.5 bleach 3.1.0 blis 0.4.1 boltons 19.1.0 boto3 1.9.137 botocore 1.16.19 cached-property 1.5.1 cachetools 3.1.0 catalogue 1.0.0 celery 4.2.1 certifi 2019.3.9 cffi 1.12.3 channels 1.1.8 chardet 3.0.4 Click 7.0 colorama 0.4.3 configparser 4.0.2 constantly 15.1.0 convertdate 2.2.0 croniter 0.3.30 cymem 2.0.2 Cython 0.29.14 daphne 1.4.2 dateparser 0.7.1 DateTimeRange 0.5.5 ddtrace 0.36.1 decorator 4.4.1 defusedxml 0.6.0 dill 0.2.9 dj-database-url 0.5.0 Django 1.11.27 django-appconf 1.0.3 django-axes 4.5.4 django-bower 5.2.0 django-compressor 2.2 django-cors-headers 2.5.3 django-debug-toolbar 1.11 django-extensions 2.1.6 django-htmlmin 0.11.0 django-ipware 2.1.0 django-json-response 1.1.5 django-model-utils 3.1.2 django-phonenumber-field 2.3.1 django-ratelimit 2.0.0 django-redis 4.10.0 django-rest-auth 0.9.5 django-rq 1.2.0 django-static-precompiler 1.8.2 django-test-without-migrations 0.6 … -
Synchronize local CouchDB database with remote CouchDB database when connecting to the internet
The idea is simple, I don't know how the execution is: I'm using CouchDB as an option because it was the only one I found with something like what I need. I have a local application (Python / Django) that writes to a database (CouchDB). The local database should be synchronized whenever possible with the remote database. The connection to the remote database drops a lot so it is important that this web page works locally on the user's computer. Important notes: The database does not have to be exactly CouchDB, it can be another (if there is a better one for this purpose) I am not developing a mobile application, so I will not use a PouchDB, for example. It is actually an offline, but web application, installed on the user's computer. -
psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations
What my settings.py for DB looks like: ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'fishercoder', 'USER': 'fishercoderuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } I have created a new and empty db named "fishercoder" this way: psql -U postgres create database fishercoder; ALTER USER postgres with password 'badpassword!'; CREATE USER fishercoderuser WITH PASSWORD 'password'; ALTER ROLE fishercoderuser SET client_encoding TO 'utf8'; ALTER ROLE fishercoderuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE fishercoderuser SET timezone TO 'PST8PDT'; GRANT ALL PRIVILEGES ON DATABASE fishercoder TO fishercoderuser; Then I've imported my other SQL dump into this new DB successfully by running:psql -U postgres fishercoder < fishercoder_dump.sql Then I tried to run ./manage.py makemigrations on my Django project on this EC2 instance, but got this error: Traceback (most recent call last): File "/home/ubuntu/myprojectdir/myprojectenv/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied for relation django_migrations I found these three related posts on SO: One, two and three I tried the commands they suggested: postgres=# GRANT ALL ON ALL TABLES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL SEQUENCES IN SCHEMA public to fishercoderuser; GRANT postgres=# GRANT ALL ON ALL FUNCTIONS IN SCHEMA public to fishercoderuser; … -
Is javascript date object compatible to python datetime object
For example in python, a date can be something like: 2020-06-19T11:32:16.548109Z, is there a way that i can use to convert this to a javascript Date object? -
Django... How to use different several models in one view function?
Any help??? How can I use many models in one view function? I have "get" query from the form template under Q name... like this: class UserSearchRequestView(TemplateView): model=ForQuery template_name='do_requests.html' def get_results(self): query=self.request.GET.get("q") if query: our_object=ForQuery.objects.filter(query_id__iexact=query) return our_object Now I need to pass this object through the search through three models to get results... I know, I could do something like this: def index(request): company_info = Company.objects.all() director_info = Director.objects.all() context = { 'company_info' : company_info, 'director_info' : director_info, } return render(request, 'index.html', context=context) But it is only if this function is outside of the class... But my function inside of the class already... So it doesn't work in my case... I could do like this: def get_context_data(self, **qwargs): conObject = super(DirDetailView, self).get_context_data(**qwargs) conObject['mcons'] = RequestSell.objects.all() conObject['fcons'] = DirDict.objects.all() return conObject But, then these objects are only good for using them in template? How can I bring several models into one view function, do operations with them and return the result. I'm kind of confused and probably don't see obvious? -
Django MultipleChoiceField how show only one item
I am creating a combobox with multiple choices using the MultipleChoiceField component. Everything works perfectly, but the list that appears in the combo brings repeated the item and subitem. I looked in the documentation but found nothing regarding this problem. As I understand it, the choice parameter requires bringing a tuple. The choice_test() returns [('test0', 'test0'), ('Test1', 'Test1'), ('test3', 'test3'), ...] Is there a way to show only one item? combo_test = forms.MultipleChoiceField( label=_("Combo test"), required=False, choices=choice_test(), widget= autocomplete.Select2Multiple(url='autocomplete_test') ) -
"This Field is Required" even though I am uploading my file
This is a follow up question to my last question: Lists are currently not supported in HTML Input . I have learned that Lists are simply not supported in Django-Rest-Framework browsable API, and I am trying to test my ability to POST data using Postman. The error I am getting is: "This Field is Required" for my BreedImages field even though I am posting it. Here are some pictures: Here are my models: class Breed(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BreedImage(models.Model): breed = models.ForeignKey(Breed, related_name='BreedImages', on_delete=models.CASCADE) breedImage = models.ImageField(upload_to='photos', null=True, blank=True) My Serializers: class ImageSerializer(serializers.ModelSerializer): class Meta: model = BreedImage fields = ['id', 'breedImage'] class BreedSerializer(serializers.ModelSerializer): BreedImages = ImageSerializer(many=True, allow_null=True, required=True) class Meta: model = Breed fields = ['name', 'BreedImages'] My view: class BreedList(generics.ListCreateAPIView): parser_classes = (MultiPartParser,) queryset = Breed.objects.all() serializer_class = BreedSerializer pagination_class = None -
Process Text Files with Python Dictionaries and Upload to Running Web Service lab
I want to write a Python script that will upload the feedback automatically without having to turn it into a dictionary. The script should now follow the structure: List all .txt files under /data/feedback directory that contains the actual feedback to be displayed on the company's website. Hint: Use os.listdir() method for this, which returns a list of all files and directories in the specified path. You should now have a list that contains all of the feedback files from the path /data/feedback. Traverse over each file and, from the contents of these text files, create a dictionary by keeping title, name, date, and feedback as keys for the content value, respectively. Now, you need to have a dictionary with keys and their respective values (content from feedback files). This will be uploaded through the Django REST API. Use the Python requests module to post the dictionary to the company's website. Use the request.post() method to make a POST request to http:///feedback. Replace with 35.193.233.100. Make sure an error message isn't returned. You can print the status_code and text of the response objects to check out what's going on. You can also use the response status_code 201 for created success … -
Can i serve media files on production server in Django?
Actually I created a fully functional web app using Django. I don't have much experience to host a Django web app on a production server. But I'm trying. My problem is that I read from a blog that we can't serve media files using Django. We need Amazon S3 server to serve media files to Django. I'm trying to host my Django app on digital ocean with apache server. Is there any way that I can serve media files using Django in production server. Even I don't have a huge budget to buy a space on Amazon S3. What should I do? -
How to add example in swagger field
I am currently using following libraries of django - Django==2.2.4 django-pdb==0.6.2 django-rest-swagger==2.2.0 django-service-objects==0.5.0 django-timezone-field==3.0 django-windows-tools==0.2.1 djangorestframework==3.10.2 djongo==1.2.33 It is running on Python version 3.7.4 The problem that I am facing is I can able to generate body part of API using corapi.Field in Autoschema. class SwaggerSchemaView(APIView): permission_classes = [AllowAny] renderer_classes = [ renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer ] def get(self, request): generator = SchemaGenerator() schema = generator.get_schema(request=request) return Response(schema) class ParseResume(APIView): permission_classes = [AllowAny] schema = AutoSchema( manual_fields=[ coreapi.Field( "data", required=True, location="body", description='Send Json Data', type="string", schema=coreschema.Object(), ) ] ) def post(self, request): data = request.data response_data = SetConnections.parse_resume(data) return Response(response_data) Now, I can able to generate Swagger view like as follows - enter image description here But I want to add a sample data inside this body part through coreapi.Field like as follows - { "id": "56-df-pt", "fname": "John", "lname": "Doe", "experience": { "employee": "Company X", "period": "1996 - 2002", "engaged_in": [ { "work": "Jr. Manager", "team_size": 5, "time": "Sep. 1996 - Dec. 1998" }, { "work": "Sr. Manager", "team_size": 5, "time": "Jan. 1999 - Dec. 2002" }, ] } How can I add that? I can't change any version of Django or Python at this moment now.