Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when trying to see my site in PythonAnywhere
I've put my site in PythonAnywhere, but when I try to see it through the browser, it's generated an error. It has something to do with the secret key. In the project (created in pycharm), the secret key is stored in a .env file, and in PythonAnywhere, the secret key is stored in an environment variable in the .profile file. Here's the log error: PythonAnywhere_log_error How could I solve this problem? -
Python Django ORM select custom DB for raw query by session variable
Given the following raw query, inside a view: @login_required(login_url='/login/') def view(request): result = CustomObject.objects.raw("SELECT a, b, c FROM table WHERE d = %(param)s", { 'param': 123 }) ... return render(request, 'templates/template.html', { 'a': 'b' }) I use a router to route the query to a DB (use case is read only). class MyDBRouter(object): @staticmethod def db_for_read(model, **hints): if model == CustomObject: return 'customdb' return None @staticmethod def db_for_write(model, **hints): return None I have the available databases configured: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'customdb': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxx.yyy.zzz:1234/DB', 'USER': 'user', 'PASSWORD': 'pass', } } Problem: During login, the User can specify which database he wants to execute the commands on. Depending on the session, I have to use different databases to connect to, therefore I have to specify manually for each request which DB it goes to. Question: How can I access my session variables from a static method of a router? If using routers is not advised in this specific case, what other options do I have for this problem? -
Django long running asynchronous view blocking other requests
I need help I have been trying to solve a problem for a long time now I want my django project to send some data which it would obtain from another url but the data would be sent in batches. However all have done seems to be blocking other request or operation which I want to do. I have tried to make it an async function but it keeps on blocking other request view.py async def asyncTest(): print('inside asyncTest sleep') await asyncio.sleep(20)#purpose of this is ensure that other request can recieve response print('inside asyncTest wakeup') ..do some other operations @sync_to_async def send_invitation(request): if request.method == 'POST': loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return HttpResponse(json.dumps({"result":"msg_type"}), loop.run_until_complete(loop.create_task( asyncTest())), content_type ="application/json", status=status.HTTP_200_OK) when it gets to asynctest where the sleep is, i try to open another view, the server does not respond. Please can I do to make my program respond asynchronously to other request. -
Django jquery: new elements lost functionality after scroll pagination
I created page where my posts showing after scroll down, they have like function which works well on the first 3 elements (from page=1), but for those posts that show up with pagination function of likes doesn't work. Even the console.log('click') doesn't cause any log in console. list.html {% extends "base.html" %} {% block content %} <div id="image-list"> {% include "content/list_ajax.html" %} </div> {% endblock %} {% block domready %} var page = 1; var empty_page = false; var block_request = false; var max_page = {{posts.paginator.num_pages}}; $(window).scroll(function(){ var margin = $(document).height() - $(window).height() var postion = $(document).scrollTop() if (0.9*margin < postion && block_request==false) { page += 1 block_request=true $.get( '?page=' + page, function(data){ if (page > max_page) { empty_page = true} else{ $('#image-list').append(data); block_request=false} } ) } }) $('button.like').click(function(){ var id_but = $(this).data('id') console.log('click') $.post( '{% url "content:post_like" %}', data = { id : $(this).data('id'), action : $(this).data('action') }, function(){ var button_id = 'button#id-'+ id_but var span_id = 'span#id-'+ id_but var previous_action = $(button_id).data('action') var previous_likes = parseInt($(span_id ).text()) $(button_id).data('action', previous_action == 'unlike' ? 'like' : 'unlike'); $(button_id).text(previous_action == 'unlike' ? 'Like' : 'Unlike'); $(span_id).text(previous_action == 'unlike' ? previous_likes-1 : previous_likes+1)} ) }) {% endblock %} list-ajax.html {% for post … -
Do I need a clean install of Python to start working with virtual environments?
I've been using Python on my system for about a year as a new programmer. Until recently, the topic of virtual environments hasn't come up until got to the end point of the Django course on codecademy. I'm now expected to make a Django project on my own system. I have been just installing packages to Python without making virtual environments in the past as I wasn't aware that it was recommended to create an environment for each project. Should I have a clean install of Python before I start using virtual environments? If so, is there a pip command to uninstall all non-python native packages and essentially reset the install? -
How to push data on git hub I having Permission issue Of my same Account
hello I m new In Coding I made a project I want to push my project on git hub every thing is goes well but if I want to push my data in git repo then I m having this kind of error $ git push -u origin main remote: Permission to manojgupta143/python-.git denied to manojgupta143. fatal: unable to access 'https://github.com/manojgupta143/python-.git/': The requested URL returned error: 403 in my git bash terminal please some buddy can help -
How to separate data by date and its value count of its time interval
I created function in django. where I am fetching data from api by time interval. which have parameters datetime and value. the data is getting like this: { "Parameter_1": { "2021-11-16 14:29:00": 319.56, "2021-11-16 15:16:00": 319.56, "2021-11-16 15:17:00": 319.56, "2021-11-17 00:00:00": 335.48, "2021-11-17 00:01:00": 335.48, "2021-11-17 00:02:00": 335.48, "2021-11-18 00:00:00": 355.45, "2021-11-18 00:01:00": 355.45, "2021-11-18 00:03:00": 355.45, }, "Parameter_2": { "2021-11-16 14:29:00": 319.56, "2021-11-16 15:16:00": 319.56, "2021-11-16 15:17:00": 319.56, "2021-11-17 00:00:00": 335.48, "2021-11-17 00:01:00": 335.48, "2021-11-17 00:02:00": 335.48, "2021-11-18 00:00:00": 355.45, "2021-11-18 00:01:00": 355.45, "2021-11-18 00:03:00": 355.45, } When I am fetching data by time interval of 1 min. the data is getting with date and value but I wish to separate date and value by per date. here, I am separating date and value, I am getting dates by time interval of 1440. and values from time interval 1 I wish to count data of one date and get data like this and count value. { "Parameter_1": { "2021-11-16: 319.56,319.56,319.56, "2021-11-17": 335.48,335.48,335.48, "2021-11-18": 355.45,355.45,355.45, }, "Parameter_2": { "2021-11-16": 319.56,319.56, 319.56, "2021-11-17": 335.48,335.48,335.48, "2021-11-18": 355.45,355.45,355.45, } This is code I does: data = [] for parameter in parameters: for key, values in data_response.items(): for key1, value in values.items(): date = … -
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")