Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'post_comment' with keyword arguments '{'kwargs': {'pk': 1}}' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9]+)/\\Z']
I have this comment section that allows users to comment, but the problem I have is that I want users to stay on the same page after commenting. And that is giving me a headache about how to go about it. I wanted to redirect using 'post-detail," but because I have a slug in there, it doesn't work. The second option is to use "post_comment," and this is the error I'm getting. I need to redirect either by using post-detail or post_comment. views.py class PostDetailView(DetailView): """ show the detail of a specific post """ model = Post template_name = 'blog/post_detail.html' slug_field = 'slug' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['author'] = lowercase_first_name(self.object.author) context['tags'] = self.object.tags.all() # context['comments'] = self.object.comment.all() context['comments'] = Comment.objects.filter(blog=self.object) context['pk'] = self.kwargs.get('pk') return context def post_comment(request, pk): blog = Post.objects.get(pk=pk) comment = Comment( user_comment=request.user, comment =request.POST['comment'], blog=blog) comment.save() return redirect('post_comment', kwargs={'pk': pk}) urls.py urlpatterns = [ path('', views.post_list, name='home'), path('<author_slug>/<slug:slug>/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/', views.post_comment, name='post_comment'), ] -
how to condition use with field in django using python
Why does it not ap class opportunity(models.Model): lead_id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) TYPE_CHOICES = [ ('...', '...'), ('Individual', 'Individual'), ('Company', 'Company'), ] type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='...') if type == 'Individual': name = models.CharField(max_length=200) elif type == 'Company': Company = models.CharField(max_length=200) pear field based on the selection? nothing showed up Is the condition correct? -
Static files such as videos and images take time to load in production
The video and images loaded faster when I opened the website in the local server. After hosting it, the video in the homepage takes time to load and the images retrieved from the database also take time to load. I have used AWS light sail to host the website on the internet. Please let me know what I can do to load the video and images faster when the user opens the website. I have followed the steps to load the static files in django, but the load time is very slow. -
Django with SQLAlchemy
can someone tell me why i am getting this error when importing my models in django? django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. i dont know what to register in my installed_apps section. i created a new project and registered it like this INSTALLED_APPS = [ 'smashbook.apps.SmashbookConfig', ... ] i import my models like this: from models import players i have a python file "mockdata.py" which i want to use to fill my postgresql database with data using sqlalchemy. can anyone help me? Thanks in advance! -
How to make your own pagination Django
I have some json data from 3rd party API which has params like 3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber1 NumberOfItemsOnPage - how many items will be on one page and PageNumber - current page. This json has items, info about current page, how many items on page and how many pages in general And i want to know how can i paginate trough that json using paginate_by in class ListView class myView(ListView) paginate_by = 5 def get_queryset(self, ...): queryset = [] page_number = self.request.GET.get('page') request = f'3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber{page_number}' <- this might be wrong but i doesnt rly care bcs i need to know how to paginate using default django pagination queryset = request.json() return queryset I guess i need to override django Paginator class but i dont know how to do that bcs django paginator paginates will trough only first page and wont get anothers -
How to set codemirror to highlight multiple languages in Django admin?
For one of my pet projects, I needed to use syntax highlighting for one of the TextField fields. Codemirror is great for this. After trying several “django-batteries” with widgets, I decided to abandon external dependencies and install codemirror myself. Models have TbTemplate with fields for describing templates. From there, the backend takes templates for rendering, and the TextField itself with the template is szJinjaCode. I do it like this. admin.py: class TemplateAdminForm(forms.ModelForm): class Meta: model = TbTemplate fields = "__all__" widgets = { 'szJinjaCode': forms.Textarea(attrs={'class': 'jinja2-editor'}) } # Template admin @admin.register(TbTemplate) class AdminTemplate(admin.ModelAdmin): class Media: # set for codemirror ON css = { 'all': ( # '/static/codemirror-5.65.13/doc/docs.css', '/static/codemirror-5.65.13/lib/codemirror.css', '/static/codemirror-5.65.13/addon/hint/show-hint.css', '/static/codemirror-5.65.13/addon/lint/lint.css', '/static/codemirror-5.65.13/theme/rubyblue.css', ) } js = ( '/static/codemirror-5.65.13/lib/codemirror.js', '/static/codemirror-5.65.13/addon/hint/show-hint.js', '/static/codemirror-5.65.13/addon/hint/xml-hint.js', '/static/codemirror-5.65.13/addon/hint/html-hint.js', '/static/codemirror-5.65.13/mode/xml/xml.js', '/static/codemirror-5.65.13/mode/javascript/javascript.js', '/static/codemirror-5.65.13/mode/css/css.js', '/static/codemirror-5.65.13/mode/htmlmixed/htmlmixed.js', '/static/codemirror-5.65.13/mode/jinja2/jinja2.js', # '/static/codemirror-5.65.13/addon/runmode/colorize.js', # '/static/codemirror-5.65.13/addon/hint/html-hint.js', # '/static/codemirror-5.65.13/addon/lint/lint.js', # '/static/codemirror-5.65.13/addon/lint/html-lint.js', '/static/js/codemirror/init_jinja2.js' ) # set form TemplateAdminForm form = TemplateAdminForm # other description for admin TbTemplate # ... # ... As you can see from the code, you also need to run the initialization file /static/js/codemirror/init_jinja2.js into statics-files. Actually, he took from the recipe and changed it a little: /static/js/codemirror/init_jinja2.js (function(){ var $ = django.jQuery; $(document).ready(function(){ $('.jinja2-editor').each(function(idx, el){ function getSelectedRange() { return { from: editor.getCursor(true), to: editor.getCursor(false) }; … -
Want to create folder in Django...the user wants to create subfolders
`In my Django Application....I want to create an directory in that directory I want to create an subdirectory in that particular subdirectory I want to create another subdirectory like that the user how long wants like that they want to create an directory Example Code in Django` -
Why does Heroku search inside '/app/static' and not in the folder 'static'?
Context I'm deploying a project through Heroku and I get the following warning: ?: (staticfiles.W004) The directory '/app/static' in the STATICFILES_DIRS setting does not exist. This happens I run the command heroku run python manage.py migrate . Note: I don't get this warning when I try to migrate locally. Only while deploying, which I can actually do. Question I don't understand why Heroku is searching under '/app/static' when I specify in the settings.py file STATICFILESDIRS = [BASE_DIR / "static"]. Code My 'django/settings.py' file looks like this: # django_project/settings.py INSTALLED_APPS = [ ... "whitenoise.runserver_nostatic", "django.contrib.staticfiles", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "static"] STATIC_ROOT = BASE_DIR / "staticfiles" This is my file tree. ├── .env ├── .gitignore ├── .venv ├── accounts │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── django_project │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── Procfile ├── requirements.txt ├── runtime.txt ├── static │ ├── css │ └── js ├── staticfiles │ └── admin │ … -
Calling .env variables in a JS script in a Django template
I have my following credentials stored in a .env file: #Google Drive API GOOGLE_DRIVE_API_KEY='XX' GOOGLE_DRIVE_API_CLIENT_ID='XX.apps.googleusercontent.com' GOOGLE_DRIVE_APP_ID='XX' In my Django template, I would like to call these variables to initiate the Google Drive File Picker: <script> var API_KEY = 'xx'; var CLIENT_ID = 'xx.apps.googleusercontent.com'; var APP_ID = 'xx'; // Scope to use to access user's Drive items. var SCOPES = 'https://www.googleapis.com/auth/drive'; </script> Since it's absolutely not secure to put these credentials directly inside the JS script, do you know how I can call these credentials (like os.getenv() in Python)? -
How to filter one model by another if it doesnt have relation
I have 2 models and model ObjectList has m2m field to CounterParty but i need to show info from CounterParty model filtered by object How am i suppose to do it? class CounterParty(models.Model): name = models.CharField(max_length=150, verbose_name='Наименование') class ObjectList(models.Model): name = models.CharField(max_length=250, verbose_name='Наименование') contractor_guid = models.ManyToManyField(CounterParty, related_name='object_contractor',default=None, blank=True) I know this is not right but it should look like this object = ObjectList.objects.get(id=1) a = CounterParty.objects.filter(object_contractor=object) -
Websocket issue in Python Django
The console shows that the websocket is connected in the inbox, but the real-time notification is not received import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import ChatRoom, Message, Notification from django.contrib.auth import get_user_model from asgiref.sync import async_to_sync from channels.layers import get_channel_layer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] formatted_timestamp = await self.save_message(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender': self.scope['user'].username, 'formatted_timestamp': formatted_timestamp, } ) async def chat_message(self, event): message = event['message'] sender = event['sender'] formatted_timestamp = event['formatted_timestamp'] await self.send(text_data=json.dumps({ 'message': message, 'sender': sender, 'formatted_timestamp': formatted_timestamp, })) @database_sync_to_async def save_message(self, message): chat_room = ChatRoom.objects.get(name=self.room_name) sender = self.scope['user'] new_message = Message(chat_room=chat_room, sender=sender, content=message) new_message.save() formatted_timestamp = new_message.formatted_timestamp() participants = chat_room.participants.exclude(id=sender.id) for participant in participants: notification = Notification(user=participant, chat_room=chat_room, message=new_message) notification.save() return formatted_timestamp @database_sync_to_async def get_or_create_room(self, user_ids): users = get_user_model().objects.filter(id__in=user_ids) chat_room = ChatRoom.get_or_create_chat_room(users) return chat_room class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): print("NotificationConsumer Connected") print('connected') print(self.scope['user'].username) self.room_group_name = '%s_notifications' % self.scope['user'].username print(self.room_group_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, … -
Unable to change password in Django with custom user model
I have been trying to get the default Django authentication system to work with custom users. I am able to create the user types, login and logout. However, when it comes to changing the password, I get logged out and then the password is not changed. I also tried to see if by resetting the password through email anything would change, yet I still can't change the password. My app name is account. This is my custom user model, I tried adding the set_password method to make sure it could change the password. I have removed the managers for readability : class CustomUser(AbstractUser): username = None email = models.EmailField(_("email address"), unique=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def set_password(self, raw_password): self.password = make_password(raw_password) self._password = raw_password class Student(CustomUser): student = StudentManager() class Meta: proxy = True class Teacher(CustomUser): teacher = TeacherManager() class Meta: proxy = True For the rest I use all the default Django authentication urls and views but i have tried modifying the password change view to make sure I don't log out, however the issue persists : urlpatterns = [ path('password_change/', CustomPasswordChangeView.as_view(), name='password_change') path('', include('django.contrib.auth.urls')), ] CustomPasswordChangeView : class CustomPasswordChangeView(auth.views.PasswordChangeView): template_name = "registration/password_change_form.html" success_url … -
There are 34 other sessions using the database
I normally run tests like this: python manage.py test --keepdb path.to.MyTestCase This command is stuck, does nothing so I decided to run without --keepdb, I get the following error: Destroying old test database for alias 'default'...Got an error recreating the test database: database "test_myproject" is being accessed by other users DETAIL: There are 34 other sessions using the database. My assumption, my previous 34 test commands hang on the command line. What can I do at this point? -
Django models.CASCADE does not delete ForeignKey object
I'm trying to figure out why my Files objects are not getting deleted if I delete a Artist object. All models seemd to be related correctly class Artist(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(verbose_name="Artist Title", blank=True, null=True, editable=False, unique=True, max_length=255) class Playlists(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) class Files(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) playlists = models.ForeignKey(Playlists, on_delete=models.CASCADE, verbose_name="Playlist", blank=True, null=True, db_index=True) backend = models.ForeignKey(Backend, on_delete=models.CASCADE, related_name='bafiles_relation', db_index=True) class MusicAlbums(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='music_artist_relation', db_index=True) album_artist = models.ManyToManyField(through='AlbumArtist', to='Artist', db_index=True) backend = models.ForeignKey(Backend, on_delete=models.CASCADE, related_name='backend_music_album_relation', db_index=True) genre_relation = models.ManyToManyField(through='GenreMusicAlbum', to='Genre', db_index=True) class AlbumArtist(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE, blank=False, null=False, db_index=True, related_name='album_artist_relations') album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, blank=False, null=False, db_index=True) class Genre(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(verbose_name="Genre", blank=True, null=True, editable=False, unique=True, max_length=255) class GenreMusicAlbum(models.Model): objects = RandomManager() music_album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, blank=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, blank=False, null=False) class MusicTracks(models.Model): objects = RandomManager() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) file = models.ForeignKey(Files, on_delete=models.CASCADE, related_name='music_track_file_relation', db_index=True) artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='music_track_artist_relation', db_index=True) album = models.ForeignKey(MusicAlbums, on_delete=models.CASCADE, related_name='music_track_album_relation', db_index=True) class Backend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, … -
Module of side-script, which is imported in django views.py can not find weights file with tensorflow's load_weights func
I have a django application, which contains activation an imported side-script from another project, when it gets an image file in POST-request. Side-script calls another script, which uses tensorflow function load_weights to load pre-trained weights and apply a super-resolution trained model to image, then i expect to return enchanced version of it in views.py and transfer back to html page in response. The problem, however, is that for some reason module of side-script can not find weights file (no such file or directory error), while if i run it directly (not calling from django project) it finds it perfectly fine. Does anyone have a solution? Error text: Unable to open file (unable to open file: name = 'weights/edsr-16-x4/weights.h5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0) Python version 3.7 tensorflow version 2.3.1 Django version 3.2.19 I have tried to move weights file to script's folder so it wouldn't be necessary to give it full path anymore, just a file name, but it did not work, so i can not figure any solution for now. P.S. couldn't figure out how to put multiple code blocks, so i put all three files in … -
how to add my function to values parameters?
I have a function 'is_recently' that checks how long the item I added has been hanging, and if 30 minutes have not passed yet, then write that it is recently on sale. I decided to optimize queries in the database, and I cannot add this function to the parameters of the values function, is it possible to do this at all? Forgive me in advance if I wrote with errors, I'm not English speaking. def index(request): data = ( Product .objects.select_related('category') .filter(is_on_main=True) .values('name','price','pk','date') ) Maybe there are some other functions? Or I don't understand something -
How to improve Django's collectstatic command performance in Docker?
I'm working on a Django project that's containerized using Docker, and I've noticed that the collectstatic command has very poor performance during the Docker image build process. The collectstatic command in Django works by comparing the timestamps of files from the source and destination. Based on this comparison, it determines whether a file should be copied, deleted and copied, or skipped. This behavior significantly affects the performance of the collectstatic command. I realized that the issue was due to the timestamps of my static files not being preserved during the Docker build process, causing collectstatic to perform unnecessary operations. Is there a way to preserve the original timestamps of my static files when building a Docker image for a Django application, and thereby improve the performance of the collectstatic command? -
How to web scrape an svg of site(Hackerrank) using Django [closed]
I want to scrape and display or store svg of the hackerrank website. Hackerrank robots.txt: User-agent: * Disallow: /x/tests/ Disallow: /x/interviews/ Disallow: /x/settings/ Disallow: /*download_solution$ Disallow: /tests/ Disallow: /work/embedview/ User-agent: AhrefsBot Disallow: / User-agent: MauiBot Disallow: / User-agent: ia_archiver Disallow: / User-agent: DuckDuckBot Crawl-Delay: 3 User-agent: Bingbot Crawl-Delay: 3 User-agent: YandexBot Crawl-Delay: 3 User-agent: MJ12Bot Crawl-Delay: 3 Sitemap: https://cdn.hackerrank.com/s3_pub/hr-assets/sitemaps/sitemap.xml.gz I tried using beautifulsoup but it only extracts the svgs tags and not the styles or the resources. I am willing to use other scraping software -
in my code send_bulkledger call many time ,but i called it only once
if main1['res']['message']['module']=='bulk_ledger_save': ledger_list=await self.save_bulk_ledger(main1) # returns a list print('6000') msgdict= {"msg":"bulk_legder_return","ledger_list": ledger_list} await self.channel_layer.group_send( self.room_group_name, { "type":"send_bulkledger", 'msg':msgdict }) async def send_bulkledger(self, event): print(event,'7000') data=event['msg'] await self.send(text_data=json.dumps({ "msg":data })) This code belongs to Django Channels While running above code 6000 is printing only once but 7000 is printing multiple times because of this getting data in frontend many times -
[GSI_LOGGER]: The given origin is not allowed for the given client ID. && Failed to load resource: the server responded with a status of 400
[GSI_LOGGER]: The given origin is not allowed for the given client ID. I have added "javascript_origins": [ "http://localhost", "http://localhost:8000" ] I don't uderstand Why am i gettingthis The given origin is not allowed for the given client ID. <script src="https://accounts.google.com/gsi/client" async defer></script> {% load static %} <script type="text/javascript" src="{% static '/js/app.js' %}"></script> <h1>My Awesome App</h1> <div id="g_id_onload" data-client_id="873307876888-9ht3ph1vm7l62ugtmos36fddrrm6bj5n.apps.googleusercontent.com" data-context="signin" data-ux_mode="popup" data-callback="handleLogin" data-auto_select="true" data-itp_support="true"> </div> <div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signin_with" data-size="large" data-logo_alignment="left"> </div> -
Custom field in django-filter causes an error
I have django-filter and i want to add new custom field in my model filter but it causes an error Cannot resolve keyword 'category_choice' into field. When i deleted self.filters.extra everything okay but i dont know how to fix that bcs i need to add choice in init def qsCategory(request): object = request.GET.get('open_point_object') if object: return OpenPointList.objects.filter(open_point_object_id=object).values_list('category', flat=True).distinct() return OpenPointList.objects.values_list('category', flat=True).distinct() class OpenPointFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.data.get('category_choice'): self.data._mutable = True category_choice = request.GET['category_choice'] if category_choice: self.data['category'] = self.data.get('category_choice') self.data._mutable = False self.filters['category_choice'].extra['choices'] = [ (category, category) for category in qsCategory(self.request) ] status = django_filters.ChoiceFilter(choices=CHOICES) category = django_filters.CharFilter(method='custom_category_filter') category_choice = django_filters.ChoiceFilter(label='Категория') class Meta: model = OpenPointList fields = ( 'open_point_object', 'status', 'category', 'category_choice', ) ) -
Django rest framework: Cascade activate/deactivate
I am working on an API using django and django rest framework, what I want to do is cascading with two action for related models Deleting an instance and that goes smothely with no problem using on_delete=modles.CASCADE on the models.ForeignKey. Activation and deactivation and here is the problem Each model I defined in my application there is a boolean field is_active which indicates if this instance is active or not, what I want to do here is to cascade activation and deactivation whenever the is_active field changes and I want to handle this in a dynamic way because my application is growing big and I don't want to change this service manually every time I create a new foreign key for any model. For example I have the following models class Company(AbstractNamingModel): name_en = models.CharField(_("English Name"), max_length=64, unique=True, null=True, blank=True) name_ar = models.CharField(_("Arabic Name"), max_length=64, unique=True, null=True, blank=True) is_active = models.BooleanField( _("Is Active"), blank=True, default=True, ) class Branch(AbstractNamingModel): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name=("Company branches"), related_name="company_branches", ) is_active = models.BooleanField(_("Is Active"), blank=True, default=True) class Department(AbstractNamingModel): branch = models.ForeignKey( Branch, on_delete=models.CASCADE, verbose_name="Branch Departments", related_name="branch_departments", ) is_active = models.BooleanField( _("Is Active"), blank=True, default=True, ) class Employee(AbstractUser, TimeStampedModel): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) … -
Issue with creating different profiles in Django signals
I'm facing an issue in my Django application where I need to create different profiles, either Profile1 or Profile2, based on the value of user.is_manager. I'm utilizing signals to handle this logic. Here is a summary of the problem: I have two profile models: Profile1 and Profile2. Profile1 is intended for manager users, while Profile2 is for non-manager users. In my managers.py file, I set user.is_manager to True for manager users during the creation of a user. However, when I try to access instance.is_manager in my signals.py file, it consistently returns False, even though it should be True according to the value set in managers.py. I have already reviewed my code and verified that user.is_manager is correctly set to True in managers.py. I'm looking for guidance on why the value of instance.is_manager is not being captured accurately in the signals. Any suggestions or insights to resolve this issue would be greatly appreciated. # managers.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone, username, email, password): user = self.model(phone=phone, username=username, email=email) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, phone, username, email, password): user = self.create_user(phone, username, email, password) user.is_admin = True user.is_manager = True # when create a superuser it's a … -
Django Rest Framework Serializer Update Method
I have a serializer that I am using to make an update I however cannot seem to make it work. The view is a ModelViewSet, and the main Model is a User model which has a foreign key mapping to a Profile model. Below is the view code class RegisterPublicAPIView(viewsets.ModelViewSet): # serializer_class = RegisterPublicSerializer http_method_names = ['get', 'post', 'put', 'delete'] lookup_field = "public_id" permission_classes = (permissions.IsAuthenticated,) def get_serializer_class(self): if self.action in ['list', 'retrieve']: return RegisterListPublicSerializer if self.action == 'create': return RegisterManagePublicSerializer else: return RegisterUpdatePublicSerializer def get_queryset(self): return User.objects.all() def post(self, request): updateSerializers = self.get_serializer_class() serializer = updateSerializers(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data return Response(user_data, status=status.HTTP_201_CREATED) Below is the serializer code with comments on what I have tried and the error response I am getting. class RegisterUpdatePublicSerializer(serializers.ModelSerializer): department = serializers.IntegerField(required=True) salutation = serializers.CharField(max_length=10, required=True) firstname = serializers.CharField(max_length=40, required=True) lastname = serializers.CharField(max_length=40, required=True) mobile = serializers.CharField(max_length=40, required=True) tel = serializers.CharField(max_length=40, required=True) class Meta: model = Profile exclude = ('id',) def update(self, instance, validated_data): profile = Profile.objects.get(id=instance.profile.id) profile.firstname = validated_data.get('firstname') profile.lastname = validated_data.get('lastname') profile.mobile = validated_data.get('mobile') profile.tel = validated_data.get('tel') profile.salutation = validated_data.get('salutation') profile.save() dept = Department.objects.get(id=validated_data.get('department')) # instance.department_id = (dept.id, instance.department_id) # Expected a number but got (2, 2) # instance.department_id = dept.id … -
Connecting to snowflake in django using proxy
I have deployed my django app on heroku and I want to connect to snowflake. But whenever I redeploy, IP changes and my app is not able to connect to snowflake(IP whitelisting issue). I have tried to use fixie as a proxy so that when I connect to snowflake, my IP doesnt change and I don't need to get it whitelisted. Below are two code snippets I have been using to connect to snowflake. But my app keeps trying to connect using my network IP and not the proxy. MY IMPORTS: from sqlalchemy import create_engine from sqlalchemy import text import requests import snowflake import snowflake.connector snippet 1: engine = create_engine( 'snowflake://{user}:{password}@{account}/{database}/{schema}'.format( user=connection_details["user"], password=connection_details["pw"], account=connection_details["account"], database=connection_details["database"], schema=connection_details["schema"], ), connect_args={ 'proxy': 'http://fixie:kT8kuyNpPbrbdx@velodroll.usefixie.com:80' }) snippet 2: engine = snowflake.connector.connect(user=connection_details["user"],password=connection_details["pw"],account=connection_details["account"],database=connection_details["database"],schema=connection_details["schema"],connect_args={'proxy': 'http://fixie:kT8djczxc14@velodsad.usefixie.com:80'}) and the error i keep getting : snowflake.connector.errors.DatabaseError: 250001 (08001): Failed to connect to DB: pv40812.east-us-2.azure.snowflakecomputing.com:443. IP address 169.169.169.69 is not allowed to access Snowflake. Contact your account administrator. For more information about this error, go to https://community.snowflake.com/s/ip-xxxxxxxxxxxx-is-not-allowed-to-access. I tried to connect to snowflake through fixie proxy but it keeps ignoring it