Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django // How do I need to setup user data management?
I'm working on a pwa with django and I almost done all the front/backend and I'm now facing which might be the last part to put in place (I believe and hope so !) : User Data Management I already had a look at Django's documentation regarding user/group management and I think it is quite logical and understandable however I'm really stuck on how should I implement all of this according to my project ? And especially how should I manage user's data ? Today, the development part is already setup with models/data saving/editing. But there's no user dimension for now, everything created and stored in the database is "general" (I'm using SQLite3 mainly because it was easier to deal with for development and testing but I'm clearly not fixed to it and I can easily readapt parts of the code based on the chosen database and how it work, even more if other database are better adapted to what I am looking for). To give you a bit of context the application should allow anyone to create an account to access the app. When he user is logged on, he/she will be able to arrive on an interface with … -
Optimal Way to Add Dynamic Fields or Preload Initial Values for Django Models
So... I'm working on Django Project in which a question form will be presented to the user. The questions are all yes or no so it will be easy to do that on a database. NOT! for me at least. I've been scouring Google, Django Docs, et al. looking for an answer to this however the only answer I can think of is the one I will be presenting below. GOAL: Make a model class named EmployeeMedicalQuestions in which I will store all the responses sent by a user referencing a One-to-One Relationship with EmployeeProfile. PROBLEM: I have realized that to ask the same questions for all the users, I need to reinitialize the questions for each of them because of the One-to-One Relationship. With my novice experience in Django and Python, I really don't have any idea how to do this 'programmatically'. I also don't want to hard-code the questions (because they might change) as model.BooleanField() one-by-one because I'm too lazy to do that and defeats the purpose of 'dynamic' content. And it's boring. OPTIMAL SOLUTION: I have created a way to overcome this, though by programmatically creating multiple model.BooleanField() variables. Take a look at the code below: models.py … -
Is there any way to make a Cross Login authentication via external API from django view?
Is there any way to make a Cross Login authentication via external API from django view? I need to make request for login, then if this token exists, will be authenticated to the external API. I am googling for a very long time but could not find anything useful. Any help would be appreciated -
best free api for VIN decoder
try to find vin decoder but I did not find please Introduce one website that free and have document for VIN decoder thanks -
Django, don't localize datetimes in views
I'm having trouble understanding how timezones in Django works. Let's say I have a third party API that I get data from with a timestamp of: 2020-10-26 05:00:00 now, let's say that in my view I have a query that filters all of the records from Yesterday ( October 26th) if I have a user that looks at that endpoint in the states, he will see data from October 25th (because in his time zone he is still on the 26th) but I want him to see the data as if he was on the time zone of the original request so he can see this time stamp. -
Use nested dictionary as a datasource for Datatables
I'm new to JS and Django. I have a nested dict in python containing some data that I'd like display in Datatables in Django framework. The dict looks like: {'report': {'country': {'country1': {'POP Count': 15.0, 'POP Age': 2.0, 'Issues': 35.0}}, {'country2': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 2.0}} {'city': {'city1': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 4.06}}, {'city2': {'POP Count': 16.0, 'POP Age': 1.0, 'Issues': 3.099}} }}} The webpage has two datatables - per country and per city and I'm trying to use this dict above as the datasource in the following way: {{ report.country|json_script:"country_json" }} {{ report.city|json_script:"city_json" }} var country_json = JSON.parse(document.getElementById("country_json").textContent); var city_json = JSON.parse(document.getElementById("city_json").textContent); $('#CountryTable').DataTable({ "data": country_json, "column": [ { "data": "POP Count" }, { "data": "POP Age"} ] }) What I'm trying to achieve is for the Country Table to look like this: Country | POP Count | POP Age | Issues -------------------------------------- Country1| 15.0 | 2.0 | 35.0 Country2| 16.0 | 1.0 | 2.0 When I do this, the datatable goes wonky with all my leaf items merged as a string into a single column. I think the nested dictionary isn't being read properly. How do I get my nested dict get read … -
how to modify nested object field inside get_object
I have the following models: class Course(TranslatableModel): thumbnail = ResizedImageField(size=[342, 225], crop=['middle', 'center'], blank=True, null=True) # thumbnail = models.ImageField(blank=True, null=True) students = models.ManyToManyField(UserProfile, related_name='courses') created_by = models.ForeignKey(UserProfile, related_name='course_created', on_delete=models.CASCADE) languages = models.ManyToManyField(Language) categories = models.ManyToManyField(Category) default_language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='def_language') price = models.FloatField(null=True, blank=True, default=0.0) user_group = models.ManyToManyField(UserGroup, related_name='courses', null=True, blank=True) date_creation = models.DateTimeField(auto_now_add=True, null=True, blank=True) translations = TranslatedFields( title=models.CharField(max_length=50, null=False), description=models.CharField(max_length=500, blank=True, null=True) ) and `class Module(TranslatableModel): thumbnail = models.ImageField(blank=True, null=True) course = models.ForeignKey(Course, related_name='modules', on_delete=models.CASCADE) avatar = models.ForeignKey(Avatar, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) evaluation = models.BooleanField(null=True) translations = TranslatedFields( title=models.CharField(max_length=50, null=False), description=models.CharField(max_length=500, blank=True, null=True) ) def __unicode__(self): return self.safe_translation_getter('title', str(self.pk))` the thing that i want to do is that when i do a get of a given course (example:website/api/courses/3) If the field of the module title is empty( means no translation was performed), instead of showing the empty field it returns the field with the original language. This is the code inside get_object: def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ queryset = self.filter_queryset(self.get_queryset()) #print(queryset) # Perform the … -
I want to put data got in Django server into Elasticsearch
I want to put data got in Django server into Elasticsearch. Now I made application named app,I wrote codes in app/admin.py from django.contrib import admin from .models import User, Info class UserInfoAdmin(admin.ModelAdmin): list_display = ( '__str__', 'user', 'info', ) admin.site.register(User) admin.site.register(Info) in app/models.py from django.db import models from django.contrib.auth.models import User class User(models.Model): user_name = models.CharField(max_length=10) pass = models.CharField(max_length=20) class Info(models.Model): foreign_key = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="foreign_key") adress = models.CharField(max_length=200) When I run Django server,username & password & adress info was saved in admin. I want to save these data Elasticsearch.I already installed elasticsearch-dsl-py,read README.(https://github.com/elastic/elasticsearch-dsl-py) However README has only Search Exaple and I cannot understand how to save data Elasticsearch via elasticsearch-dsl-py. Also should I write searching code of Elasticsearch in Search Example in app/models.py?Should I make another file in app directory? Please give me advices. -
DJANGO not receiving data with POST
I'm having an issue trying to send data with fetch to DJANGO. I want to send some data to django through fetch but when I debug I receive nothing in the post value, do you know what could be happening? This is my fetch call: const defaults = { 'method': 'POST', 'credentials': 'include', 'headers': new Headers({ 'X-CSRFToken': csrf_token, 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }), data:{'name':'A name'}, dataType:'json' } const response = await fetch (url, defaults) When I debug I get an empty querydict in the request.POST What am I doing wrong? -
im trying to send authentication request for apple using python and django 1.9, but always giving me unsupported_grant_type
im trying to send authentication request for apple using python and django 1.9, but always giving me unsupported_grant_type def login_with_apple(self, code): apple_url = "https://appleid.apple.com/auth/token" client_secret = generate_apple_client_secret() adapter = AppleOAuth2Adapter(self.request) headers = {'content-type': 'application/x-www-form-urlencoded'} data = {'client_id': settings.CLIENT_ID, 'client_secret': client_secret, 'code': code, 'grand_type': 'authorization_code'} resp = requests.post(url=apple_url, data=data, headers=headers) access_token = None if resp.status_code in [200, 201]: try: access_token = resp.json() except ValueError: access_token = dict(parse_qsl(resp.text)) if not access_token or 'acces_token' not in access_token: raise OAuth2Error( 'Error retrieving access token: %s' % resp.content ) return access_token ** how i generates my client_secret** def generate_apple_client_secret(): now = datetime.utcnow() claims = { 'iss': settings.SOCIAL_AUTH_APPLE_TEAM_ID, 'aud': 'https://appleid.apple.com', 'iat': now, 'exp': now + timedelta(days=180), 'sub': settings.CLIENT_ID, } headers = {'kid': settings.SOCIAL_AUTH_APPLE_KEY_ID, 'alg': 'HS256'} client_secret = jwt.encode( payload=claims, key=settings.SOCIAL_AUTH_APPLE_PRIVATE_KEY, algorithm='HS256', **strong text** headers=headers).decode('utf-8') return client_secret ** im sending a request to apple but always giving me this error** user = self.login_with_apple(ser.instance.token) File "/home/omar/PycharmProjects/Aswaq/oscarapi/views/login.py", line 488, in login_with_apple Error retrieving access token: %s' % resp.content OAuth2Error: Error retrieving access token: {"error":"unsupported_grant_type"} -
Django how can I query only the records which exactly fullfill the filter condition in a Many-to-one condition
I have the following models: class McMbData(models.Model): lastname = models.CharField(max_length=50,blank=True) class Visits(models.Model): mcmbdata_id = models.ForeignKey(McMbData, on_delete=models.CASCADE) name = models.CharField(max_length=50,blank=True) signe_in = models.BooleanField(default=False) I only want to get the records of Visits where signe_in =True Here is what I have tried: McMbData.objects.filter(visits__signe_in = False) So I get all McMbData entries where the condition is fulfilled at least once: Lastname: Mutermann Visits: Bears,True - Renegade,False - Hollywood,False I only want to get the entries of visits which are true. Like this: Lastname: Mutermann Visits: Bears,True -
Response from Google Cloud Platform to Django app
I created a simple Django app and tested in the local server and it was working fine. The app is expected to work like, whenever a post request is received to the corresponding view, the response should be an audio file . In the local server it is working as expected and the response header is showing "'Content-Type': 'audio/mpeg'" but from the Google cloud I am not getting the audio file and the response header is showing the content type as "text/html". Django view if request.method == 'POST': data = request.FILES['file'] tmp = os.path.join(settings.MEDIA_ROOT, "Image", data.name) path = default_storage.save(tmp, ContentFile(data.read())) tmp_file = os.path.join(settings.MEDIA_ROOT, path) # ================ DATA PROCESSING ======================= # Image can be acced in :: tmp_file # ================ DATA PROCESSING - END ======================= fhandle = open("piZero/from_file.mp3", 'rb') # audio output file name tmp = os.path.join(settings.MEDIA_ROOT, "Audio", "output.mp3") path = default_storage.save(tmp, ContentFile(fhandle.read())) audioFile = os.path.join(settings.MEDIA_ROOT, path) # Response build response = HttpResponse() file_handle = open(audioFile, "rb") file = file_handle.read() file_handle.close() response['Content-Disposition'] = 'attachment; filename=filename.mp3' return HttpResponse(file, content_type="audio/mpeg") else: return HttpResponse("GET") app.yaml : since I don't have any static files I haven't run the collect static. In the actual program this audio file will be created from the program. So I … -
Reverse for 'add_review' with arguments '('',)' not found. 1 pattern(s) tried: ['addreview/(?P<id>[0-9]+)/$']
I am getting an error after i have added Review model in django... on admin page model is created but on my site it is not working.I don't know where i am going wrong ...please guide me Getting an error on line 28 of base.html Its also showing an error on views.py line 21 views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def home(request): allbooks= book.objects.all() context= { "books": allbooks, } return render(request,'main/index.html',context) #error line def detail (request,id): bk=book.objects.filter(id=id) reviews=Review.objects.filter(book=id) context ={ "book":bk, "reviews":reviews } return render (request,'main/details.html',context) def addBooks(request): if request.user.is_authenticated: if request.user.is_superuser: if request.method== "POST": form=BookForm (request.POST or None) if form.is_valid(): data=form.save(commit=False) data.save() return redirect("main:home") else: form=BookForm() return render (request, 'main/addbooks.html',{"form":form,"controller":"Add Books"}) else: return redirect("main:home") else: return redirect("accounts:login") def editBooks(request,id): if request.user.is_authenticated: if request.user.is_superuser: bk=book.objects.get(id=id) if request.method== "POST": form=BookForm (request.POST or None,instance=bk) if form.is_valid(): data=form.save(commit=False) data.save() return redirect("main:detail",id) else: form=BookForm(instance=bk) return render (request, 'main/addbooks.html',{"form":form,"controller":"Edit Books"}) else: return redirect("main:home") else: return redirect("accounts:login") def deleteBooks(request,id): if request.user.is_authenticated: if request.user.is_superuser: bk=book.objects.get(id=id) bk.delete() return redirect("main:home") else: return redirect("main:home") else: return redirect("accounts:login") def add_review(request,id): if request.user.is_authenticated: bk=book.objects.get(id=id) if request.method == "POST": form= ReviewForm(request.POST or None) if form.is_valid(): data=form.save(commit=False) … -
Django admin template css is not loaded when deploy it in Heroku?
this is the admin page deployed in heroku, enter image description here here is my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' deploy_settings.init.py DEBUG = False STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] I tried to run python manage.py collectstatic locally, and run it in heroku bash also, but it didn't work. Do we actually need to run this command? or staticfiles are collected when pushing to heroku master? I tried to add DEBUG_COLLECTSTATIC=1 in heroku config variables, but it doesn't work. one last note, I tried to install whitenoise and add it to the settings.py middlewars, and add STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' in deply_settings.init.py but I recieved this error, enter image description here when -
How to create self defined token in Django Token Auth
Can we create a self-defined token in the Token Auth in Django? Currently, we are creating a super-user and generating a token for that super-user. But there are several environments and we want to keep the token same for all environments. Hence, a self-defined token is needed. -
I Have 2 python files in a same directory i want to import one .py file from another .py file
self.txtok=Button(Login_Frame,text='SIGN-IN',font=('arial',15,'bold'),command=self.Login, height=2,width=10,bd=4,padx=2,pady=2,fg='yellow',bg='brown',) self.txtok.grid(row=4,column=0) def Login(self): if (self.uname.get()=="" or self.upass.get()==""): messagebox.showerror("Error","All the feild are requried") elif(self.uname.get()=="1" and self.upass.get()=="1"): self.root.destroy() import WarehouseInventory #messagebox.showerror("SuccessFull",f"welcome{self.uname.get()}") import WarehouseInventory elif(self.uname.get()=="s" and self.upass.get()=="1"): self.root.destroy() import CRUD [Directrories I cannot execute Import WarehouseInventory in 2nd elif ]1 -
Django-allauth Not sending html email on Signup but works perfectly on other times / for other process
I'm using Django-allauth to authenticate user and I'm successfully send HTML email. But problem is when user SIGNUP then verification email is txt file and when Verification email resend it goes of HTML email. Other times like password Reset, login HTML email works perfectly. Only problem is for new user at time of signup only..... Please help me out.. -
How to use django html template tags in react jsx?
I want to use react as a template engine in django. But i don't know how to use django template tags in react jsx Syntex. I searched the web but i got a very common answer the use django as a backend and make an api with django rest framework and use it in react as an api. But in this i have to run two servers, one for django and another one for react but i want to use both in a single server. For this i have to pass data from django backend to template, and for reflect the data on template i have to use django template tags. But in react i don't know how to do this. Any help plz.... -
Provide a specific folder in the media folder for the user to download
Consider that there are three models that are related: class User(AbstractUser): # Its fields class Event(models.Model) user = models.ForeignKey('User', on_delete=models.CASCADE) # other fields class Event_file(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) file = models.ImageField(upload_to='{1}/{2}'.format(self.event.user, self.event) So we will have this structure in the media folder: media User 1 event 1 (where there are several photos) event 2 (where there are several photos) event 3 (where there are several photos) User 2 event 1 (where there are several photos) child 2 (where there are several photos) How can I provide a button in the web page for each user to download their own folder (ie user folder)? Although the user folder may need to be zipped for download. Note: Folder contents are not fixed and may change over time. Thank you in advance -
how to login multiple user in same browser using django
I am create a application where admin and customer login same browser. I read many blog not able not fix my problem. As Django use session based login. I am facing issue while logout my admin then my customer automatic logout. maybe session based functionally My admin LoginView and Logoutview: class AdminLoginView(SuccessMessageMixin,LoginView): authentication_form = LoginForm template_name = 'login.html' redirect_field_name = reverse_lazy('admin_panel:dashboard') redirect_authenticated_user = False success_message = '%(username)s login Successfully !' def dispatch(self, *args, **kwargs): if self.request.user.is_authenticated: # messages.info(self.request, f"{self.request.user.firstname} is already Logged In") return redirect('/admin/dashboard/') return super().dispatch(*args, **kwargs) def get_success_url(self): url = self.get_redirect_url() LOGIN_REDIRECT_URL = reverse_lazy('admin_panel:dashboard') return url or resolve_url(LOGIN_REDIRECT_URL) class LogoutView(LogoutView): """ Log out the user and display the 'You are logged out' message. """ next_page = "/admin/login" def dispatch(self, request, *args, **kwargs): response = super().dispatch(request, *args, **kwargs) messages.add_message(request, messages.INFO,'Successfully logged out.') return response I have implemented customer based login & logout def LoginView(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] remember_me = form.cleaned_data["remember_me"] user = User.objects.get(email=username) if user and user.check_password(password): if user.is_active: if remember_me == False: request.session.set_expiry(0) request.session['user_id'] = user.id request.session['username'] = user.email return HttpResponseRedirect('/') else: context = {'auth_error': "You're account is disabled"} return render(request, 'forntend-signin.html', context ) else: context = { … -
Ways to add new row or update existing in a CSV without using mysql using Django / PHP
I have to add a new row or update existing row of a csv file from a webpage (In the form of AJAX table with crud operation ) without using MySQL or any other DB Table . once i add or update the row it should be updated in that CSV file . Is this possible to do in Django / PHP if yes , can anyone provide me the link so that i can refer Thanks -
Django Filter show default last 30 days
Right now I have a filter that allows me to show objects from a specific date range. It's gotten to the point though where it does not make sense to show the full date range. One always ends up filtering for at least the month or last month. How can this month be set up by default? If you manually pick the dates for, let's say, this month the loaded URL looks as such: http://127.0.0.1:8000/stats/?type=&asset=&symbol=&broker=&date_range_min=2020-10-01&date_range_max= Ideally in the end there could be a quick-select button for [this month | last month | this year] filters.py class StatsFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] def get_filterset_kwargs(self, filterset_class): kwargs = super(StatsFilter, self).get_filterset_kwargs(filterset_class) if kwargs['data'] is None: # I've tried just setting a default to a simpler field but have yet to get any results # kwargs['queryset'] = kwargs['queryset'].filter(type='Long') # Is this where I could fitler for the date_range? # kwargs['queryset'] = kwargs['queryset'].filter(date_range= ???) return kwargs -
How to choose a csv file from a number of csv files available in django
I am pretty new to django and python. I have a number of different csv files with same format in my app in django project. I want to choose a particular file using the hyperlink of the project(website). How can I do that? Are there some other methods? -
what is the mean to getting invalid parameter to prefetch_related()
I am getting below error AttributeError: Cannot find 'detail_set' on Article object, 'detail_set' is an invalid parameter to prefetch_related() I want to know that from where this problem is comming. for exapmle:- Is the issue in serializers or in view file? -
Check if row exist in postgresql if not create and insert it
i would like to know if there is a way to check if a row exists in the db, I'm working with an api and I'll be adding a script who will run every 24 hours to collect data from a page wich has data from many companies but if I run the script today and tomorrow for example there's a chance of gather almost the same data with new ones so i need to get rid of those, is a good idea to use COUNT or should i use if statements? I'm adding this json data to my db: { OrgName: name, Direction: Street 123 City: cityname Lat: 13.123123 Lon: 12.123123 Code: XC23-123D } As mentioned before, the data can be repeated in all the keys but not in the code, will code=unique solve the problem?