Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How create django model with timestamptz field
I have responce data from API it's look like this { "api": { "results": 1, "fixtures": { "65": { "fixture_id": "65", "event_timestamp": "1533927600", "event_date": "2018-08-10T19:00:00+00:00", "league_id": "2", "round": "Premier League - 1", "homeTeam_id": "33", "awayTeam_id": "46", "homeTeam": "Manchester United", "awayTeam": "Leicester", "status": "Match Finished", "statusShort": "FT", "goalsHomeTeam": "2", "goalsAwayTeam": "1", "halftime_score": "1 - 0", "final_score": "2 - 1", "penalty": null, "elapsed": "95", "firstHalfStart": "1533927660", "secondHalfStart": "1533931380" } } } } Now I am trying to build fixture model to store above data in PosgreSql database. I dont understand didnt find any example of builded model with timestamptz field. I need to store event_date key in timestamptz. Can anyone to show me how i should create this field -
Facing a Client Error when trying to Upload an image to Amazon S3 bucket from Django website
I have recently uploaded my Django website on Heroku and the media and static files are served by Amazon S3. The static files and media files are serving well and I can see them in the website. But the problem comes when I try to Upload a profile Image in profile page. It shows a Client Error: An error occurred (InvalidAccessKeyId) when calling the PutObject operation: The AWS Access Key Id you provided does not exist in our records. My amazon s3 settings: AWS_STORAGE_BUCKET_NAME = 'oryxrating' AWS_S3_CUSTOM_DOMAIN = 's3.ap-south-1.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_KEY = os.environ.get('AWS_SECRET_KEY') AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'Oryx.storage_backends.MediaStorage' I have set amazon access id and secret key in heroku configuration variables as AWS_ACCESS_KEY_ID and AWS_SECRET_KEY and they are correctly set. Please help me as I cannot understand the problem and definitely not getting a solution. Please tell where to put the Access id so that the upload works. -
Use Key-Value Lookup for Second Model in Django Template For Loop?
I'd like to figure out a way to use a key-value lookup for a second model within a Django for loop. This question on dictionary key-value loops in templates is on the right track, but I am using two normalized data models. There is a 'Parent' data object (EventDetail) that contains the relevant link and 'Child' data object (DateEvent) that has date-specific information with data on user actions. I have a template tag, link_if_exists, that is being duplicated many times. Django-debug-toolbar tells me this is being duplicated 76 times right now. This 'duplicate' message is, itself, duplicated many times. This is what I have now: app_extras.py @register.filter() def link_if_exists(title): """Return a link if it exists""" event_link = None try: event_link = EventDetail.objects.filter(title=title).values_list('link', flat=True)[0] except IndexError: pass if event_link != "": return event_link return False template.html {% load 'app_extras' %} {% for item in child_date_items %} {% if item.title|link_if_exists %} <a href="{{item.title|link_if_exists}}">{{item.title}}</a> {% endif %} {% endfor %} models.py class DateEvent(models.Model) title = models.CharField(max_length=250) event_date = models.DateField(default=date.today) event_datetime = models.DateTimeField(auto_now=False) class EventDetail(models.Model) title = models.CharField(max_length=250) link = models.URLField(max_length=200, default="", blank=True) views.py class ProblemView(TemplateView): template_name = "template.html" def get_context_data(self, **kwargs): context = super(ProblemView, self).get_context_data(**kwargs) date_today = utils.get_date_today() child_date_items = DateEvent.objects.filter(event_date=date_today) context['child_date_items'] = … -
django framework to create homepage
Installed django framework and created an app for my homepage. Added app to settings in project folder. Able to get html running however css won't style it. My html, css file is inside appfolder/templates/appfolder -
int() argument must be a string, a bytes-like object or a number, not 'ModelBase'
I'm fairly new to Django, and coding in general so this could be a conceptual oversight, but I'm running out of ideas so any help is appreciated. I'm trying to add logic to my form's clean() method which has nested try blocks. I'm trying to get object instances from different ForeignKey related models in each try block. The first two levels seem to work fine, but the third level throws the error below. I've printed the value and type for wine_get.wine_id and I get back 6 and 'int' respectively, so I'm not sure why this isn't considered a number. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/post/new/ Django Version: 2.1 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'bootstrap4', 'accounts', 'groups', 'posts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/anaconda3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/contrib/auth/mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/anaconda3/lib/python3.6/site-packages/django/views/generic/edit.py" in post 141. if form.is_valid(): File "/anaconda3/lib/python3.6/site-packages/django/forms/forms.py" in … -
two factor authentication on django
I would like to add two factor authentication to my django project. I made some research and found two libraries (django-two-factor-auth and drf-pyotp), but both of them have very little documentation, and my problem is that i really don't know how to implement the library on my already existing project. Are there other widely used libraries for this? Is there a tutorial or a example that i can use in order to understand it better, in order to implement my own version? Thanks in advance. -
How do I automatically set to_user (receiver) in my message form?
Models class Message(models.Model): sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE) reciever = models.ForeignKey(User, related_name="reciever", on_delete=models.CASCADE) title = models.CharField(max_length=50) I am pretty sure I have the right idea, and that is to first create a button: <a href="{% url 'send-message-to' profile.user.id %}" class="btn btn-primary">Send a message</a> I then pass the profile id to my CreateView and then query the user with the received pk: class MessageCreateView(CreateView): model = Message fields = ['title', 'msg_content'] def form_valid(self, form): form.instance.sender = self.request.user form.instance.receiver = User.objects.get(id=self.kwargs.get('pk')) return super().form_valid(form) But it is not working as intended. I am receiving the error IntegrityError at /messages/create/1/ null value in column "reciever_id" violates not-null constraint For some reason the code I have written is not filling in the receiver id. form.instance.receiver = User.objects.get(id=self.kwargs.get('pk')) How can I get my form to automatically set the reciever (to_user) in my form? What is happening right now is that when I try to create a message I get a dropdown of all the users available which is not desired. -
How to deal with OneToOneField admin/forms
I'm struggling to design relations between models. I'm working on a base for a big project so I'm want things to be as universal as they can. There will be more models with addresses. For example auth.User, Client, Property so I decided to create an addresses app with Address model. The same thing with contacts.ContactInformation. It's much more intuitive and modular to do this: class Client(..): address = OneToOneField('addresses.Address',on_delete=PROTECT... contact_information = OneToOneField('contacts.ContactInformation'...) Than this: class Address(..): client = OneToOneField('clients.Client',on_delete=CASCADE) Problems with 1. I can't use many built-in behaviors like admin inlines, on_delete=CASCADE etc. Address is mandatory. Problems with 2. As I mentioned, is much less intuitive for new developers and theoretically, I can't be sure that every address has either Client, User or Property. And you can't see immediately that Client has Address. So now I'm considering multiple approaches. 1. The first one is to use add_to_class so I can put all logic to one app (for example clients for Client: class Client... .... Address.add_to_class('client',OneToOneField('clients.Client',on_delete=CASCADE... I could use admin inlines, forms and everybody can clearly see that Client has Address. 2. I could create multiple Address models like ClientAddress, UserAddress which uses abstract model AbstractAddress. Do you have arguments which … -
What Is The Concept Behind Django ORM
In Django When We Are Writing - User.objects.all() It Gives Us All The Data From Model User Which is Actally SELECT * FROM user; In SQL Query. How Django Is Converting Or Translating This Object to SQL Code. I Wants to Know The Concept Behind This. -
Possible Unhandled Promise Rejection: Error: Authentication failed vue-authenticate django-rest-auth
I'm using vue-authenticate for social login for google. I followed the basic setup as stated in the vue-authenticate gituhub readme. Below is the code for my vue file <template> <button @click="authenticate('google')">auth Google</button> </template> <script> export default { name: 'app', methods: { authenticate: function (provider) { this.$auth.authenticate(provider).then(function () { }) } } } </script> My js file where I define the provider is as follows import Vue from 'vue' import App from './App.vue' import VueAxios from 'vue-axios' import VueAuthenticate from 'vue-authenticate' import axios from 'axios'; Vue.use(VueAxios, axios) Vue.use(VueAuthenticate, { baseUrl: 'http://localhost:8000', // Your API domain storageType: 'localStorage', tokenName: 'token', providers: { google: { clientId: 'client_id_key', redirectUri: 'http://localhost:8080/', url: 'http://localhost:8000/rest-auth/google/', } } }) new Vue({ el: '#app', render: h => h(App), }) My view on the backend for the google authentications is as follows class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = 'http://localhost:8080/' client_class = OAuth2Client Now, When I click on the button on the frontend, a window pops up, all the entries in my database are created as expected and the user is made as I want on the backend side. However, on the frontend, I get the error on the console: Possible Unhandled Promise Rejection: Error: Authentication failed at eval (vue-authenticate.es2015.js?5ab3:1380) … -
Django: How to override verbose_name and help_text of model fields
I need some morre input/opinion on the following matter: I want to overwrite the verbose_name and help_text for all fields of certain django models. I already have a structure where these values are stored into the database. Fields are iterated through: Contract._meta.get_fields() The I use a formset with initial/default values for this fields. This is working nicely so far. My problem now is that I want to keep the default values within the value and want to override this everywhere the values are accessed (admin-forms, form, templates etc.). I think something like a Mixin although I thing then I would have to change too much of the django-code. Other possibility which already worked is to call a function instead of verbose_name and help_text e.g. title = models.CharField(max_length=120, blank=True, null=True, verbose_name=get_vname('title') help_text=get_help_text('title')) title_long = models.CharField(max_length=120, blank=True, null=True, verbose_name=get_vname('title_long') help_text=get_help_text('title_long')) But thats too much manual changes and I need to store the defaults as well. Is there a better way (DRY) to achieve this? Maybe there is an extension? -
DRF UpdateAPI View returns "detail": "Not found."
When making PUT or PATCH to my DRF endpoint I get a 404 "detail": "Not found." response. I'm not sure what is causing the error, my view or serializer. The documentation on DRF is a little lacking and there is no working example of a UpdateAPIView for me to reference. Code: urls.py path('api/update/job/<int:pk>/', views.UpdateJobView.as_view() ), serializers.py class JobsUpdateSerializer(serializers.ModelSerializer): designer_one = serializers.PrimaryKeyRelatedField(many=False, queryset=UserProfile.objects.all()) designer_two = serializers.PrimaryKeyRelatedField(many=False, queryset=UserProfile.objects.all()) class Meta: model = Job fields = '__all__' views.py class UpdateJobView(generics.UpdateAPIView): serializer_class = JobsUpdateSerializer lookup_field = "pk" def get_queryset(self): queryset = Job.objects.all() jobID = self.request.query_params.get('pk', None) if jobID is not None: queryset = queryset.filter(id=jobID) else: return False Do I need to modify my view to contain the get_object function? Django==2.1.3 djangorestframework==3.9.0 -
Cannot install Python GDAL on Mac OSC High Sierra
completely stuck on this one. trying to run Django (django==1.11.9) in a Python 3.6.3 virtualenv with PostGIS. HighSierra 10.13.6. Originally I installed postgres, postgis, and gdal2 via homebrew. when I run make, the build signals: CPLUS_INCLUDE_PATH=/usr/include/gdal \ C_INCLUDE_PATH=/usr/include/gdal \ pip install GDAL==$(gdal-config --version | cut -f-2 -d'.') Collecting GDAL==2.2 Installing collected packages: GDAL Found existing installation: GDAL 2.4.0 Uninstalling GDAL-2.4.0: Successfully uninstalled GDAL-2.4.0 Successfully installed GDAL-2.2.0 python manage.py migrate ... File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/base.py", line 6, in <module> from .features import DatabaseFeatures File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/backends/postgis/features.py", line 1, in <module> from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/backends/base/features.py", line 4, in <module> from django.contrib.gis.db.models import aggregates File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/models/__init__.py", line 3, in <module> from django.contrib.gis.db.models.aggregates import * # NOQA File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/models/aggregates.py", line 1, in <module> from django.contrib.gis.db.models.fields import ExtentField File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/db/models/fields.py", line 3, in <module> from django.contrib.gis import forms, gdal File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/forms/__init__.py", line 3, in <module> from .fields import ( # NOQA File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/forms/fields.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/geos/__init__.py", line 5, in <module> from .collections import ( # NOQA File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/geos/collections.py", line 11, in <module> from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin File "/Users/me/.pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/geos/geometry.py", line 11, in <module> from django.contrib.gis import gdal File … -
Django: Media image isn't loading and a 'static/' is getting included in the path from nowhere
I have a Account model: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField (upload_to ='media/images/profile-photos', verbose_name="Upload a profile picture") ... I am keeping media images in media folder and static files in static folder. But at first I was placing uploaded images in static/images/profile-photos. Later I updated the path and moved every media images to media/images/profile-photos. My settings.py file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py is: ... from django.conf import settings from django.conf.urls.static import static urlpatterns = [ ... ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I can see the images when I'm writing the paths like this: http://127.0.0.1:8000/media/images/profile-photos/SoloCharacter.jpg. But when I try to visit through the pages, the images are not coming and I'm getting this in the command line: "GET /media/static/images/profile-photos/SoloCharacter.jpg HTTP/1.1" 404 1885. Could it be the problem that from somewhere, i guess, the static/ word is getting included in the path (i.e., "GET /media/static/images/profile-photos/...")? This is my template: {% block contains %} {% load static %} {% for c in ca %} <p><strong>{{ c.car_no }}</strong>--<em>{{ c.car_model }}</em>--{{ c.garage }}</p> <img src="{{ c.car_model.photo.url }}" height="200" /> <form action="{%url 'booking' c.id c.garage.id %}" … -
Azure hosting from Pycharm
I want to try and push my django app to Azure, has anyone done this? I am using MySQL for the database but can only find POSTGRESQL as a WebApp. Does anyone have any suggestions?? -
Uploading a CSV file with foreign key into Django
I have uploaded two datasets (without foreign keys based on Service and Library models see below), but cannot upload the third which has foreign keys for the two other datasets. First, I'm uploading them in the shell, by running this code in "python manage.py shell". My foreign key columns are service and library and connecting to service via 'cpt' and library via 'hid'. from catalog.models import Service, Library, Price # not including the intro - price dataset gets pulled in with open('price.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: p = Price(com_desc=row['com_desc'],service=Service.objects.get(row['cpt']),price_offer=row['price_offer'], comments=row['comments'], library=Library.objects.get['hid']) p.save() Here is the error that I get: /projects/hosproject/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1161, in build_filter arg, value = filter_expr ValueError: too many values to unpack (expected 2) Here are my models: Service, Library and Price. As I said before, Service and Library are already uploaded, but struggling to upload Price because of the foreign keys. # Service Model class Service(models.Model): serviceid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID for this particular service in database') desc_us = models.TextField(blank=True, primary_key = True) cpt = models.IntegerField(default= 10000) price_std = models.DecimalField(max_digits=6, decimal_places=2, blank=True) # Library Model class Library(models.Model): hid = models.CharField(max_length = 8, null=True) name = models.CharField(max_length=200, primary_key=True) hopid = models.UUIDField(default=uuid.uuid4, help_text='Unique ID … -
Django: aggregate returns a wrong result after using annotate
When aggregating a queryset, I noticed that if I use an annotation before, I get a wrong result. I can't understand why. The Code from django.db.models import QuerySet, Max, F, ExpressionWrapper, DecimalField, Sum from orders.models import OrderOperation class OrderOperationQuerySet(QuerySet): def last_only(self) -> QuerySet: return self \ .annotate(last_oo_pk=Max('order__orderoperation__pk')) \ .filter(pk=F('last_oo_pk')) @staticmethod def _hist_price(orderable_field): return ExpressionWrapper( F(f'{orderable_field}__hist_unit_price') * F(f'{orderable_field}__quantity'), output_field=DecimalField()) def ordered_articles_data(self): return self.aggregate( sum_ordered_articles_amounts=Sum(self._hist_price('orderedarticle'))) The Test qs1 = OrderOperation.objects.filter(order__pk=31655) qs2 = OrderOperation.objects.filter(order__pk=31655).last_only() assert qs1.count() == qs2.count() == 1 and qs1[0] == qs2[0] # shows that both querysets contains the same object qs1.ordered_articles_data() > {'sum_ordered_articles_amounts': Decimal('3.72')} # expected result qs2.ordered_articles_data() > {'sum_ordered_articles_amounts': Decimal('3.01')} # wrong result How is it possible that this last_only annotation method can make the aggregation result different (and wrong)? -
Intermediary model in django
I want to join Post and Category with an intermediary table called PostaCat as follow: Class Post(models.Model): Name=models.CharField(max_length=50) Class Category(models.Model): Name=models.CharField(max_length=50) post=models.ManyToMany(Post) Class PostCat(models.Model): post=models.ForeignKey(Post,on_delete=models.CASCADE) category=models.ForeignKey(Category,on_delete=models.CASCADE) But it gives me error. What is wrong with this piece of code? Can you correct it? -
Local time for report generation
I am working on a device that will be measuring certain data and creating pdf's based on this data. The device is running a Windows IOT core front end and django on the back end on a separate device. The two communicate using an api from the django server. The problem that I am currently generating the reports on the backend and sending them to the front end, and when i am taking the date when the data is collected to create the report it is always in UTC, which is expected. We need to be able to generate these reports in the users current timezone. The user can set the timezone of Windows IOT through a built in endpoint on the administration portal. The problem for the back end is that it is only accessible from the IOT interface so we need some way to set the timezone using the set timezone on the front end or at least pass the timezone to the function that is creating the report so we can convert the UTC datetime stamp to whatever the user has set. The big problem is that what is available for the Windows IOT is there are … -
DoesNotExist: Group matching query does not exist
I am trying to get the details of authors with the id of the author using a librarians group.i have also included it in settings.py file and set up the group in postgresql db.Buy some group matching query does not exist is showing up while i am running the server. directory structure: untitled2 librarymanage library decorators __init__.py group_required.py migrations static css js templatetags __init__.py has_group.py xextends.py __init__.py admin.py apps.py forms.py models.py tables.py tests.py urls.py validators.py views.py librarymanage __init__.py settings.py urls.py wsgi.py templates authors.html authors_show.html base.html books.html change_password.html periods.html periods_show.html publisher_show.html publishers.html sign_in.html sign_up.html table_without_footer.html db.sqlite3 manage.py venv views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.hashers import check_password from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from django.contrib.auth.models import User from .forms import * from .models import Book, LendPeriods, Author, Publisher, UserProfile from .tables import BookTable, BookTableUser, AuthorTable, PublisherTable, PeriodsTable from django_tables2 import RequestConfig from django.contrib import messages from django.utils import timezone from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .decorators.group_required import group_required from django.db.models.base import ObjectDoesNotExist from .templatetags import has_group from django.http import HttpResponse @login_required(login_url='/sign_in/') def authors_show(request, author_id): try: author = Author.objects.get(id=author_id) except ObjectDoesNotExist: messages.error(request, "This author does not exist") return redirect('/') if author: books_qs = Book.objects.filter(author=author_id) books_table = … -
How can I use signed urls in my template with DRF?
I'm using vue as a frontend framework. Users are able to CRUD images. The images are restricted to a group of users. Therefore security of the images is required. CloudFront is used to get images from an AWS S3 bucket. I am thinking of using signed urls for this. I've found a script how to generate signed urls here. How can I convert the image urls to signed urls with this script? I tried extending the serializer I wrote for the Image like this: Serializer: class ImageBlockSerializer(SubContentBlockSerializerMixin, serializers.ModelSerializer): image = HyperlinkedSorlImageField(geometry_string=settings.THUMBNAIL_ALIASES['image-large']['size'], source='signed_url') caption = serializers.CharField(required=False) def has_files(self): return ['image'] def has_fields(self): return ['caption'] def create(self, validated_data): instance = super().create(validated_data) instance.signed_image = generate_signed_url(instance.image) instance.save() return instance Model: class ImageContentBlock(SubContentBlock): image = models.ImageField(verbose_name=_('Image'), upload_to=site_directory_path) caption = models.CharField(verbose_name=_('Caption'), max_length=255, blank=True) signed_image = models.CharField(verbose_name=_('Signed url'), max_length=1000, blank=True, null=True) def has_files(self): return ['image'] def to_dict(post_request=None): if post_request: return {'image': post_request['image'], 'caption': post_request['caption']} else: return {'image': "", 'caption': ""} class Meta: abstract = True Or am I thinking in the wrong direction on securing images using signed urls? -
Rendering PK instead of username in CreateView
I am building an app where managers can create a private webpage, they need to add people manually in order for them to access the page. I don't want the managers to see all of the users, So I would like to render only the PK in the list. My views.py class HotelCreateView(LoginRequiredMixin, CreateView): model = Hotel fields = ['code','hotel','colleague'] Thanks -
Can do longer load packages django
Historically, I was able to easily install packages on my app, but after installing Heroku and whitenoise, soemthing broke. I tried to rebuild the app, virtualvenv from scratch, according to best conventions, but nothing fixes it. Now, any package I try to install I get this error. The packages successfully install, but when I try to run the application, I get a the following error: return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'settings' This seems to be a common problem discuss in a lot of groups, but I have not found any solutions. I've been working on this all day. Please help. New to django. https://groups.google.com/forum/#!topic/django-users/0tAtr4NBJ_4 http://www.techlighting.info/django-channels-tutorial-1-creating-a-chat-application/ I think that my project is not connecting to the packages correctly. Here is my file relationship. This is where the project is: Documents > Projects > hosproject > catalog, manage.py, hosproject2, venv This is where the packages are Documents > trydjango > … -
how to add google login to react and django api which already has a auth with jwt
how to authenticate users using google sign in with react in front end and Django in back end. I already authenticated using token based. -
pass url parameter to serializer
Suppose my url be, POST : /api/v1/my-app/my-model/?myVariable=foo How can I pass the myVariable to the serializer? # serializer.py class MySerializer(serializers.ModelSerializer): class Meta: fields = '__all__' model = MyModel def custom_validator(self): # how can i get the "myVariable" value here? pass def validate(self, attrs): attrs = super().validate(attrs) self.custom_validator() return attrs # views.py class MyViewset(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer