Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSS files not loading correctly in the application
In my Django application, I see that the code that is loaded is different from the code written in CSS files. What is the source of this change? How can it be resolved? -
How to set session with Django Rest Framework
For my Django project, I'm implementing RestAPI using DRF. To preserve some variables needed by two APIs, I wish to use a Django session. However, when I called Api2 after setting the session on Api1, it was None. Has anybody encountered it before? Thank you very much for your assistance! Here is an example of my API code: from rest_framework import viewsets class BaseViewSet(viewsets.ViewSet): @action(methods="post") def lookup(self, request): request.session['abc'] = 1 request.session.modified = True request.session.save() print(request.session.session_key) # p02sr0qlnzntagfkf9ekm8f8km4w82t4 return = {} @action(methods="post") def login(self, request): print(request.session.session_key) # None, it should be key p02sr0qlnzntagfkf9ekm8f8km4w82t4 print(request.session.get('abc') # None data = {} -
Django - Hide legend in Highcharts from Python script
I would like your help for a little project I'm doing with Django and Highcharts.js. My target: hide legend in Highcharts's chart from my script views.py From my views.py file I have managed to be able to correctly plot different types of charts. But I can't hide the legend from views.py. To give an example I have borrowed the code from this django-highcharts-example tutorial in Github. Here is the example code to replicate the behaviour of the script: views.py def ticket_class_view_3(request): dataset = Passenger.objects \ .values('ticket_class') \ .annotate(survived_count=Count('ticket_class', filter=Q(survived=True)), not_survived_count=Count('ticket_class', filter=Q(survived=False))) \ .order_by('ticket_class') categories = list() survived_series_data = list() not_survived_series_data = list() for entry in dataset: categories.append('%s Class' % entry['ticket_class']) survived_series_data.append(entry['survived_count']) not_survived_series_data.append(entry['not_survived_count']) survived_series = { 'name': 'Survived', 'data': survived_series_data, 'color': 'green' } not_survived_series = { 'name': 'Survived', 'data': not_survived_series_data, 'color': 'red', 'showInLegend': "false" } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Titanic Survivors by Ticket Class'}, 'xAxis': {'categories': categories}, 'series': [survived_series, not_survived_series], 'plotOptions': {'column': {'showInLegend': 'false'}} } dump = json.dumps(chart) return render(request, 'index.html', {'chart': dump}) The html where I import Highcharts.js and create the charts. ticket_class_3.html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Django Highcharts Example</title> </head> <body> <a href="{% url 'home' %}">Return to homepage</a> <div id="container"></div> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> … -
Django Rest Framework Nested Representation Not Showing
My models.py: class Brand(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name=_("brand name"), help_text=_("format: required, unique, max-100")) def __str__(self): return self.name class ProductOrService(models.Model): web_id = models.CharField(max_length=50, unique=True, verbose_name=_("product web id"), help_text=_("format: required, unique")) slug = models.SlugField(max_length=255, null=False, blank=False, verbose_name=_("product/service url"), help_text=_("format: required, letters, numbers, underscore or hyphen")) name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("product/service name"), help_text=_("format: required, max_length=250")) seller = models.ForeignKey(User, related_name="product_or_service", on_delete=models.PROTECT) description = models.TextField(verbose_name=_("product description"), help_text=_("format: required")) category = TreeManyToManyField(Category) is_visible = models.BooleanField(default=True, verbose_name=_("product/service visibility"), help_text=_("format: true->product is visiible")) is_blocked = models.BooleanField(default=False, verbose_name=_("product/service blocked"), help_text=_("format: true->product is blocked")) created_at = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_("date product/service created"), help_text=_("format: Y-m-d H:M:S")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("date product/service last updated"), help_text=_("format: Y-m-d H:M:S")) is_product = models.BooleanField(default=True, verbose_name=_("Is this product?"), help_text=_("format: true->product, flase->service")) users_wishlist = models.ManyToManyField(User, related_name='user_wishlist', blank=True) reported_by = models.ManyToManyField(User, related_name='reported_product', blank=True) def __str__(self): return self.name class Product(models.Model): brand = models.ForeignKey(Brand, related_name="brand_products", on_delete=models.PROTECT) show_price = models.DecimalField(max_digits=7, decimal_places=2, verbose_name=_("Cost of Product shown on the site."), help_text=_("format: max price = 99999.99")) available_units = models.IntegerField(null=False, default=0, verbose_name=_("available units")) sold_units = models.IntegerField(null=False, default=0, verbose_name=_("sold units")) product_or_service = models.OneToOneField(ProductOrService, related_name='product', on_delete=models.CASCADE, null=True) def __str__(self): return self.product_or_service.name class Service(models.Model): price_min = models.DecimalField(null=True, blank=True, max_digits=7, decimal_places=2, verbose_name=_("Minimum Cost of Service"), help_text=_("format: max price = 99999.99")) price_max = models.DecimalField(null=True, blank=True, max_digits=7, decimal_places=2, verbose_name=_("Maximum Cost of … -
Django problem if language string not in url
My Django site returns 404 if a language string is not attached to the URL as : https://web-***-uw.a.run.app However, when the language string is set, the page loads just fine. https://web-***-uw.a.run.app/en/ I am using Django i18n translation this way: urlpatterns = i18n_patterns( path("i18n/", include("django.conf.urls.i18n")), path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path("", include("core.routes.urls", namespace="resumes"), name="resumes"), path("admin/", admin.site.urls), ) and my setting files language settings: TIME_ZONE = "Asia/Seoul" USE_I18N = True USE_L10N = True USE_TZ = True # Translate files LOCALE_PATHS = [ os.path.join(BASE_DIR, "locale"), ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", # Cors Headers App "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", # End Cors Headers App "django.middleware.locale.LocaleMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] I must be doing something wrong. What is it? -
Cannot add dynos on Heroku (usingDjango app)
Struggling to get my app available on Heroku. Which is strange because it used to work. When querying the error ("heroku logs --tail), this is what I get "at=error code=H14 desc="No web processes running" method=GET path="/"" I searched the problem and looks like I am not running any web dynos. I therefore, went with the following $ heroku ps:scale web=1 Unfortunately, I then came across the following error message: "Scaling dynos... ! ! Couldn't find that process type (web)." When checking with "heroku ps",it does say No dynos on "AppName" The Heroku webiste advises that this is related to the Procfile, which mine seem to be correct: Procfile web:gunicorn mysite.wsgi I have removed the buildpacks as suggested using heroku buildpacks:clear I retried to add some dynos, but still no joice. Would anyone be able to know tell me what I am doing wrong here? Did I miss a step? -
How to create and download a zip file with a list of images?
Here I have list of images with their url. I want to create a zip and store all the images inside zip. After extract the zip file I want the images inside folder. What's happening with the below code is: it creates zip and downloads but when I extract the zip file, there are so many folders like zipfoldername/home/user/my_project/img and only inside img folder there are files. I want is only zipfoldername/img. Also inside img folder files doesn't have images it has image_url only. I want to store image from that image url in the extracted file. image_list = ['https://example.com/media/file1.jpg', 'https://example.com/media/file2.jpg'] folder = os.path.join(settings.BASE_DIR, "imgs") if not os.path.exists(folder): os.mkdir(folder) for i, imgfile in enumerate(image_list): with open(os.path.join(folder, str(i)), 'wb+') as f: f.write(imgfile) response = HttpResponse(content_type='application/zip') s = StringIO.StringIO() zip_file = zipfile.ZipFile(s, "w") folder_files = os.listdir(folder) for filename in folder_files: file = os.path.join(folder, filename) zip_file.write(file) zip_file.close() resp = HttpResponse(s.getvalue(), content_type = "application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=gik.zip' return resp -
Django - Trouble authenticating with a 2 form view (one is a login screen)
I'm attempting to create a login screen that features a search bar at the top. When attempting to log in, I receive this error: "'CustomAuthenticationForm' object has no attribute 'login'". I followed the advice in this post here. Here's my html: <form class="text-2xl" method="POST"> {% csrf_token %} {{ forms.login|crispy }} <button value="login" name="action" class="text-white flex text-xl mx-auto mt-4 max-h-10 stone-bg stone-bevel px-2 pt-1 drop-shadow-md hover:text-amber-200" type="submit"> Login </button> </form> Here's a link to the gist for my MultiFormsView class here. Here's my views: class CustomLoginView(MultiFormsView): form_classes = { 'login': CustomAuthenticationForm, 'search': SearchForm, } success_url = reverse_lazy('home') template_name = 'login.html' def get_context_data(self, **kwargs): context = super(CustomLoginView, self).get_context_data(**kwargs) context['search'] = SearchForm context['login'] = CustomAuthenticationForm return context def login_form_valid(self, form): return form.login(self.request, redirect_url=self.get_success_url()) Here's my forms: class CustomAuthenticationForm(AuthenticationForm): username = forms.CharField( label = "", widget = forms.TextInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black my-1", 'placeholder': "Username *", 'size': "35", }) ) password = forms.CharField( label = "", widget = forms.PasswordInput(attrs={ 'class': "form-control text-lg h-8 rounded-full px-2 pt-1 border-2 border-black my-1", 'placeholder': "Password *", 'size': "35", }) ) class Meta(AuthenticationForm): model = CustomUser fields = ('username', 'password',) After looking into the inherited classes of AuthenticationForm, I didn't find a ".login()" method. … -
How do i add a display filter on queryset received on page with filtering options on a siderbar?
This is view function-based view for the page q=Q() context={'p_qtn':None,'h_qtn':None,'hu_qtn':None} p_qtn=request.GET.get('check1',None) h_qtn=request.GET.get('check3',None) hu_qtn=request.GET.get('check2',None) if p_qtn: q = q & Q(PQtn="None") context['p_qtn']=True if h_qtn: q = q & Q(HQtn="None") context['h_qtn']=True if hu_qtn: q = q & Q(HuQtn="None") context['hu_qtn']=True vessel=request.GET['vessel'] query_args={ f'{vessel}__exact':True} questions = ( Qtion.objects .exclude(q) .filter(**query_args) ) context['questions']=questions return render(request,'ques.html',context) class code: class Qtion(models.Model): Chapter=models.CharField(max_length=3) Stext=models.CharField(max_length=100) Ftext=models.CharField(max_length=400) Qno=models.CharField(max_length=10) HQtn=models.CharField(max_length=30) PQtn=models.CharField(max_length=30) HuQtn=models.CharField(max_length=30) Qtype=models.CharField(max_length=10) Chemical=models.BooleanField() LNG=models.BooleanField() LPG=models.BooleanField() Oil=models.BooleanField() Conditional=models.BooleanField() I want to add display filter by chapter on a siderbar. Code for the page: {% for question in questions %} <div class="question-div"> <div class="top-bar"> <div class="q-code">{{question.Qno}}</div> <div class="short-text">{{question.Stext}}</div> </div> <div class="middle-bar"> <span>{{question.Ftext}}</span> </div> <div class="bottom-bar"> {% if p_qtn %} {% if question.PQtn == 'Graduated' %} <div class="res"> <div class="res-d">Procedure Response</div> <div class="res-dr"><input type="range" id="grad" min="0" max="3" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% elif question.PQtn == 'Binary' %} <div class="res"> <div class="res-d">Procedure Response</div> <div class="res-dr"><input type="range" id="bin" min="0" max="1" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% endif %} {% endif %} {% if h_qtn %} {% if question.HQtn == 'Graduated' %} <div class="res"> <div class="res-d">Hardware Response</div> <div class="res-dr"><input type="range" id="grad" min="0" max="3" step="1"></div> <div class="res-dr"><span class="trans-text">Move slider..</span></div> </div> {% elif question.HQtn == 'Binary' %} <div class="res"> <div class="res-d">Hardware Response</div> <div class="res-dr"><input type="range" … -
Selecting one row from Foreign Key in Django
I have the following models in Django: class Kingdom(models.Model) : class Meta: ordering = ('kingdom_name', ) kingdom_name = models.CharField(max_length=128, null=True, blank=True) def __str__(self) : return self.kingdom_name class Phylum_Clade(models.Model) : class Meta: ordering = ('phylum_name', ) phylum_name = models.CharField(max_length=128, null=True, blank=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.phylum_name class Classe_Clade(models.Model) : class Meta: ordering = ('classe_name', ) classe_name = models.CharField(max_length=128, blank=True, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.classe_name class Ordre(models.Model) : class Meta: ordering = ('ordre_name', ) ordre_name = models.CharField(max_length=128, blank=True, null=True) classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.ordre_name class Famille(models.Model) : class Meta: ordering = ('famille_name', ) famille_name = models.CharField(max_length=128, blank=True, null=True) ordre = models.ForeignKey(Ordre, on_delete=models.CASCADE, null=True) classe_clade = models.ForeignKey(Classe_Clade, on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, on_delete=models.CASCADE, null=True) def __str__(self) : return self.famille_name class Binomiale(models.Model) : class Meta: ordering = ('binomiale', ) nom = models.CharField(max_length=128, blank=True) name = models.CharField(max_length=128, blank=True) binomiale = models.CharField(max_length=128, blank=True) famille = models.ForeignKey(Famille, related_name='famille_names', on_delete=models.CASCADE, null=True) ordre = models.ForeignKey(Ordre, related_name='ordre_names', on_delete=models.CASCADE, null=True) classe_clade = models.ForeignKey(Classe_Clade, related_name='classe_names', on_delete=models.CASCADE, null=True) phylum_clade = models.ForeignKey(Phylum_Clade, related_name='phylum_names', on_delete=models.CASCADE, null=True) kingdom = models.ForeignKey(Kingdom, … -
Djano UpdateView not rendering modelForm
I have a model assesment which is related to other models. i have created a UpdateView, Form based on the model assesment. The problem now is when I render the form in a template, no field is displayed except the submit button, so there is nothing to update. i only see a submit button with no form fields Here designs below models.py class assessment(models.Model): className = models.ForeignKey(all_class, on_delete=models.SET_NULL, null=True) student = models.ForeignKey(students, on_delete=models.SET_NULL, null=True) subjectName = models.ForeignKey(allsubject, on_delete=models.SET_NULL, null=True) firstCa = models.IntegerField(default=0) secondCa = models.IntegerField(default=0) exam = models.IntegerField(default=0) section = models.CharField(max_length=100, choices=section_choices) term = models.CharField(max_length=100 , choices=term_choices) session = models.CharField(max_length=1000) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.className) class Meta: ordering = ['className'] views.py class assessmentEntry(UpdateView): model = assessment fields = '__all__' Form_class = AssessmentForm template_name = 'result/assessmentScore.html' success_url = reverse_lazy('result:index') Forms.py class AssessmentForm(forms.ModelForm): class Meta: model = assessment fields = ['className','student','subjectName','firstCa','secondCa','exam'] urls.py path('assessmentScores/<int:pk>/', assessmentEntry.as_view(), name='assessmentScores'), template(assessmentScore.html) <div > <form method="POST"> {% csrf_token %} {{ Form.as_p}} <button type="submit" class="px-2 text-white bg-indigo-500 rounded-md focus:bg-indigo-600 focus:outline-none"> Save Scores </button> </form> </div> Please what exactly am I doing wrong? and how do I correct it. -
Django Validation - Use Parent field validator and have subclass provide values
I have an abstract Parent model, and the subclasses inherit a field that has a validator. The validator takes in a list, and I would like each child to provide it's own list to validate against. I have something like this. Is there a way to do this? Am I over complicating it? app1.py @deconstrutible class ValidateInList(): def __init__(self, valid_items): self.valid_items = valid_items def __call__(self, value): if value not in self.valid_items: raise ValidationError() class Parent(models.Model): field = models.CharField(max_length=20, validators=[ValidateInList(something)]) class Meta: abstract = True app2.py class Child1(Parent): child_valid_items = [x,y,z] # would take the value of 'something' in Parent class class Child2(Parent): child_valid_items = [a,b,c] # would take the value of 'something' in Parent class -
How to save wallet address to user model in Django?
I have run into a bit of a hiccup here. I have a script which gets the user's Metamask wallet address which works fine. The problem arises when I need to save that wallet address to the user model in this field: ethereum_address = models.CharField(max_length=42, blank=True, null=True) I have a Javascript that fetches the wallet when the Connect button is pressed: function connect() { ethereum .request({ method: 'eth_requestAccounts' }) .then((account)=> saveAccount(account)) .catch((error) => { if (error.code === 4001) { // EIP-1193 userRejectedRequest error console.log('Please connect to MetaMask.'); } else { console.error(error); } }); } function saveAccount(account) { console.log(account); $.ajax({ url: '/connect-metamask/', type: 'POST', data: { 'account': account, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, }); } In the views.py I have this when I have a POST request: def connect_metamask(request): user = request.user if request.method == "POST": user.ethereum_address = request.POST.get("account") user.save() ......... But when I look at the database the ethereum_address is Null . How do I make this work? -
ImportError: cannot import name 'path' from 'django'
I am trying to learn django/make my first web app with the platform. I am trying to set up my first url page, but the path import won't work (Import Error). The import code I used (which is pretty straightforward...) from django import path I am using a virtual environment venv, and have python v 3.10 and django 4.0.5. Any pointers? The only info I could find on this is from 4 years ago, and the issue was a older version of django, which does not seem to be the case here. -
Django displays app.Model.None for attribute with a Foreign Key relationship
Trying to display the attributes of a model (Model2) accessed via a ManytoManyField in Model1. However, Model2 has a ForeignKey field of another model (Model3). That is, I want to display the notes about a song (SongNote model - Model2) where the song title is stored in the Song model (Model3). The SongNote model is a ManytoManyField attribute in a Note model (Model1). wow. this is why computers read code... models.py: # Model3 class Song(models.Model): title = models.CharField(max_length=255, null=True) ... # Model2 class SongNote(models.Model): TYPE_CHOICES = ( ('R', 'Review',), ('W', 'Work on',), ) type = models.CharField( max_length=140, choices=TYPE_CHOICES, default='W', ) song = models.ForeignKey(Song, null=True, on_delete=models.CASCADE) ... def __str__(self): song_name = str(self.type) + " - " + str(self.song) return song_name # Model1 class Note(models.Model): date = models.DateField() student = models.ForeignKey( CustomUser, on_delete=models.CASCADE, ) song_note = models.ManyToManyField(SongNote) views.py: class NotesDetailView(DetailView): model = Note template_name = "note_detail.html" template.html <div class="card"> <div class="card-header"> <span class="text-muted">{{ object.student }}</span> &middot; <span class="font-weight-bold">{{ object.date }} </span> </div> <div class="card-body"> <h5 class="card-title">Songs</h5> <p class="card-text">{{ object.song_note }}</p> # this displays as "[R/W] - [app].SongNote.None" </div> </div> I have tried various for loops in the template. Attempted to you QuerySets in the view.py. And have searched the internet (this post … -
Django conditional subquery slicing with another subquery value
I am looking for a way to conditionally slice the result of a subquery based on another subquery value. Lets' Say i have the models Author and Books: Author: name = models.CharField(max_length=100) birthday= ... Book: author: models.ForeignKey('Author') title: models.CharField(max_length=100) copies_sold: models.CharField(max_length=50) publish_date: .... Now here is what i want to query: 1.All books by an author 2.The best selling n books out of all books by an author (let's say for this example, if an author has less then 3 books return all of them, if the author has between 3 and 6 books return n-1 of the best selling books, if more then 10 give me the 6 best selling books, the excact logic here is irrelevant it just has to be able to destinct between cases of how many books the author has I gave this a try without yet the conditional cases with the following approach: books = Books.objects.all() included_books_qobj = Q() all_books_by_author_qobj = Q() books_by_author_subquery = Books.objects.filter(author_id=OuterRef('id')) .order_by('copies_sold').values('id').annotate(books_count=Count('*')) included_books_qobj.add(Q(id__in=Subquery(books_by_author_subquery.values('id')[:Subquery(scores_by_athlete_subquery.values('scores_count'), output_field=IntegerField())])), Q.OR) all_books_by_author_qobj.add(Q(id__in=Subquery(books_by_author_subquery.values('id'))), Q.OR) best_n_books_by_author = books.filter(included_books_qobj) all_books_by_author = books.filter(all_books_by_author_qobj) Now this fails with: TypeError: '>=' not supported between instances of 'Subquery' and 'int' This makes sense as a subquery cannot be evaluated on its own before … -
Django - redirect to home after login when session times out
If I'm on foo.html and click on a link to bar.html but my session has timed out, I'm taken to the login page. After successful authentication, I am redirected to bar.html. I want it to always redirect to home.html. My settings.py has LOGIN_REDIRECT_URL = 'home'. I am using the django auth and have not overridden the login view. My login.html file contains: <form method="post"> {% csrf_token %} {{ form|crispy }} <a class="button secondaryAction" href="{% url 'password_reset' %}">Forgot Password?</a> <button type="submit" class="btn btn-secondary mt-2 pl-4">Log In</button> </form> -
How to create a request object in Django with a session and cookies of an authenticated user?
In a Django view I can use the cookies from the incoming request and pass it into another request as means of authentication and make requests to other views in the project using the requests module. def someview(request): cookies = request.COOKIES csrftoken = cookies['csrftoken'] baseurl = settings.BASEURL url = f"{baseurl}/api/csvuploads/" payload = {...} resp = requests.post( url, data=payload, cookies=cookies, headers={'X-CSRFToken': csrftoken}, ) I need to have a management command running periodically (as a cronjob) to have a similar logic, the problem is that the management command will run in a container in Kuberentes so I need to create an user, a request, authenticate, and login so I can make more requests. How can I recreate the same request with session, cookies and everything if the request is not coming from a view? My first attempt was to use RequestFactory from the test framework but I couldn't figure out how to create the request with the session and cookies from the authentication. def handle(self, *args, **options): factory = RequestFactory() request = factory.post( "/admin/login", {'username': username, 'password': password} ) user = authenticate(request, username=username, password=password) request.user = user -
how can i get divide time to 1hrs time interval using django?
I wrote a model that adds time limits it is assumed that it will be large limits (eg 9 am - 6 pm) class Schedule(models.Model): WEEKDAYS = ( (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday'), ) worker = models.ForeignKey(User, on_delete=models.CASCADE) weekday = models.IntegerField(choices=WEEKDAYS) from_hour = models.TimeField() to_hour = models.TimeField() now i need it to be automatically broken down into small time intervals, it is needed in order to implement the booking model, it looks like this class Appointment(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) worker = models.ForeignKey(User, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, editable=False) from_hour = to_hour = in (from_hour,to_hour) should be this small interval it should look like a calendar so that the user can choose a convenient time from the available, I think in django there should be some tool that will break a large time interval Thanks -
Accessing production postgres database with django
I have a django site hosted using elastic beanstalk, with a RDS postgres database I'd like to be able query this database and write some code to analyse aspects of the database. I can do this by directly accessing the database and writing postgres queries but I wondered if there was a way to do this using python/django - I can do it when I am accessing a local database but I cant work out how to make a local python kernel connect to the production database -
Async in Django ListCreateApiView
I have a simply ListCreateApiView class in Django, for example: class Test(ListCreateApiView): def list(self, request, *args, **kwargs): """ Some code which is creating excel file with openpyxl and send as response """ return excel_file The problem is, when user send a request to get an excel_file, he must wait for 5-10 minutes till the file will return. User can't go to others urls untill file will not download (I have 10k+ objects in my db) So, how can I add async here? I want that while the file is being formed, a person can follow other links of the application. Thanks a lot! -
where does django inherits 'users' from to feed API to a web
I've created an API with certain paraments and fed it to my django URL with the following sample.. def home(request): response = requests.get('http://127.0.0.1:8000/api/workers/') workers = response.json() return render(request, "home.html", {'users': workers}) pass Where does it inherit the 'users' from? my API doesn't contain anything related to it and I would like to add a second API ontop of it but something like return render(request, "home.html", {'users': workers}, {'users': speciality}) will not work because users is already inherited. -
Log Django shell operations to Google Cloud
We use Django shell (shell_plus to be specific) to do some operations with our data. We would like to log all the operations to comply with some regulations. For example, if we are in the shell now: >> user = User.objects.get(id=1) >> user.name >> Steve These 3 lines of code should be logged (ideally in our Google Cloud logging). What I've found so far, is using iPython and their logstart magic command. For this, I need to create a ipython-config.py file where I specify the log file: # ipython-config.py c = get_config() time_stamp = datetime.now().strftime("%Y-%m-%d-%H-%M") c.InteractiveShellApp.exec_lines = ["%%logstart -t -o /var/log/django/shell-%s.log"" % time_stamp] It now automatically will create a file and save everything (basically what we need). However, we need them to be in Google cloud logs. One option we could use google.cloud.logging lib for python, create a client and then if we run logging.info(msg) (from standard python lib) we will have them logged to GC. But iPython logstart magic function does not seem to even log to stdout, only to file. Is there anything we can do to achieve this? -
Assign 0 if the date doesn't exist in the records from the database
I'm trying to generate a list of values to plot on a dashboard. The list shows how many orders have been made per day for the last 7 days, and if there was no order recorded for that day, then return 0. For example, if we have this order tracker model: Order: {date_ordered (date), count_orders (int), restaurant (string)} If we want to list all the orders for the last seven days, I'd do something like: from datetime import datetime, timedelta from .models import Order last_seven_days = datetime.now()-timedelta(days=6) orders = Order.objects.filter(date_ordered__gte=last_seven_days).order_by('date_ordered') orders return something like this: [<19-05-2022, Restaurant1, 35>, <19-05-2022, Restaurant2, 30>, <22-05-2022, Restaurant1, 19>, <22-05-2022, Restaurant2, 10>, <23-05-2022, Restaurant1, 32>] The final result I would like to get is stretched over the last 7 days. If the last seven days are ['18-06-2022', '19-06-2022', '20-06-2022', '21-06-2022', '22-06-2022', '23-06-2022', '24-06-2022'] Then my output needs to be: [[0,35,0,0,19,32,0], [0,30,0,0,10,0,0]] The above array basically says 2 things: 1- there should be as many tuples as restaurants 2- if the date doesn't exist it means 0 orders were recorded. I feel this can be solved using a query rather than looping 3 times and many conditions. Can you please share some thoughts on this? Thanks -
Use JWT in Django - Automatic refresh token after 'ACCESS_TOKEN_LIFETIME' ends
I want to implement simpleJWT in API in such a way that generated token is send to API request and if the JWT lifetime expires then automatically refresh that token and from now the new token should be used in API request. my customrequest code is--> def _get_jwt(self): refresh = RefreshToken.for_user(self.user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } def _get_authorization_headers(self): """ This function returns authorization headers including token Which is to be passed in post method Returns: This function returns dictionary that contains Authorization (Token) and content-type """ if self.jwt: # access_token = headers = {"Authorization": "Bearer {}".format(self._get_jwt()["access"]), "content-type": "application/json"} else: headers = {"Authorization": "Token {}".format(self._get_token(self.token)), "content-type": "application/json"} return headers def post(self, url=None, data=None): """ This function sends post request to the url Params: url = endpoint where we want to send post request data = data to be sent on that endpoint """ url = self.url + url headers = self._get_authorization_headers() result = requests.post(url, data, headers=headers) return result.text currently I'm using this approach but problem is that, token which is generated first time same token is in headers even after JWT lifetime expires after 5 minute('ACCESS_TOKEN_LIFETIME': timedelta(minutes=5) ) and I want to use new token after every time token …