Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django- how to create submenu
I am envisioning to create menu with links to various pages. I want to create submenu which should be visible when particular main menu option is clicked. Please suggest what I am writing wrong. <nav id="primary-menu"> <ul class="main-menu text-center"> <li><a href="{% url 'index' %}">{% if '/' == request.path %} <mark>Home</mark> {% else %} Home {% endif %}</a> </li> <li><a href="{% url 'listings_residential_rent' %}">{% if 'listings_residential_rent' in request.path %} <mark>Residential Rent</mark> {% else %} Residential Rent {% endif %}</a> </li> <ul class="sub-menu"> <li><a href="#">Submenu1</a></li> <li><a href="#">Submenu1</a></li> </ul> <li><a href="{% url 'admin:index' %}">{% if user.is_authenticated %} Welcome {{ user.username }} {% else %} Realtor Login {% endif %}</a> </li> </ul> </nav> -
django - saving more than one information from foreign key
I have three model User, Topic and Major class User(AbstractUser): email = models.EmailField(_("Email Address"), max_length=254, unique=True) first_name = models.CharField(_("First Name"), max_length=254) last_name = models.CharField(_("Last Name"), max_length=254) major = models.ForeignKey(Major, verbose_name=_("Student Major"), on_delete=models.SET_NULL, null=True) class Major(models.Model): code = models.CharField(_("Major Code"), max_length=10,unique=True,) name = models.CharField(_("Major Name"), max_length=250) class Topic(models.Model): name = models.CharField(_("Name"), max_length=400) description = models.TextField(_("Description")) created_by = CurrentUserField(blank=True, null=True, on_delete=models.SET_NULL, related_name="created_by") I'm using this repository to save created_by column Now, I want to save the Major code of created_by user on the Topic, i don't know how to pick and save the Major code or created_by user. My end goal is at the end Topic will only displayed to user who has the same major with the person on created_by -
How to deploy a django + django channels docker container in heroku?
I have a dockerized django api backend hosted on heroku. I've used the heroku documentation to deploy the docker container https://devcenter.heroku.com/articles/container-registry-and-runtime. Now I integrated django channels, it works fine locally after i followed the basic installation tutorial https://channels.readthedocs.io/en/stable/installation.html, but it doesn't work on heroku enviroment. What is the best way to deploy a dockerized django channels to heroku? -
Migrating Fixtures to Django Test Database
I need to use a custom database for my tests. I can ensure this by a custom setting file for tests. How can I export fixtures to this test database? (e.g. superuser for tests or other test related database exports) I'm ready to apply other solutions instead of fixtures if fixtures are not applicable to second custom database. Here's my custom setting file for testing: (settings/test.py) from defaults import * DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'my_test_db', } } Here's how I run the tests: python manage.py test --settings=settings.test -
Setting up an academic year in Django
I am fairly new to Django, and find it best to learn by doing but I am truly scratching my head on this one. I am building a pricing tool to practise but I would like to be able to set a rolling academic year regardless of the current year. The fiscal academic year ends at the 31st of March every year so this would be ideal. It would also allow me to pro-rata prices generated by the quoting based on the current month until the next occurrence of March. To summarise: Fiscal year ends at the end of March every year Will be a rolling fiscal year Need to account for pro-rata data, £100 per month so if it is mid-January then it will cost them £200 for contract to start in February. I have searched high and low but it is time to admit defeat and ask those much wiser than me. Your help is appreciated, let me know if you need any more information. -
django admin - displaying multiple column of data in one column from foreign key using list_display
So, I have 2 tables user and major, major as foreign key on the user model. Right now the 'major' on list_display only displaying the name column from major model I need to display column name and rank from major model on the list_display is there a way to do this from django.contrib.auth.admin import UserAdmin as OrigUserAdmin class ProfileAdmin(OrigUserAdmin): list_display = ('username', "email", 'major', 'student_id',) -
Django ldap3 : how to retrieve users belonwing to a CN group
I am trying to implement a login screen on a Windows 2012 server with Django, which brings the Windows AD users belonging to a certain group. For that, I am using ldap3. I put the following code in settings.py: LDAP_AUTH_URL = "ldap://server:389" LDAP_AUTH_USE_TLS = False LDAP_AUTH_SEARCH_BASE = "CN=DevGroup,OU=Groups,OU=America,DC=domain,DC=company,DC=com" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "domain" LDAP_AUTH_CONNECTION_USERNAME = "user" LDAP_AUTH_CONNECTION_PASSWORD = "pass" It is not giving any error (it appears the lookup OK message). However, it isn't retrieving any users to the auth_users table. Doing some research, I saw that the problem is that the users are within the group CN=DevGroup, so I put LDAP_AUTH_OBJECT_CLASS = "group" in stead of "user". That "works" and bring the groups to auth_user table, but I want to bring the users belonging to CN=DevGroup. Can you help me, please? I've been reading a lot of comments and doing a lot of tests, but I can't get it to work. Thank you so much. -
Bootstrap Glyphicons not showing in Django
I am trying to import the bootstrap cdn and display some social icons. For some reason, it is not showing what am I doing wrong? {% load static %} <!DOCTYPE html> <head> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'main/css/styles.css' %}" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> <body> <div class ="right"> <span class="glyphicon glyphicon-envelope"></span> </div> </body>