Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it necessary to use serializes in Django rest framework?
Is it necessary to use serializers in Django rest? I'm building a project where I came across a scenario where fields in forms add dynamically and then I need to validated and save data into DB. Since fields in forms dynamic, How can we handle this in serializer? Can we do validations and saving without using serializes? -
Hi, I am using django rest framework I have a json data and i want to post this data using ajax and display this data using ajax
Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax Please help me how i submit my html form using ajax and dispaly my blogs in my html form.I am using django rest framework please help me how i submit my request using ajax and dispaly my blog data using ajax MY views.py file: @api_view(['GET', 'POST']) # @parser_classes([MultiPartParser, FormParser]) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def add_blog(request, format=None): if request.method == 'POST': serializer = AddBlogSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): blog = serializer.save() blogdata = {'title':blog.title, 'author':blog.author, 'description':blog.description, 'image':blog.image.url, 'time':blog.time, 'date':blog.date} data = {'result': 'success', 'message':'Blog post added successfully', 'blogdata': blogdata} return Response(data=data, status=201) elif not serializer.is_valid(): serializererrors = serializer.errors data = { 'result': 'error', 'message':serializererrors} return Response(data=data) if request.user.id and request.method == 'GET': return render(request, 'blog.html') @api_view(['GET', 'POST']) # … -
django-bootstrap5 TemplatesSyntaxError
I am trying to utilize django-bootstrap 5 for my form, after creating the form and everything i rendered my template and here is it. {% extends "base.html" %} {% load bootstrap5 %} {% block content %} <div class="container"> <h1>Log In</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">login</button> {% endbuttons %} {% endblock bootsrap_form %} </form> </div> {% endblock content %} urls.py path('login/',auth_views.LoginView.as_view(template_name='account/login.html'),name='login') But when I run the server I got a template syntax error telling me that its expecting an end block meanwhile I have an endblock already, here is the error: TemplateSyntaxError at /account/login/ Invalid block tag on line 8: 'bootsrap_form', expected 'endblock'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 3.2.4 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 8: 'bootsrap_form', expected 'endblock'. Did you forget to register or load this tag? and the code returned in the error interface looks like this: 1 {% extends "base.html" %} 2 {% load bootstrap5 %} 3 {% block content %} 4 <div class="container"> 5 <h1>Log In</h1> 6 <form method="POST"> 7 {% csrf_token %} 8 {% bootsrap_form form%} 9 <input … -
Not able to retrieve data values from Ajax GET call into Django view
I am trying to query the employee list based on parameter I send through ajax call inside data, but it giving me an error (i want it through GET req only ) Js ajax func $(document).ready(function () { $(".call_ajax").click(function () { $.ajax({ url: "/employee_list", type: "GET", contentType: "application/json", dataType: "json", data: { designation: "soft eng", }, headers: { "X-CSRFToken": csrftoken, Authorization: my_token, }, success: function (data) { console.log(data); }, error: function (xhr) { //Do Something to handle error console.log(xhr.error); }, }); }); my view @csrf_exempt @api_view(['GET', 'POST', 'PUT', 'DELETE']) @permission_classes([IsAuthenticated]) @authentication_classes([TokenAuthentication]) def employee_list(request): if request.method == 'GET': data_ = request.data['designation'] print(data_) employees = Employee.objects.all() students = Student.objects.all() user = MyUser.objects.all() serializer = EmployeeSerializer(employees, many=True) serialized_sudents = StudentSerializer(students, many=True) multi = { 'employees': serializer.data, 'students': serialized_sudents.data } # serializer2 = UserSerializer(user, many=True) return JsonResponse(multi, safe=False) error i am getting in browser GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error) error in Django log File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list data_ = request.data['designation'] KeyError: 'designation' -
How to create superuser for my django project on first migration?
I am creating super user with command python manage.py createsuperuser I would like to set an email, password and create a superuser while running my first migrations. What is the best way to achieve that? -
creating a new instance of todolist in every URL
I want to upgrade my todolist app so that users can create a link to their own todolist. for example, they can do 127.0.0.1/room/testroom and it'll take them to a todo list. Another use can do 127.0.0.1/room/testroom2 will take them to a new room with another instance of the todo list. I'm not sure how to implement this feature. I already have one app set up for the main todo app functionality. I'm in the progress of writing the ROOMS app which will let users create rooms. I don't know how to mix both models from different apps, or should I put them all in the same app? -
Getting self.pk from DetailView for lte/gte comparison (Django)
Goal: Implement next article / previous article feature on article page which is being served via DetailView. Compare current article pk against queryset in order to grab the next and previous articles. I've tried a lot of different methods so far, but I'm getting errors on all of them. ''' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) pk = Post.objects.filter(pk=self.kwargs.get('pk') ''' I've also tried: pk = self.kwargs.get('pk') and pk = self.kwargs['pk'] I get KeyError on the dictionary attempt and None on the get attempts. I can't figure out why I'm not able to return the pk for the article in order to finish the code. Also, I've tried to get other data from the Post model, with the same errors. -
How to host 2 Django Application using gunicorn & nginx in Production
Hello I want to host 2 djagno websites using Gunicorn and Nginx and I don't know how to do this this is my first time to host 2 django websites in one server and 2 domain so please tell me how to host 2 django website. Here is my 1 file located /var/www/site1 and here is my 2 file /var/www/site2 -
Django Social Auth Update First And Last Name in Django App Permanently
I am using django-social-auth to simplify the coded needed to use Auth0 to authenticate for the django application. I want to give my users the functionality to update their first and last names within the django application and have set up an edit profile form to do so. However, after changing their first and last name, once a user logs out and logs back in, their name is re-written so that their first name is their email and they have no last name. I have already tested to make sure the form is working properly (both from the app front end and the database). Is there something I need to configure to prevent social-auth from re-setting the user's name each time they log in? -
Configuring Scrapyd + Django on Docker to use django models
I have this project with scrapy, scrapyd and django. My crawler uses the django models to add the items to the database through the pipelines. What i did was use a single container to start the scrapyd and the django server, but this give the problem that the scrapyd can't find the spiders even if they exist docker-compose.yaml version: "3" services: api: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "cd pokemon_crawler && scrapyd & python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=pokedex - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: "postgres:10-alpine" environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword - POSTGRES_DB=pokedex My crawler view to run the crawler from rest_framework.views import APIView from rest_framework import authentication, permissions from rest_framework.response import Response from scrapyd_api import ScrapydAPI class CrawlerView(APIView): scrapyd = ScrapydAPI("http://localhost:6800") authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def post(self, request, format=None): pokemons = request.POST.getlist("pokemons", None) if not pokemons or not isinstance(pokemons, list): return Response({"error": "Missing args"}) pokemons = ["+"] if "all" in pokemons else pokemons settings = { "USER_AGENT": "Mozilla/5.0 (compatible; Googlebot/2.1; " "+http://www.google.com/bot.html)", } # Here we schedule a new crawling task from scrapyd. # This returns … -
Button must have a tooltip in one of template, but not in the others
I include the button for different templates (and different divs). There should be a tooltip in one of these divs, but not in the others. How can I do this? I think I can check the div class in the button (something like {% if div_class=="..."%}), but I do not know how to do this. Is it possible? Maybe I need to check the template name or something else? first.html <div class="single-card__favorite"> {% include 'button.html' %} </div> second.html <div class="card__footer"> {% include 'button.html' %} </div> button.html {% load user_filters %} {% if author|isfavorite:user %}> <button class="button button_style_none" name="favorites"> <span class="icon-favorite icon-favorite_active"></span> </button> <div class="single-card__favorite-tooltip tooltip">Delete from favorites</div> {% else %} <button class="button button_style_none" name="favorites" data-out> <span class="icon-favorite"></span> </button> <div class="single-card__favorite-tooltip tooltip">Add to favorites</div> {% endif %} -
Django fails at properly redirecting from one view to another
I have a search bar on the side of the webpages of the app i'm working on, what i'm trying to do is have my search view take in the user's query, compare it with a list of entries and if what the user typed in matches the title of any of the entries available, search should redirect to another view called title which handles rendering the html file of the entry the user searched for along with matching it with the approparitate URL (i.e if the user searches for the Django entry, title renders HTML file of said entry and assigns it the URL "example.com/Django") The problem lies in the fact that every time i redirect from search to title, title renders the html file reserved for the case in which no entry matches what the user searched for, no matter whether the entry is available or not. It should also be noted that the path for the search view is a mess. if i write the path like that path("<str:search>", views.search, name="search" i get a NoReverseMatch error saying that django was expecting an argument but recieved none, but path("search", views.search, name=search causes the rendered error page to have … -
Do I need to create react app for every Django app?
I am following this tutorial. https://www.youtube.com/watch?v=6c2NqDyxppU I'm just confused if I have couple of django apps, do I need to create a react app for each or just one react app (in the video's case named frontend)? -
Rendering part of a form conditionally
I have a form where I need to only take address input if "new-address" is selected. I've been trying to only include this form if the correct radio button is checked, but I'm having trouble getting it to work. If I don't escape the braces, the js breaks, but if I do, it renders the addressform as {% include 'partials/form_fields.html' %} and not as the actual form template. I'm open to django based solutions, but this logic needs to be done without refresh. js var addresslist = document.getElementById("address-list"); var addressform = "\{% include 'partials/form_fields.html' %\}" addresslist.addEventListener("change", function () { var address = document.querySelector('input[name="addresses"]:checked').value if (address == "new-address") { console.log(address) document.getElementById('address-form').innerHTML = addressform; } else { console.log(address) document.getElementById('address-form').innerHTML = ""; } }); form <form method="POST" id="subscription-form" data-secret="{{client_secret}}"> {% csrf_token %} <label class="block uppercase text-gray-600 text-xs font-bold mb-2">Payment Details</label> <div class="form-check my-3 bg-gray-200 p-2 rounded-md"> <input class="form-check-input" type="radio" name="payment-methods" id="add-new-card" value="add-new-card" onclick="addCard()"> <label class="form-check-label" for="add-new-card"> Add new payment method </label> <div id="new-card" style="display: none;"> <label class="block uppercase text-gray-600 text-xs mb-2" for="cardholder-name"> Name on Card </label> <input id="cardholder-name" class="mb-2 border-0 px-3 py-3 placeholder-gray-300 text-gray-600 bg-white rounded text-sm shadow focus:outline-none focus:ring w-full ease-linear transition-all duration-150" value="{{customer.name}}" detype="text"> <!-- placeholder for Elements --> <label class="block … -
Semantic UI active link with django not working properly
Thank you for trying to help. Here's my problem. I'm starting to do a simple blog project with Django and to learn something new for the styling I'm doing it with Semantic UI. In the menu, I tried to do the active links dynamically and did it with 'active link tags' in Django. It's working properly in the 'About' tab, but the 'Home' tab is constantly active. Here's my code in the template. <div class="ui pointing menu"> <a class="item {% active_link 'home' %}" href="{% url 'home' %}"> Home </a> <a class="item {% active_link 'about' %}" href="{% url 'about' %}"> About us </a> </div> Here is how the menu looks like when I'm on 'About' -
Django - Get image link from form and save to database
My form: <label class="label-input100" for="imagelink">Image Link*</label> <div class="wrap-input100"> <input id="imagelink" class="input100" type="text" name="imagelink" placeholder="Please paste an image link of the item you are donating" required> <span class="focus-input100"></span> </div> I want the user to paste an image link in the input box (For example, https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80), and then have Django associate it with an imagefield, save it, and then I can render it out on another page. My view: (There is a lot of stuff here that do not pertain to my question, I just included it in case it is needed) def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] date = datetime.datetime.now().date() ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, date = date ) ins.save() # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1) UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2)) return HttpResponseRedirect( '/thankyou/', ) return render(request,'donate.html') As you can see above, this view takes data from other parts of the form, and saves them to the database. I am not sure how to do it with the imagelink part of the form, i … -
How to make a user loged in (authenticated) in django with Reactjs? i'm using Django rest api to connect django and react
Here is the view i created in Django Views to verify the if the user is authenticated or not, but even if the user is valide, whene i try to get the currect user i get Null class LoginView(APIView): def get(self,request): data = request.data usr = authenticate(username=data["username"], password=data["password"]) if usr in not None: login(request,usr) return Response(status=status.HTTP_200_OK) else: return Response(status = status.HTTP_404_NOT_FOUND) -
Is it posssible to have a terminal that can ssh using iframe?
I am trying to make a website where you are able to access a docker container using ssh, Is there any way to have a window in the website that shows a terminal. (I was trying to use iframe but had no luck) -
How to display Data of foreign key in Django html page?
I want to display a Company header and the products below its related company. I am new to django i do not understand this fully. My models.py class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return str(self.name) class Products(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display") engine = models.CharField(max_length=250, blank=True) cyl = models.CharField(max_length=250, blank=True) bore = models.CharField(max_length=250, blank=True) def __str__(self): return str(self.engine) + " (ref:" + str(self.ref) + ")" My views.py: def Companies(request): context = { 'categories': Company.objects.all() } return render(request, 'product_list.html', context) My html: {% for category in categories %} <h2>{{ category.name }}</h2> {% for item in category.item_set.all %} {{ item_engine }} {% endfor %} {% endfor %} -
how to display an image from a url in django
I am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database. I want to collect an image url, save it to the database, and render it on a separate page. How would I go about doing this? This is the form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> -
Psycopg2-binary issue
Using Django and using the psycopg2-binary library, and a postgres DB, when i try to makemigrations I get the following error-- ```/Users/renoaverill/codePlatoon/week7/django-todo/project/venv/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but wrong architecture``` any and all help will be much appriciated! -
Apply filtering in Django-admin inline section
I'm stuck in filtering my Django-admin section using NestedTabularInline. Trying to get it right using a custom Modelform. I want to filter the plan method on the selected plan activity parent. 2 problems: The print(filter_id) generates only output when the first relation is stored in the database, which makes sense. But off-coarse you want to filter your first planmethod as well. I can't figure out how to create the queryset correctly. get(id=11) works but I need to plug in the self.instance in some way. Some suggestions needed here. model.py: class Activity(models.Model): activity = models.CharField(max_length=30, default=0) def __str__(self): return self.activity class Method(models.Model): method = models.CharField(max_length=30) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True) def __str__(self): return self.method class PlanActivity(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE, null=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE, null=True) position = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('position', ) class PlanMethod(models.Model): planactivity = models.ForeignKey(PlanActivity, on_delete=models.CASCADE, null=True) method = models.ForeignKey(Method, on_delete=models.CASCADE, null=True) position = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('position', ) admin.py: class PlanMethodAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(PlanMethodAdminForm, self).__init__(*args, **kwargs) filter_id = self.instance.planactivity_id print(filter_id) self.fields['method'].queryset = Method.objects.filter(activity_id=PlanActivity.objects.get(id=11).activity_id) class PlanMethodAdminInline(SortableHiddenMixin, NestedTabularInline): model = PlanMethod sortable_field_name = "position" extra = 0 form = PlanMethodAdminForm class PlanActivityAdminInline(SortableHiddenMixin, NestedTabularInline): model = PlanActivity sortable_field_name = "position" … -
Django - Filter for Multiple Foreign
Assume I have models like so: class Story(...): name = models.CharField(...) class Chapter(...): title = models.CharField(...) story = models.ForeignKey('Story', ..., related_name='chapters') How can I filter for stories that have chapters with N specifc titles, i.e.: titles = ['Beginning', 'Middle', 'End'] # is there a better way to do this? stories_with_these_chapters = Story.objects.filter( chapters__title = titles[0] ).filter( chapters__title = titles[1] ).filter( chapters__title = titles[2] ) -
How to retain all EXIF metadata in images on a Wagtail website?
Wagtail seems to clear all (EXIF) metadata in generated thumbnails and custom sized copies of an image. Is this correct? Is there a simple Wagtail way, in leaving all the image metadata? (SEO, Copyright...) Thank you! -
How to get a Groupby count for my django template tag?
I'm trying to get a total count of number of times a category has been used. @register.inclusion_tag('blog/components/categories_list.html', takes_context=True) def categories_list(context): categories = Category.objects.all() return { 'request': context['request'], 'categories': categories, 'categories_count': categories.count() } 'categories_count': categories.count() does not work, as it just counts the total amount of objects in categories Is there a simple way on doing this without working too much at the database level? I would like to get a count for the amount of times an object in categories has been used.