Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.core.exceptions.FieldError: Related Field got invalid lookup: icontains
I am creating a Cascading dropdown and keep getting a Related Field got invalid lookup: icontains error. I have tried several suggestions under this subject on Stackoverflow but none seems to address my case. I am using autocomplete I have two models. class BusinessCategory(BaseModel): name = models.CharField(max_length=255, verbose_name=_('Category name')) status = models.BooleanField(default=True) class SubBusinessCategory(BaseModel): business_category = models.ForeignKey(BusinessCategory, on_delete=models.CASCADE) name = models.CharField(max_length=255) status = models.BooleanField(default=True) And this is the setup of how it has been used in my model forms class BusinessBoardingForm(forms.ModelForm): """On boarding business form for Business Application""" category = forms.ModelChoiceField( queryset = BusinessCategory.objects.all(), label=u"Business Category", widget=ModelSelect2Widget( data_url='/admin/directories/businesscategory/autocomplete/', model=BusinessCategory, search_fields=['name__icontains'], ) ) # This one works alright. sub_category = forms.ModelChoiceField( queryset = SubBusinessCategory.objects.all(), label=u"Sub Category", widget=ModelSelect2Widget( data_url='/admin/directories/subbusinesscategory/autocomplete/', model=SubBusinessCategory, search_fields=['business_category__name__icontains'], dependent_fields={'business_category': 'name'}, max_results=500, ) ) I am getting the lookup error at the Sub category. What am I missing? -
Where can i find projects or more information using Django channel3?
I am trying to implement a live notification system using Django. But all tutorials seems to be in django-channels2. Can anyone suggest books or tutorials in other than documentation? -
Is there any one to assist me with my django project deployment in ubuntu server
I am using the ubuntu server VPS, placed the Django project in /var/www - name as srv. srv is a folder and inside srv my project name "ems" is placed. it is fully running using python3 manage.py runserver myip:8000. but when I configured site at cd /etc/apache2/sites- available/ems.conf. and below is my content under ems.conf <VirtualHost *:80> ServerAdmin me@amritshahi.com ServerName amritshahi.com ServerAlias www.amritshahi.com DocumentRoot /var/www/srv Alias /static /var/www/srv/ems/static <Directory "/var/www/srv/ems/static"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/srv/ems/media <Directory "/var/www/srv/ems/media"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/ems_error.log CustomLog ${APACHE_LOG_DIR}/ems_access.log combined WSGIDaemonProcess ems python-home=/var/www/srv/ems/venv python-path=/var/www/srv/ems WSGIProcessGroup ems WSGIScriptAlias / /var/www/srv/ems/ems/wsgi.py <Directory /var/www/srv/ems/ems> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> When I enable my site using : a2ensite ems.conf it sucefully enabled and restart apache server . but I get the error message in the page as : Internal Server Error, The server encountered an internal error or misconfiguration and was unable to complete your request.Please contact the server administrator at me@amritshahi.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be … -
Celery - How to get the task id for a shared_task?
I've looked at questions like this one and a dozen others. But none of them seems to be working. I've a shared_task like this one, which doesn't return anything: @shared_task def rename_widget(widget_id, name): w = Widget.objects.get(id=widget_id) w.name = name w.save() I've tried self.request.id and current_task.request.id but they both returned None. My celery version is 5.0.4 and django version is 3.1.1. I'm using Rabbitmq as messenger. -
Iterate Over objects in an m2m_changed signal
I have the following setup: order/signals.py @receiver(m2m_changed, sender=Order.deliverer.through) def m2m_changed_order_deliverer(sender, instance, **kwargs): if kwargs['action'] == 'post_add': instance.deliveringstatus = True instance.save() #changes the order model's, on-delivery status to TRUE once an order_deliverer has been appended onto its ManyToManyField. account-app/signals.py @receiver(m2m_changed, sender=Order.order_deliverer.through) def m2m_changed_deliverer_profile(sender, instance, **kwargs): if kwargs['action'] == 'post_add': #print(instance.order_deliverer.through.objects.all()) obj = instance.order_deliverer.through.objects.last().deliverer obj.busy = True obj.save() #alters the deliverer's profile status to busy. 1. My problem is on handling iterations. If the order's order_deliverer field has multiple user objects, the account signal is only handled on the last object. 2. How do I iterate & alter each deliverer's profile. I'm thinking of looping via 'for' but I first need to be able to fetch individual user objects rather than first or last. -
How to use multiple column from one model
I have three model the user, major, and topic. every user related to one major and each user can have multiple topic. My issue is I want to make sure topic only displayed to user with related major. For example only user with math major can create and see math topic. I have to tell django "This topic is made by math major and only math major can see it." Right now my plan is when user create topic, I want the topic remember the user and what is the user's major.I can save the user who create the topic but I cannot save the major of that user who create the topic to get the current user I use this package class Profile(AbstractUser): # Extra Few New Fields for django user model email = models.EmailField(_("Email Address"), max_length=254, unique=True) major = models.ForeignKey(Major, verbose_name=_("Major Name"), on_delete=models.SET_NULL, null=True) student_id = models.CharField(_("Student ID"), max_length=50, null=True, blank=True) class Topic(models.Model): name = models.CharField(_("Name"), max_length=400) major = models.ForeignKey(Major, verbose_name=_("Major Name"), on_delete=models.SET_NULL, null=True, blank=True) created_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name="created_by") class Major(models.Model): kode = models.CharField(_("Kode Prodi"), max_length=5, unique=True) name = models.CharField(_("Major Name"), max_length=250) status = models.BooleanField(_("major Status"), default=True, help_text="check the box to make major active") -
How can I override admin column name 'is_staff' and 'is_superuser' in django? [closed]
def is_staff(self, obj): return obj.is_staff is_staff.short_description = "Staff" def is_superuser(self, obj): return obj.is_superuser is_superuser.short_description = "Superuser" I've wrote the code above to override the coulmn name of 'is_staff' and 'is_superuser', which is 'STAFF STATUS' and 'SUPERUSER STATUS', to 'STAFF' and 'SUPERUSER'. But it doesn't working. What should I do to fix it? Thanks in advance! -
Django - how does the system determine which form to use?
Django version 3.0.3 I'm trying to use Django's built-in user authentication system, specifically its login form and view. When creating 'login.html' template, we can just write "form" variable in it and the system magically displays it when requested. But the question is "When does Django determine which form to display?" Does it do so while it processes the request for the page containing that form through middlewares? -
unable to update cart table after deleting with jquery
when I delete Item from my Cart. Item deleted on backend but on front end webpage show json data -- {"added": false, "removed": true, "CartItemsCount": 3} -- and not showing actual cart (table). all code is attached. pleaseenter image description here help if you can thanks in console log of chrome. this msg come for nano seconds and disapear.. ""resource interpreted as document but transferred with mime type application/json django"" Cart update view function of Django jquery Code update Cart function of jquery api-cart view function Django Error Message -
Why am I getting a 400 bad request error? Using the Django Rest framework as a backend and React as a frontend for my web application
I am developing a simple web application that utilizes the openweathermap api. There is an api call to a view that returns the api data, and displays the temp & description for the weather of the particular city that the user types in. The api call below is another call for a new feature that allows the user to save a particular weather data of their choosing. It takes the temp & desc from the state, and sends it to the backend view. The view then saves that data into the database, and returns a Response that I will then use to display the data in the same api call. It is giving me a 400 error. I console logged the temp & desc and they both print out correct so I am not sending undefined data to the backend. Could it be the way I am serializing the data? Front end api call const saveWeather = (temperature, description) => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json"}, body: JSON.stringify({ temperature: temperature, description: description }) }; fetch("/api/savedweather", requestOptions) .then((response) => { if (response.ok) { console.log("OK"); } }) .catch((error) => { console.log(error); }); } View class SaveWeather(APIView): serializer_class … -
How do I retrieve a value of ordered queryset
I'm using Django ORM and want to retrieve a value after ordered queryset like below. How do I get a value after ordered? rankings = Ranking.objects.annotate( rank=Window( expression=Rank(), order_by=F('count').desc() ) ) # I want to get an ordered single value. print(rankings.get(user_id=self.id).rank) <- not work well -
how to handle response types with same status code but different meanings
I'm building an API and there are some cases where our frontend can make a request to the API sending in data from a form. The data is checked on the backend and a response status code of 200, 201, or 400 could be returned. For example, status code 200 can mean that the request was good from the frontend to the API, but there is a suggestion from the validated data. (user submitted data, backend validated and has a suggestion for the user). We could also return 200 where everything checks out and the user confirms once more that the validated data is looking good. status code 400 can mean that the request was bad but due to a missing field, an empty field, or there wasn't enough data in the request such that the backend couldnt validate the form data. My current approach is to send a response back with a message, type, and the status code. For example, from the above: {"message": "The username should be: xxxx", "type": 0}, 200 {"message": "Everything looks good!", "type": 1}, 200 {"message": "Missing field", "type": 2}, 400 {"message": "Submitted data couldn't be validated. Try again?", "type": 3}, 400 Then on the … -
Django Ajax with jQuery is not removing elements on success
So , im still learning Ajax , and i faced a new problem , the code i have can add or delete elements dynamicly , for the adding task everything work well but for the delete one its send me a succesful response for the ajax post and its deleting the choosen object on database , but in the html page nothing happend so this is my html ` <div class="col-md-4 col-sm-6 animate-box"> {{request.user.username}} <h3 class="section-title">Add Exercise</h3> <form class="submit-form" method="post" id="TaskForm" data-url="{% url 'exo' %}"> {% csrf_token %} <div class="form-group"> {% for field in form %} <div style="margin-bottom: 2rem;"></div> {{field}} {% endfor %} <div style="margin-bottom: 2rem;"></div> <button type="button" class="btn btn-outline-success" id="addExercise" onclick="">Confirm</button> </div> </form> <div id="taskList"> {% for task in tasks%} <div class="card mt-2" id="taskCard" data-id="{{task.id}}" style="{% if task.completed %}text-decoration: line-through {% endif %} "> <div class="card-body"> {{task.name}} {{tasks.completed}} <button type="button" class="close float-right" data-id="{{task.id}}" > <span aria-hidden="true">&times;</span> </button> </div> </div> {% endfor %} </div> <div style="margin-bottom: 4rem;"> </div> </div> </div> </div> the ajax/jQuery code delete part its the last onclick() call $(document).ready(function(){ var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); $("#addExercise").click(function() { var serializedData = $("#TaskForm").serialize(); console.log("hey hey!"); $.ajax({ url: $("TaskForm").data('url'), data : serializedData, type: 'post', success: function(response) { $("#taskList").append('<div class="card mt-2"><div class="card-body" id="taskCard" … -
Shortest Username Available
I want to write a program in python that can find the shortest available username for example on Gmail. I want to start from "aaaaaa" and end in "zzzzzz" and I want be able to check that in any website. This is a library I find I am not sure if it's related to what I am looking for. https://pypi.org/project/shortuuid/ I would appriciate if you can help with the topic I need to study or where to start. Thank you -
Django: TypeError: object() takes no parameters
I'm trying to create a chat app and am getting this error. I am not really sure what causes this error. I've checked the file where the error occurs(asgirf\compatibilty.py) but still cant seem to get a clue of what causes the error. Exception inside application: object() takes no parameters Traceback (most recent call last): File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routing.py", line 160, in __call__ send, File "C:\Users\aysha\AppData\Local\Programs\Python\Python36\lib\site-packages\asgiref\compatibility.py", line 33, in new_application instance = application(scope) TypeError: object() takes no parameters my asgi.py: application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) and routing.py: from chat.consumers import EchoConsumer,ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<username>\w+)/$', ChatConsumer), re_path(r'ws/chat/', EchoConsumer), ] This is the consumers.py: class ChatConsumer(SyncConsumer): def websocket_connect(self, event): me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) self.thread_obj = Thread.objects.get_or_create_personal_thread(me, other_user) self.room_name = f'presonal_thread_{self.thread_obj.id}' async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) self.send({ 'type': 'websocket.accept' … -
How to get my submit button to submit a comment and post It to the bottom of the page in Django?
I want to create a simple review page. I want someone to be able to type a comment and submit and the page will refresh to the comment being posted at the bottom of the text box. how can I achieve this? so far I have a text box and a submit button that does nothing. Someone, please help! -
Best way to query and filter a database based off of drop down selections in Django
I am new to Django and struggling to figure out how to query a database and then return a filtered list based off of drop-down selections. I have tried doing it with forms but I'm not sure this is necessary as I do not need to store the drop-down data- I just want to use it to query a database and filter it accordingly. So if user selects "dog" in the "type" drop-down I would then query the Dog db and then filter it based off of the second drop-down selection of "age_group". So, if user selected "dog" and then "baby" it would return a list of puppies. dog.model class Dog(models.Model): name =models.CharField(max_length=200,validators=[MinLengthValidator(2, "Nickname must be greater than 1 character")]) breed_group = models.CharField(max_length=200, choices=BreedGroup.choices, null=False, blank=False, default='Not Enough Information') breeds = models.ForeignKey(DogBreed, on_delete=models.PROTECT) age = models.PositiveIntegerField() ageGroup = models.IntegerField(choices=AgeGroup.choices, null=False, blank=False, default=0) sex = models.IntegerField(choices=SEX, blank=False, null=False, default=0) tagLine = models.CharField(max_length=150) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') def __str__(self): return self.name search.html <div class="row" > <div class="col-md-12 justify-content-sm-center"> <div class="input-group" id="searchBox"> <div class="col-xs-1 mx-4"></div> <form class="form-inline" action="." method="GET"> <div class = "justify-content-sm-center"> <label class="sr-only type … -
How do I position Toasts(messages) with Javascript
I'm working on a Toast message setup where, if multiple messages are active, they're not visible except for the one in the front (so maybe a margin of 15px between them would help) and display them on the bottom-corner of the screen (fixed), which doesn't change position when scrolling and make them disappear after 3 secs one by one. How do I go about solving this with JavaScript? Maybe it's possible to target color as in color-green"? {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="color-green"> <div class="color-white"> <div class="icon-success"> <i class="fas fa-check icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'info' %} <div class="color-blue"> <div class="color-white"> <div class="icon-info"> <i class="fas fa-info icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'warning' %} <div class="color-orange"> <div class="color-white"> <div class="icon-warning"> <i class="fas fa-exclamation-circle icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% elif message.tags == 'error' %} <div class="color-red"> <div class="color-white"> <div class="icon-cross"> <i class="fas fa-times icon"></i> </div> <div class="text"> <h2>{{message}}</h2> </div> </div> </div> {% endif %} {% endfor %} {% endif %} .color-green{ bottom: 0; position: absolute; background-color: #40ff00; box-shadow: 4px 4px 16px 0 … -
Importing external js files into React component returns GET 404 result from django server
Inside a React component I am trying to import an external js file i tried this <ScriptTag type={'text/javascript'} src={'./assets/js/main.js'} /> and using this custom hook const ImportScript = resourceUrl => { useEffect(() => { const script = document.createElement('script') script.src = resourceUrl script.async = true document.body.append(script) }, []) } but I always get a 404 error from the django server and I can't really find a solution Your time is very much appreciated -
django - help text for foreignkey on admin page
This is my admin page, I want to display add help_text on admin page for the foreignkey but it looks like if i put help_text on the model file like this. topic = models.ForeignKey(Topic, verbose_name=_("Study Topic"), on_delete=models.SET_NULL, null=True, blank=True, help_text="Help Text 101") it doesnt work, i didnt find a way to put help text on foreignkey on the net but then i found empty_label to replace -----------but it doesn't work as well, is there something wrong with this code. class TopicAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): kwargs['widgets'] = { 'topic': forms.ModelChoiceField(queryset=Topic.objects.all(), empty_label='Select the topic') } return super().get_form(request, obj, **kwargs) -
min() arg is an empty sequence list python
I am trying to fix the following error: ValueError: min() arg is an empty sequence but it always returning the same error above, and I think it needs empty value. Is there any trick or solution how to handle this kind of error. What I've already tried getlist = request.POST.getlist('batch[]') #depends output ex. ['1','3','5'] if (len(getlist)) ==1: batch_level = min(getlist) print(batch_level) else: batch_level = min(getlist) + "-" + max(getlist) #the error is here print(batch_level) -
cannot listen to stripe webhook on an asynchronous django application
Hope you all are doing well. I am trying to connect to my asynchronous django web app a stripe webhook which can send me notifications whenever a payment is made through stripe, the problem that occurs with me right now is that it already is an asynchronous application via django channels, connecting stripe webhook to this url path("hooks/",views.my_webhook_view,name="Hook") doesn't seem to work while doing python manage.py runserver it gives me this error Listen failure: Couldn't listen on 127.0.0.1:8000: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted. . The question that goes off is can I not have more than one websockets to a django app, any leads or approach would be highly appreciated. -
how do I convert json schema into django models?
I have a few jsons with the following structure, but I want to convert in a proper way to render the following JSON schema into a Django model with its proper relationship in order to keep the same format to save its data [ { "Resource Development": [ { "technique_id": "T1583", "technique": "Acquire Infrastructure", "tactic": [ "Resource Development" ], "subtechnique": [ { "technique_id": "T1583.001", "technique": "Acquire Infrastructure : Domains", "url": "https://", "command_list": [], "queries": [], "possible_detections": [] }, ], "command_list": [], "queries": [], "possible_detections": [] } ] } ] -
Can't Get Form To Show in Django
I am trying to build a form that allows users to provide a review of an area they have visited However, every iteration of trying to link the review to the beach model proves to be wasted effort. Could someone please tell me why I can't get the form to show. I am consistently getting an error: Reverse for 'beaches-review' with arguments '('',)' not found. 1 pattern(s) tried: ['review/(?P<beach_id>[0-9]+)/$'] or some variation of that. My code is below. Thank you for any help you can provide. Models.py class Beach(models.Model): name = models.CharField(max_length=80) location = models.CharField(max_length=200) video = models.FileField(upload_to='beachvideo', blank=True) beachPic = models.ImageField(default='default.jpg', upload_to='beachphotos', blank=True) datetimeInfo = models.DateTimeField(auto_now=True) lat = models.FloatField() lon = models.FloatField() info = models.TextField() def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __str__(self): return f'{self.name}' class Review(models.Model): RATING = ( ('1', 'Avoid'), ('2', 'Not Great'), ('3', 'Decent'), ('4', 'Awesome'), ('5', 'The Best'), ) beach = models.ForeignKey(Beach, on_delete= models.CASCADE) author = models.ForeignKey(User, null=True, blank=True, on_delete= models.CASCADE) ratingRank = models.CharField(max_length= 100, blank=False, choices=RATING) waveIntensityRank = models.CharField(max_length= 100, blank=True, choices=RATING) crowdednessRank = models.CharField(max_length= 100, blank=True, choices=RATING) pollutionRank = models.CharField(max_length= 100, blank=True, choices=RATING) noiseLevelRank = models.CharField(max_length= 100, blank=True, choices=RATING) servicesRank = models.CharField(max_length= 100, blank=True, choices=RATING) comments = models.TextField(max_length=250, blank=True) … -
Django:: How to manage large number of connections
I have a webpage, which will access a db every 1 sec. Its a remote db. Eventually i see its becomes very slow to go to another link SO if 100 users open the same page then 100 connection every sec. So the navigation is getting blocked. Any idea how to takle this thing