Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display remote api response (in json) without storing to backend database
How can I implement a super lightweight frontend data display on Django which: the frontend page just need to display json which is response from a remote http request I don't want to store the reponse on Django database , as the user is just checking remote data, the data changes frequently , it is meaningless for me to keep a local copy(my website just provide a frontend interface for the use to check data per their interest: input an ID , retrieve remote data) Is there a lightweight implementation in Django that can do a super lightweight json data display ? Here is what I am doing : I have parsed http response with jq, extract data fields website users are interested I want to find a way to display data in Django in a super lightweight tech implementation, as long as the data is display on Django webpage and show it to the users. We are good. -
Django AuthenticationForm not working, the form takes the data but nothing happens
So basically I'm trying to do a simple login system using Django AuthenticationForm and LoginView. The form takes the user input and when the login button is pressed, the page just reloads, instead of throwing validation errors or logging the user and redirecting him. I've tried to overwrite the clean method but the result is the same. I don't know what I'm doing wrong. Аny help will be appreciated, thanks in advance! This is the User model: class StoreUser(auth_models.AbstractBaseUser, auth_models.PermissionsMixin): email = models.EmailField( unique=True, ) date_joined = models.DateTimeField( auto_now_add=True, ) is_staff = models.BooleanField( default=False, ) USERNAME_FIELD = 'email' objects = StoreUserManager() Here is the Login view: class UserLoginView(auth_views.LoginView): form_class = UserLoginForm template_name = 'store_auth/user_login.html' success_url = reverse_lazy('homepage') And also the form: class UserLoginForm(auth_forms.AuthenticationForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control', 'id': "email-login", 'placeholder': "Enter your email",})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control', 'id':"password-login", 'labels': "Password", 'placeholder': "Enter your password", })) And the HTML: <form method="post" action="{% url 'user login' %}"> {% csrf_token %} <div class="form-group"> <label for="email-login">E-Mail</label> {{ form.email }} </div> <div class="form-group"> <label for="password-login">Password</label> {{ form.password }} </div> <a href="javascript:;">Forgotten Password?</a> <div class="padding-top-20"> <button class="btn btn-primary" type="submit">Login</button> </div> -
Order queryset by field in intermediary table with recursive m2m relationship
I have followers/followees system in my django app and I want to order by user's followers and followees by action time when appropriate action is happend. My models: class UserFollow(models.Model): followee = models.ForeignKey('CustomUser', on_delete=models.CASCADE, related_name='follower_set') # The one who is followed follower = models.ForeignKey('CustomUser', on_delete=models.CASCADE, related_name='followee_set') # The one who followed timestamp = models.DateTimeField(auto_now_add=True) class CustomUser(AbstractBaseUser, PermissionsMixin): # Other fields which don't matter in this question followers = models.ManyToManyField('self', blank=True, related_name='followees', symmetrical=False, through='UserFollow') For example i have user and i can get all his followers in reverse order when they followed this user: followers = user.followers.all() # returns <QuerySet [<CustomUser: follower1>, <CustomUser: follower2>, ... , <CustomUser: follower{n}>] The following qs of course doesn't work: followers = user.followers.order_by('-userfollow__timestamp') I can get followers pk in right order and then get followers objects: followers_pk = user.follower_set.values_list('follower', flat=True).order_by('-timestamp') # returns <QuerySet [n, ... , 3, 2, 1]> followers = CustomUser.objects.filter(pk__in=followers_pk) # returns <QuerySet [<CustomUser: follower1>, <CustomUser: follower2>, ... , <CustomUser: follower{n}>]> (user objects in reverse order) Any suggestions or tips to achieve what i want? -
does swagger support JWT authentication?
How can I add JWT as an authentication for Swagger? Here is my Swagger Settings: SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "JWT": { "name": "Authorization", "description": "JWT authorization", "type": "http", "scheme": "bearer", "bearerFormat": "JWT", "in": "header", } }, "USE_SESSION_AUTH": False, } I get Unknown security definition type http -
Can't connect heroku local to 0.0.0.0:5000
I'm trying to deploy my first Django app on Heroku. The django app works fine with Heroku Local on Localhost:5000, but does not work on 0.0.0.0:5000. It also crashes on Heroku. -
How to run scripts in background in parallel django?
I want to make a web app that has one purpose, mainly for users to setup a job that requires parameters. So users will fill out a form and submit the parameters. The job is a python scripts that looks for an available tee time and book it, meaning it will run indefinitely or until it find a time and books it and then finishes. I want users to be able to setup this job and be able to cancel it. I also need to have the jobs run in parallel as not block the que of jobs. How is this best archived or what is the easiest way to do this? I have read a little about Celery but unsure if it can run tasks in parallel? Any suggestion would be much appreciated! -
django, filter in queryset forms
there is a page, the participants are displayed there, the for loop goes through and displays everything normally. And there is also a form where participants by event id should be displayed in SelectMultiple. How do I use a loop or filter in the SelectMultuple itself <li class="list-group-item px-3"><b>Participants: </b> {% for participant in participants %} {{participant}} {% endfor %} <br></li> this is a for loop and this is the filter field that for works with participants = Participant.objects.filter(event=event.id) I cannot write a form field so that not all participants are displayed there, but by event id 'participants' : forms.ModelChoiceField(queryset=Participant.filter(event=event.id)), how to fix this i need help -
How to Add data when a create django post_save() signal
This is my lead model and another model for the heatmap, here I want to add a new heatmap when a new lead is been created. Lead models.py class Lead(ModelMixin): lead_type = models.CharField(max_length=128) lead_status = models.CharField(max_length=128) agent_applied = models.UUIDField() co_broke_agent = models.UUIDField(null=True, blank=True) sell_within_three_years = models.BooleanField(default=False) has_200k_down = models.BooleanField(default=False) loan_category = models.CharField(max_length=128, null=True) loan_amount = models.FloatField(null=True) outstanding_loan_amount = models.FloatField(null=True) existing_bank = models.ForeignKey(Bank, related_name="leads", on_delete=models.PROTECT, null=True) current_interest_rate = models.FloatField(null=True, blank=True) # Add law firm here last stage. class Meta: ordering = ['-created'] def __str__(self): return self.lead_type Lead- Signals.py from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .models import Lead from heatmap.models import HeatMap @receiver(post_save, sender=Lead) def create_heatmap_for_lead(sender, instance, created, **kwargs): if kwargs['created']: heatmap = HeatMap.objects.create(client=kwargs['instance']) Heatmap - models.py class HeatMap(ModelMixin): heatmap = models.CharField(max_length=255, choices=HEAT_MAP) status = models.CharField(max_length=255) comment = models.TextField(null=True, blank=True) followUpDate = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __str__(self): return str(self.status) Heatmap- models.py -
Use MongoDB without Azure's CosmosDB in Azure Web App Django Project
How to establish a connection with the MongoDB Atlas in a Django project that has been deployed in Azure Web App. What will the database configurations in settings.py look like? This is not working in settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'db-name', 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@<atlas cluster>/<myFirstDatabase>?retryWrites=true&w=majority' } } } python==3.9 django==4.0.4 djongo==1.3.6 I'm in desperate need of assistance. I need to have this resolved as soon as possible. -
What is the difference between Django Login and Authorize in Swagger?
I set up swagger in Django, and I see both "Django Login" and "Authorize". What is the difference between them both in the case of using them in Swagger? -
Django - after changing all reverse related objects the parent object still cannot be deleted
I have the following model for deomnstration purposes): class ProjectModule(models.Model): name = models.CharField(...) module = models.ForeignKey('ProjectModule', ....., on_delete=models.PROTECT) ... (many more fields and relations) ... I wrote a function to merge instances to get rid of duplicates and such. For this I need to change all related objects of the first object (succumber) and point them to their new parent (a submodule of the survivor). After changing all foreign keys I delete the succumber. new_parent = survivor.projectmodule_set.filter(name=entry.name).first() succumber.projectmodule_set.update(module=new_module) succumber.delete() But that's not working because Django throws the following error: "Cannot delete some instances of model 'ProjectModule' because they are referenced through a protected foreign key: 'ProjectModule.module'", <QuerySet [<ProjectModule: 1.1 : LCP : 5583>, <ProjectModule: 1.2 : JB1 : 5583>, <ProjectModule: 1.3 : JB2 : 5583>]> Now, I just changed these (reverse) related objects and gave them a new foreign key. Their name even reflects that (5583 is the id of the new parent). Reloading the succumber before deleting does not help either. It just can not "forget" these relation and therefore can not be deleted although the relations have already changed. I also tried the "long approach": for submodule in succumber.projectmodule_set.all(): submodule.module = new_parent submodule.save() But no luck. What am … -
Unknown field(s) (model) specified for User
I am build project ,when i run python manage.py makemigrations i got this error File "/mnt/c/Users/ZAKARIA/Desktop/project/Accounts/admin.py", line 45, in <module> class UpdateUserForm(forms.ModelForm): File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/forms/models.py", line 327, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (is_staff) specified for User ** Here is my code for models.py** import datetime from django.core.mail import send_mail from distutils.command.upload import upload from django.db import models from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils import timezone from phonenumber_field.modelfields import PhoneNumberField from .managers import UserManger GENDER_MALE = "m" GENDER_FEMALE = "f" OTHER = "o" GENDER_CHOICES = ( (GENDER_MALE, "Male"), (GENDER_FEMALE, "Female"), (OTHER, "Other"), ) class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True) picture = models.ImageField( upload_to='images/users', null=True, verbose_name="") is_active = models.BooleanField(default=True) #is_staff = models.BooleanField(default=False) phone = PhoneNumberField() is_admin = models.BooleanField(default=False) #credits =models.PositiveIntegerField(default=100) linkedin_token = models.TextField(blank=True, default='') expiry_date = models.DateTimeField(null=True, blank=True) objects = UserManger() USERNAME_FIELD = 'email' REQURTED_FIELDS = [] def get_full_name(self): full_name = '%S %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): return self.first_name def __str__(self): return self.email def has_perm(self, prem, obj=None): "Does the user have a specific permission?" return True def has_module_perm(self, app_label): "Does the user have permissions … -
I am getting Memory ERROR when running this program
just met this question online trying to run it am getting memory error. any idea? inputs= ['nodejs','reactjs','vuejs'] print(inputs) for i in inputs: inputs.append(i.upper()) print(inputs) -
WebSocket connection to 'wss://www.mydomain.com:8001/' failed:
Given consumer and routing that previously working. Where is possibly the error happening here. -
How do I search for a query in Django with words that are not in the same order as a product?
products = ProductModel.objects.filter(Q(name__icontains=search) | Q(sku__icontains=search)).select_related('prices') .prefetch_related('images_set', 'remainsmodel_set', 'addressonwarehouse_set') .order_by(sortby + orderby) Example: Product: 'Silicone Case for IPhon 13' q = 'Case for IPhon 13' r = 1 item q = 'Silicone IPhon 13' ("Silicone + IPhon 13" should be displayed and the product should be matched) r = 0 item How to make it so that the search was not for the full name, and the individual words no matter what order. -
Django show notification to User between the two dates
I want to make a notification application on my web application. I want users to see notifications from the Admin panel that set the start and end dates to be displayed during those hours. class NotificationModel(model.Model): start = models.DatetimeField() end = models.DatetimeField() I have to do this without using Redis.I'll add notifications from the Admin panel that I want to show users. When I add, these notifications should only be displayed on the site between start and end dates How can I do that? Should I do it using the filter method through my model? -
Initializing a queryset for a dropdown field in a ModelForm
I have a problem with filtering a queryset through a list of object ID's. Upon form submission, the error [{'item': ['Select a valid choice. That choice is not one of the available choices.']}] shows up. When passing req (a list of integers) into a filtered queryset, Django does not accept req as a set of valid choices/objects and does not save the form. However, when passing a preset list that contains the same values as req, Django accepts and saves the form. I tried printing if req is equal to the same preset list and it returned True. views.py class TransferAddView(LoginRequiredMixin, generic.CreateView): ... def form_valid(self, form, **kwargs): ctx = self.get_context_data() inlines = ctx['inlines'] form.instance.requisition = ctx['req'] if inlines.is_valid() and form.is_valid(): tran = form.save() inlines.instance = tran inlines.save() return super(TransferAddView, self).form_valid(form) def get_context_data(self, **kwargs): ctx=super(TransferAddView,self).get_context_data(**kwargs) ctx['req'] = MaterialRequisition.objects.get(pk=self.kwargs['req']) req = list(MaterialRequisitionItems.objects.filter(requisition=ctx['req']).values_list('item', flat=True)) ctx['item'] = Item.objects.filter(item__in=req) if self.request.method == 'POST': ctx['form']=TransferModelForm(self.request.POST) ctx['inlines']=TransferInlineFormSet(self.request.POST) ctx['form'].fields['transferStatus'].initial = 0 else: ctx['form']=TransferModelForm() ctx['form'].fields['transferStatus'].initial = 0 ctx['inlines']=TransferInlineFormSet(form_kwargs={'req':ctx['req'].pk}) return ctx forms.py class TransferItemsModelForm(forms.ModelForm): ... def __init__(self, *args, **kwargs): req = kwargs.pop('req', None) super(TransferItemsModelForm, self).__init__(*args, **kwargs) ... req = list(MaterialRequisitionItems.objects.filter(requisition=req).values_list('item', flat=True)) self.fields['item'].queryset = Item.objects.filter(item__in=req) -
TypeError: login() takes 1 positional argument but 2 were given.Exception Value: login() takes 1 positional argument but 2 were given
I have written a login view using build-in auth ,django auth.login() gives above error my code. from django.contrib.auth.models import User from django.contrib.auth import authenticate,logout,login def loginpage(request): if request.method == "POST": user_name = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username=user_name, password=password) if user is not None: login(request, user) return redirect("dashboard") return render(request, "loginhtml.html") -
Why does is not entering to the right url?
I am making a project in school, making a site. when i click on nvbar its enter to the right URL but when i enter to another category its doesn't work. for example: if i enter to login: http://127.0.0.1:8000/login/ if i enter to register after login: http://127.0.0.1:8000/login/register and i need it to enter: http://127.0.0.1:8000/register Code: URLS: urlpatterns = [ path('admin/', admin.site.urls), path('', home_screen_view, name="home"), path('register/', registration_view, name="register"), path('logout/', logout_view, name="logout"), path('login/', login_view, name="login"), path('account/', account_view, name="account"), path('Sourcesofknowledge/', Sourcesofknowledge_view, name="Sourcesofknowledge"), path('customersatisfactionsurvey/', customersatisfactionsurvey_view, name="customersatisfactionsurvey"), ] nvbar: <div class="w3-top"> <div class="w3-bar w3-black w3-card w3-left-align w3-large"> <a class="w3-bar-item w3-button w3-hide-medium w3-hide-large w3-right w3-padding-large w3-hover-white w3-large w3-red" href="javascript:void(0);" onclick="myFunction()" title="Toggle Navigation Menu"><i class="fa fa-bars"></i></a> {% if request.user.is_authenticated %} <p>Hello, {{request.user.username}}</p> <a href="" class="w3-bar-item w3-button w3-padding-large w3-white">Home</a> <a href="#" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Medicinal stock</a> <a href="Sourcesofknowledge" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Sources of knowledge</a> <a href="customersatisfactionsurvey" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Satisfaction Survey</a> <a href="logout" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Logout</a> <a href="account" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">account</a> {% else %} <a href="" class="w3-bar-item w3-button w3-padding-large w3-white">Home</a> <a href="login" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Login</a> <a href="register" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Registry</a> <a href="Sourcesofknowledge" class="w3-bar-item w3-button w3-hide-small w3-padding-large w3-hover-white">Sources of knowledge</a> {% endif %} </div> </div> -
Failed to load response data: css and js resources work on one url only
I have a website that looks like this: localhost:8000: https://i.stack.imgur.com/Miz9M.png It contains a search feature that works, but when the page is rendered the style does not load. This is how the page looks when searching for all schools that have a postcode that starts with 30: localhost:8000/find: https://i.stack.imgur.com/5qdyA.png views.py: page = f'{ROOT_DIR}/templates/tst/index.html' @api_view(['GET']) def get_data(request): schools = School.objects.all() return render(request, page, {'schools': schools}) @api_view(['GET']) def filter_view(request, property, filter, search): property = __translate_property(property) filter = filter.replace(" ", "").lower() kwargs = { '{0}__{1}'.format(f'{property}',f'{filter}'):f'{search}' } schools = School.objects.filter(**kwargs) return render(request, page, {'schools': schools}) Both methods use the same index.html. When inspecting the network from browser side (url:http://localhost:8000/find/Postcode/Starts%20with/30?), the css files and js script files cannot be found with error Failed to load response data. No data found for resource with given credential. -
dockerfile with django in visual studio code won't launch due to path not found
I am following a tutorial from visual studio code on creating a docker web app to run my python script in. for your information it is visible in the following link: https://code.visualstudio.com/docs/containers/quickstart-python I followed the django tutorial before this on installing it correctly and tested it so that it works. After allowing vs code to create all my necessary files, i tried to run it via my launch.json file. { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true }, { "name": "Docker: Python - Django", "type": "docker", "request": "launch", "preLaunchTask": "docker-run: debug", "python": { "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/app" } ], "projectType": "django" } } ] } when i try this, i instantly get returned: > docker build --rm --pull -f "H:\Dockerfile" --label "com.microsoft.created-by=visual-studio-code" -t "h:latest" "H:\" < unable to prepare context: path "H:\"" not found The terminal process failed to launch (exit code: 1). I installed everything on my H drive, and after this error I added the H to my … -
How to handle django.http.response.StreamingHttpResponse or map object for testcase
I have test case which response is StreamingHttpResponse, not normal HttpResponse (it downloads the csv file) For example normal response, self.assertContains(response, "Testname") self.assertNotContains(response, "NoMisstake") However how can I do the same thing for StreamingHttpResponse? I reseached and found out response.stream_content is map object. It could be the clue??? -
Django {%url 'index2:Redirect' %} have error occurred
class R_View(RedirectView): pattern_name = 'first:login' query_string = True def get(self, request, *args, **kwargs): print(request.path) return super(R_View, self).get(request, *args, **kwargs) def login(requset): return render(requset, 'login.html') urlpatterns = [ path('2/', views.login, name='first'), path('f/', views.R_View.as_view(), name='Redirect'), urlpatterns = [ path('gb1/', include(('background.urls', 'first'), namespace='index2')) When I input 127.0.0.1:8000/bg1/2 Will report an error:IndexError: pop from empty list I think the hint is that there is a problem in this line, but I don't know exactly where the problem is:{%url 'index2:Redirect' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RedirectView</title> </head> <body> <br> <a href="{%url 'index2:Redirect' %} ?k=10">Go</a> </body> </html> -
Localization of the model with a tree-like structure
I'm new to python/django development and I'm stuck. I'm making a project on Django 4.0.4. I have a tree table in a SQLite database. In the admin panel, I configured it using the DraggableMPTTAdmin class from mptt. I also want to localize the fields of this table. QUESTION: How can I combine the DraggableMPTTAdmin class with the TranslationAdmin class? my_app/models.py from django.db import models from mptt.models import MPTTModel, TreeForeignKey from django.db.models import CharField class NonStrippingCharField(CharField): """A TextField that does not strip whitespace at the beginning/end of it's value. Might be important for markup/code.""" def formfield(self, **kwargs): kwargs['strip'] = False return super(NonStrippingCharField, self).formfield(**kwargs) class CategoriesAndAreas(MPTTModel): name = NonStrippingCharField(max_length=150, unique=False) is_category = models.BooleanField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name def __unicode__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] class Meta: verbose_name = "Category or area" verbose_name_plural = "Categories and areas" my_app/translations.py from modeltranslation.translator import register, TranslationOptions from .models import CategoriesAndAreas @register(CategoriesAndAreas) class CategoriesAndAreasTranslationOptions(TranslationOptions): fields = ('name',) my_app/admin.py + DraggableMPTTAdmin from django.contrib import admin from mptt.admin import DraggableMPTTAdmin from .models import CategoriesAndAreas admin.site.register(CategoriesAndAreas, DraggableMPTTAdmin, list_display=( 'tree_actions', 'indented_title', 'is_category', ), list_display_links=( 'indented_title', ), ) The table has a tree structure with the ability to drag and drop. The form … -
Can i use Chart js for long data?
In django App for visualization , for long data what i can use? Chart JS , Matplotib?.... Please recommendation exemple value for one point : 0;-0.0110227457430789;-0.0117428254241928;-0.0125132024365239;-0.0120122425942302;-0.0121398995885254;-0.0127606573714123;-0.0123882233559148;-0.0126683380476791;-0.0125534489771807;-0.0114614833910938;-0.0139670311717919;-0.0117059991385652;-0.0127469146854689