Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
react rest social auth React auth flow
I'm new to asking on stackoverflow, so please be kind :) My issue is as follows: Im developing a react app(I'm new at this), in whch I intend to authenticate users via social account. What I haven't been able to do is to fullfill the oauth flow between backendapiserver->react app->social provider. BackendAPI server: 1. Django 2. DRF 3. rest-auth 4. django-allauth with github configured with client_id a secret_key as the docs says This is what 've been able to understand about how the flow should be processed: 1. User clicks on button to authenticate to social account(e.g. GitHub) 2. react app makes a post request to Backend and returns a url for the provider.ç 3. react apps, in any manner(haven't found out how) launch another window instance(popup, another tab, etc.) where is going to be asked by the social account provider to authorize authentication from my OAuth app(guess is like that) 4. A preconfigured callback url in social account addapter from the OAuth app is then sent (to front-end? to back-end?) 5. if is to front-end, then resend(or redirect) the code, provided from the social account provider, to backend api, where is in charge to verify(guess with the provider) the … -
Git clone causing issues with Windows permissions over SSH with django project
I've got a Django project which works great. Previously we just cloned down and used password authentication. I changed the remote to git@bitbucket.org:myteam/our_repo.git Recently we started requiring 2FA, so now we can only clone down over SSH. For this project, I created an access key (read-only, which is all I need for cloning down on a staging server) and I was able to clone down the repo (git clone git@bitbucket.org:myteam/our_repo.git) without issue and get it all set up. This appeared to have worked. The other server admin remoted in and tried to run git pull origin master, he got a permission issue. His windows user is part of the Administrators group - but for some reason that didn't matter. His local user had to be added to the directory with full access before he could run git pull origin master It appears that this permission issue is causing other issues, too. File uploads (from the Django admin) are no longer actually uploading the files into the directory on the server - my guess is that this is related to the permissions issue, too. Nothing was changed to impact this - the project was just cloned down over SSH. Does cloning … -
Can not connect to postgresql on localhost using ssl client certificate with django
I am trying to connect to postgresql on localhost using ssl client certificates via django. However I get the following error django.db.utils.OperationalError: FATAL: connection requires a valid client certificate I have tried the following I can connect to a remote postgresql database via the django application (using a set of different certificates) I can connect to the local database (using the same ssl certificates that does not work in django) using psql. I can connect to the database on localhost via the django shell and psycopg2 connection using the following code psycopg2.connect("host=127.0.0.1 dbname=analyticslayer user=al-app password=... sslmode=verify-ca sslcert=/home/al-app/.postgresql/ps-analyticslayer-1-postgresql-al-app-ca.crt sslkey=/home/al-app/.postgresql/ps-analyticslayer-1-postgresql-al-app-key.pem sslrootcert=/home/al-app/.postgresql/vintercapital.com-ca.crt") I have also verified that the certificates are okay using openssl verify would really appreciate some help with this problem / Hakan -
ValueError: Attempted relative import in non-package Python 3.6 (UBUNTU 12.4)
I have the following directory structure: -project_name --folder1 --folder11 -urls.py -views.py -wsgi.py -manage.py --folder2 --folder22 -file1.py -file2.py -file3.py -file4.py -main.py Django version is 1.11.22 Python 3.6 In views.py def abc(request): .... .... .... subprocess.Popen(['python', 'path/to/main.py']) return JsonResponse({ 'status': True, 'code': 200, 'message': "Success!" }) In main.py from .file1 import FILE1 from .file2 import FILE2 from .file3 import FILE3 from .file4 import FILE4 def main(): .... .... if __name__ == '__main__': exit_status = main() I am getting this error: Traceback (most recent call last): File "/path/to/main.py", line 1, in <module> from .file import FILE1 ValueError: Attempted relative import in non-package What can be the issue? I have tried all given solutions on SO. -
Django - how to redirect while sending mail
Question: is it possible to redirect the page while sending the email. It takes 5 to 10 seconds for the mail to be sent. During this time, the page is not doing anything. Users might resubmit the form to prompt a reaction. So I was thinking maybe there's a way to redirect the page right after the object is saved instead of redirecting after the mail is sent. Code below: @login_required def handle_order(request, **kwargs): .... order = form.save(commit=False) order.active = True order.save() # send email to the user, 5-10 seconds waiting time kwargs = {...} mail_order_detail(**kwargs) return redirect('shopping:show-order', order.ref_number) I've tried to use post_save signal, not working, still have to wait before being redirected -
Will Django process inclusion tag if I hide it in html template using css
I am using inclusion tag in sidebar of html page. If I hide the sidebar using css for mobile view. Will Django process the inclusion tag in backend when visited from mobile -
Save chat conversation in json field
I have created a chat bot. I want to save the conversation in JSONField ('question': 'answer') when channel disconnect, or user ends the chat or after 5 min of inactivity. I am using django channels. Everything is working but I don't know how can I save conversation after chat ends. My model to save conversation: class ChatHistory(models.Model): question = models.TextField(null=True) # not required. added just to test answer = models.TextField(null=True) # not required. added just to test conversation = JSONField() customer = models.ForeignKey(Customer, on_delete=models.DO_NOTHING, related_name='customer_chat') date_time = models.DateTimeField(auto_now_add=True) talker = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name='user_chat', null=True) consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['secret_key'] self.user_email = self.scope['url_route']['kwargs']['user_email'] self.room_group_name = 'chat_%s' % self.room_name + self.user_email # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] dir_name = text_data_json['dir_name'] reply = bot_reply(message, dir_name) secret_key = text_data_json['secret_key'] u_id = text_data_json['user_id'] customer = Customer.objects.get(u_field=u_id) company = Company.objects.get(secret_key=secret_key) conversation = {} # I tried to save every question/answer when talker asked and bot responded. Please igore fields. # ChatHistory.objects.create( # company=company, # # question=message, # answer=reply, # # talker=company.company_name # ) # Send message to room group … -
How to store a user's cart information without using models or authentication in Django?
I am making an ecommerce website, I use this view to allow user to add items in cart: def add_to_cart(request, slug): if request.method == 'POST': item = get_object_or_404(Item, slug=slug) order_item = OrderedItems.objects.create(item=item, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] order_item.quantity = request.POST.get('number') order_item.save() order.items.add(order_item) return redirect('core:home') order = Order.objects.create(user=request.user, ordered=False) order.items.add(order_item) order_item.quantity = request.POST.get('number') order_item.save() return redirect('core:product_detail', slug=slug) The models and everything else in this website depends heavily on user authentication. I keep track of which user ordered which items through Order model: class OrderedItems(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name='ordereditems') quantity = models.IntegerField(default=1) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) So, how do I store a user's cart information without using models or authentication using cookies or sessions? Please kindly explain it with code. Github link to current project. Thank You -
Serialization of related pivot models with Django Rest Framework
I am learning Django, and are using Django Rest Framework. In my application, I have three different models Bar (holds information about a bar, has multiple beers through the BarBeer model) Beer (holds information about a beer) BarBeer (connection between a bar and a beer, has pivot fields such as alcohol, type, price and volume) This is how the different models are defined: class Bar(models.Model): name = models.CharField(max_length=60) location = models.PointField() address = models.CharField(max_length=60) description = models.TextField(default='') beers = models.ManyToManyField('api.Beer', through='api.BarBeer') class Beer(models.Model): name = models.CharField(max_length=60) alcohol = models.FloatField(default=0) class BarBeer(models.Model): bar = models.ForeignKey(Bar, on_delete=models.CASCADE) beer = models.ForeignKey(Beer, on_delete=models.CASCADE) price = models.FloatField(default=0) type = EnumField(Type, default=Type.Cask) volume = models.IntegerField(default=0) Now I want to serialize a given bar with all the beers for that particular bar including the extra fields in the pivot model BarBeer. For example, below is what I'd like the output to be (note the extra three fields on the beer, that comes from the BarBeer model): { "id": 1, "name": "A bar", "beers": [ { "id": 1, "name": "Ship Full of IPA", "alcohol": 6.5, "type": "bottle", "price": "35", "volume": "33" } ] } I can't figure out how to get the extra fields from the pivot model … -
Django group by multiple fields and apply aggregation
I'm trying to generate a report from Postgres using Django ORM which will be similar to the following SQL query: SELECT region, manager, report_group, SUM( CASE WHEN invoice_date BETWEEN '2020-01-01' AND '2020-01-31' THEN item_amount ELSE 0 END ) as p1_spends FROM A_TABLE_WITH_SOME_JOINS GROUP BY region, manager, report_group I've written this snippet queryset = queryset.values("region", "manager", "report_group").order_by().annotate( p1_spends=Case( When(invoice__invoice_date__range=('2020-01-01', '2020-01-31'), then=Sum('item_amount')), default=Value(0), output_field=FloatField() ) ) ) I was hoping to achieve a resultset where rows are grouped by region, manager and report_group and the aggregation function applied on item_amount field but the resultset gets grouped by region, manager, report group and invoice date. How can I acheive the expected resultset? -
Django filter only if value is given
I want to get the number of sites per country. Now if the country is not given, the amount of sites for all countries should be the result. My query looks like: Devices = GatewayDevice.objects.prefetch_related("model").filter( model__site__country=country, end_date=None ) Before I do the query I can check if parameter country is null and give it and other value, like example ALL (doesn't work). How can I handle this? -
Django redux knox authentication- request.user is always anonymous
My setup is Django, redux, react with knox authentication. I've managed to login to my application, redux is showing the user and token. when i'm calling a function in views.api, the user is always annoynmous. My function in views.api: def navApi(request): user = request.user data = { 'name': 'Vitor', 'location': 'Finland', 'is_active': True, 'count': time.time() } return JsonResponse(data) note- in the request i can see the token in the header. Am I missing something? -
USE_THOUSAND_SEPARATOR only to selected fields of a model Django
I have a model which has two fields ID and price- both are numbers, I only want my price to be comma separated using USE_THOUSAND_SEPARATOR in django. When I use USE_THOUSAND_SEPARATOR= True in my settings.py file it changes both ID and price to be comma-separated. Also, I have used NUMBER_GROUPING=2, but it still groups it with 3 numbers. Thanks -
Django server shuts down
As soon as I try to switch from http://127.0.0.1:8000/ to http://127.0.0.1:8000/admin/, the django server automatically shuts down, without any error. What could be the problem? I just can’t find a solution. Thanks in advance. -
The url does not change at form submit?
I have some categories, like restaurants, sport and fitness, fast food etc.. I want to create dropdown menu with all categories and show different category items each time when different category is selected: HTML: <form action="{% url 'show-all-objects' category=category page_num=1 %}" method="POST" id="sort_form"> <select data-placeholder="Categories:" class="utf_chosen_select_single" id="select_sort_category" name="select_sort_category" onchange="this.form.submit()"> <option>Категориии</option> <option value="restaurants">Ресторанти</option> <option value="sportfitness">Спортни и фитнес</option> <option value="carservice">Автосервизи</option> <option value="beautysalon">Салони за красота</option> <option value="fastfood">Бързо хранене</option> <option value="carwash">Автомивки</option> <option value="fun">Забавлание</option> <option value="other">Други</option> </select> </form> Okay, this is the first link: http://localhost:8000/objects/all/restaurants/1/ Then from <select> select second option with value sportfitness It refresh page and show items from category sportfitness but url is still http://localhost:8000/objects/all/restaurants/1/ After that select third option with value carservice page is refresh again, this time url is changed to http://localhost:8000/objects/all/sportfitness/1/ instead of carservices so it has delay 1 time. urls.py: from django.urls import path, re_path from . import views urlpatterns = [ path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects'), path('add/<str:category>/', views.add_object, name='add-object'), path('<str:category>/<int:pk>/<int:page_num>/', views.show_object, name='show-object'), #path('all/<str:category>/<int:page_num>/', views.show_all_objects, name="show-all-objects"), re_path(r'all/(?P<category>\w+)/(?P<page_num>\d+)/?/(?P<city>\d+)?', views.show_all_objects, name="show-all-objects"), ] views.py: def show_all_objects(request, category, page_num, city=None): params_map = { 'restaurants': Restaurant, 'sportfitness': SportFitness, 'carservice': CarService, 'beautysalon': BeautySalon, 'fastfood': FastFood, 'carwash': CarWash, 'fun': Fun, 'other': Other, } if request.method == 'POST': category = request.POST.get('select_sort_category') objects = Object.objects.instance_of(params_map.get(category)).order_by('rating') if city is not … -
Python requests with django.test. Send post request by django.test and have request.FILES
i have view def my_view(request): if request.method == 'POST': folder = request.POST.get('folder', '') for fname, file in request.FILES.items(): save(folder, fname, file) return HttpResponse(status=200) return HttpResponse(status=400) I send response using python lib requests like this in production requests.post(url='', data=post_data, files=files_to_send) i have request.FILES and i can save it. Now i need make tests. If i write like this i have no files in request.FILES. class Test(TestCase): def test_1(): response = self.client.post('http://127.0.0.1:8000', data={'folder': 'save_folder/'}, files=files_to_send) self.assertEqual(response.status, 200) How i can to send by post request files, and receive it on my_view in request.FILES? Or how i can use code located bellow on django.test? import requests requests.post(url=url, data=post_data, files=files_to_send) -
Cannot Get Menu item to Template
i have 2 apps in Django Project one is Saas and seccond one is Menu. from Saas i can get everything to template but from Menu i cannot get menu items in html navbar. my project Tree is Picture For Tree Code in Html Template {% for item in Menu_list %} <li class="nav-item dropdown dropdown__megamenu"> <a class="nav-link dropdown-opener" href="#"> {{ item.title }} </a> <div class="custom-dropdown-menu custom-megamenu"> <div class="content"> <ul class="megamenu"> <a href="#">დიზაინი</a> </ul> </div> </div> </li> {% endfor %} Code for Views.Py from django.shortcuts import render from .models import Menu,MenuItem def index(request): Menu_list = Menu.objects.all() MenuItem_list = MenuItem.objects.all() return render(request, 'header-footer.html',{'Menu_list' : Menu_list, 'MenuItem_list': MenuItem_list,} ) -
models.FileField.read csv returns b'0,0,0,0\n1,1,1,1'
I read the file by models.FileField and it returns myModel.document is models.FileField object. f = myModel.document.read() print(f) this might be csv file, but how can I handle this object????? b'0,0,0,0\n1,1,1,1' -
In a need of architectural advice for building a web service
I am currently planning the architecture for a web service that can process imagery using Python logic on a server. I am leaning strongly towards the Mean stack. Do I need to use Flask/Django ontop of the Mean stack or is the Mean stack itself fully interoperable with Python being executed on some kind of server? If so, is Flask good enough of a framework on its own- or do I need to use Django with the following planned features for implementation: Sending and recieving images Manage users Handle payments Handle user data I do admit that I lack certain experience in some of these fields - but I feel like it's a big waste of time to further invest time into making Tic Tac Toe games. Thank you for your time. -
How to use django request object outside of django view
def home(request): return render(request,'index.html') how to use request the request object outside of the view in Django. I want to use request.user in another simple python file in same project. -
"parcella_pk" not okay there, it cause a "ValueError". What should I use?
I don't know what type of data should I use there. With primary key I think is there are no problem. But it's not that what I needed. This is part of my models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Parcella(models.Model): ### user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.parcellanev class Muvelet(models.Model): ### parcella = models.ForeignKey(Parcella, on_delete=models.CASCADE) This is part of my views.py: @login_required def muvelethozzaadas(request, parcella_pk): if request.method == 'GET': return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm()}) else: try: form = MuveletForm(request.POST) ujmuvelet = form.save(commit=False) ujmuvelet.parcella = parcella_pk ujmuvelet.save() return redirect('parcellak') except ValueError: return render(request, 'foldmuv/muvelethozzaadas.html', {'form':MuveletForm(), 'error':'Nem megfelelő adat. Kérlek prbáld újra!'}) This is part of my parcellaegy.html: <form method="POST" action="{% url 'muvelethozzaadas' parcella.id %}"> {% csrf_token %} <button type="submit">Hozzáadás</button> </form> -
How to pass Two templates in a same class based views
I am having one issue with the django template view. I am having two urls 1) For Current User Profile 2) For His Team mates urls.py path('profile/', views.UserprofileIndex.as_view(), name='user-profile'), path('profile/<int:pk>', views.TeamProfileIndex.as_view(), name='team-profile'), It's views class TeamProfileIndex(TemplateView): template_name = 'accounts/profile/team_profile.html' def get_context_data(self, **kwargs): context = dict() self.pk = self.kwargs.get("pk") try: user_profile = Profile.objects.get(user=self.pk) except Profile.DoesNotExist: logger.error("Requested user profile not available") raise Http404 teams = User.objects.all() context.update( { 'user_profile': user_profile, 'teams' : teams } ) return context class UserprofileIndex(TemplateView): template_name = 'accounts/profile/index.html' def get_context_data(self, **kwargs): context = dict() try: user_profile = Profile.objects.get(user=self.request.user) except Profile.DoesNotExist: logger.error("Requested user profile not available") raise Http404 teams = User.objects.all context.update( { 'user_profile': user_profile, 'teams' : teams } ) return context In both views only one query is changing , that is 'user_profile'. Is there any way to pass this in a single views to two diffrent html pages ? -
Processing a Django Form in a Celery Task - How can the celery task see the form?
The use case is rather simple. That of a background transaction manager, which requires that this classic type of post handler: class MyCreate(CreateView): model = MyModel fields = '__all__' def post(self, request, *args, **kwargs): self.form = self.get_form() if self.form.is_valid(): self.object = self.form.save(commit=True) return self.form_valid(self.form) else: return self.form_invalid(self.form) doesn't save the form with form.save(), but rather saves the form object somewhere (to the session?) starts a Celery task which will then be responsible for running form.save() The problem I'm facing is that the form object is refusing to serialize at all, with JSON or pickle, it's just too rich an object, and starting a Celery tasks requires the arguments to be serialized. I can serialize just the POST data (request.POST) which is doable, and pass it to the Celery task as an argument which works but I can't from that find any way to reinstantiate a form, let alone a formset. if I want to start the Celery task from a view I redirect to (that implements a progress bar say) then I have the even bigger challenge of passing the form to a whole new Django view. The obvious candidate is to save it to session: self.request.session["my_form_data"] = self.request.POST But … -
Django: how to create dropdown dependancies
I have a dropdown taking distinct values from a database. Depending on the selected value in this dropdown, I want a second dropdown to be updated with other distinct values from the same table. As an example, let's say that I have a table with 'Continents' and 'Countries' fields, if I select 'Europe' for instance, I want the second dropdown to show the countries in my db which belong to this continent. I managed to create the first dropdown and connect it to the db, but I'm struggling with the second step, which is to retrieve the first dropdown's selection and use it to update the second one. Here is my views.py: def MyView(request): query_results = data_world.objects.all() continents_list = ContinentsChoiceField() countries_list = CountriesChoiceField() query_results_dict = { 'query_results': query_results, 'continents_list': continents_list , 'countries_list': countries_list , } return render(request,'home.html', query_results_dict) models.py: class data_world(models.Model): id = models.AutoField(primary_key=True) continent_name= models.TextField(db_column='CONTINENTS', blank=True, null=True) country_name = models.TextField(db_column='COUNTRIES', blank=True, null=True) city_name = models.TextField(db_column='CITIES', blank=True, null=True) class Meta: managed = True db_table = 'world' forms.py: class ContinentsChoiceField(forms.Form): continents = forms.ModelChoiceField( queryset=data_world.objects.values_list("continent_name", flat=True).distinct(), empty_label=None ) class CountriesChoiceField(forms.Form): countries = forms.ModelChoiceField( queryset=data_world.objects.values_list("country_name", flat=True).distinct(), empty_label=None ) home.html: <div class="container"> <form method=POST action=""> {{ continents_list}} </form> </div> <div class="container"> <form method=POST action=""> … -
It gives me AddForm() missing 1 required positional argument:'request' .. What is wrong?
Views.py Html Error message that is all