Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The current path, product/, didn't match any of these
I am having trouble with connecting to url code. Everything is showing fine but after I tried to create, this error message pops up. Also, I would like to know if path function works on the django 1.x. '''error message''' Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/product/ Using the URLconf defined in seany.urls, Django tried these URL patterns, in this order: ^admin/ ^$ ^register/$ ^login/$ ^product/create/ The current path, product/, didn't match any of these. '''url.py''' from django.conf.urls import url from django.contrib import admin from seany_user.views import index, registerview, loginview from seany_product.views import productlist, productcreate urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^register/$', registerview.as_view()), url(r'^login/$', loginview.as_view()), url(r'^product/create/', productcreate.as_view()) ] '''form.py''' from django import forms from seany_product.models import seanyproduct class registerform(forms.Form): name = forms.CharField( error_messages={ 'required': 'enter your goddamn product' }, max_length=64, label='product' ) price = forms.IntegerField( error_messages={ 'required': 'enter your goddamn price' }, label='price' ) description = forms.CharField( error_messages={ 'required': 'enter your goddamn description' }, label='description' ) stock = forms.IntegerField( error_messages={ 'required': 'enter your goddamn stock' }, label='stock' ) def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') price = cleaned_data.get('price') description = cleaned_data.get('description') stock = cleaned_data.get('stock') if name and price and description and stock: seany_product = product( … -
csrf and cors errors in localhost development of webpacked vuejs/reactjs/angularjs website with django backend
How can I run my vuejs application on localhost and have it send its API calls to my deployed django rest framework backend without getting cors and csrf issues? So far I have these issues: I can't read the cookie from browser because it's domain is not set to localhost. I need that to set the X-CSRFTOKEN header for django. I get CORS errors since localhost is not the same origin as my domain(example.com) I get error that referer does not match. -
How to crop images in django if I already have the cropping data (x,y,etc) coordinates?
I have an app where users would upload images and may crop a part of it so I added cropper.js to capture the coordinates and used a pillow code to crop it , I found it in this blogpost but nothing changes in the images I checked the data type of the coordinates and checked everything and nothing happened. from PIL import Image def crop(corrd, file ,path): image = Image.open(file) cropped_image = image.crop(corrd) resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS) resized_image.save(path) return file if form.is_valid(): image = form.save(commit=False) x = float(request.POST.get('x')) y = float(request.POST.get('y')) w = float(request.POST.get('width')) h = float(request.POST.get('height')) print(x) print(y) print(w) print(h) crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) so what I'm doing wrong here? I tried using opencv but i ran into issues/errors I couldn't fix. -
OSError at /en/ Django Saleor webpack error
I am trying Django Saleor to experience ECommerce framework. But I get this error. And I even tried finding the project root, I couldn't find webapck-bundle.json. This is the error of my django debug page OSError at /en/ Error reading /workspace/saleor/saleor/webpack-bundle.json. Are you sure webpack has generated the file and the path is correct? -
Django ReactJS bundle file not getting building with docker
I am learning docker and dockerizing my Django-react app! It is working now great except an issue and that is the bundle.js file are not getting Django when i run the project through dockcer But bundle.js files are found if run the project without docker! I guess, docker bundle the javascript in a different directory, that is why it is not getting if run with docker! this is my settings.py file STATICFILES_DIRS = [ os.path.join(os.path.join(BASE_DIR, os.pardir), 'dist'), ] and my Dockerfile is given below: FROM node:8 # Name work directory, it can be whatever you want WORKDIR /app COPY . ./ RUN yarn RUN npm run build # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and this is my dockcer-compose.yml file version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python backend/manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db volumes: postgres_data: Please know the problem … -
I'd like to know if the ManyToMany Field for each post contains a user ID in django
I'm trying to make a blog web. I want to change the color of the 'like it button' like Instagram depending on whether users like it or not. But I don't know how to build this. views.py def list(self, request, *args, **kwargs): user = request.user if not user.is_authenticated: return redirect('blog:signup') else: response = Blog.objects.filter(owner=user.id) return Response({'posts': response, 'user': user}, template_name='blog/blog_list.html') models.py class Blog(models.Model): title = models.CharField(max_length=255) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) templates {% for post in posts %} <button type="button" class="like" name="{{ post.pk }}" > {% if post.likes.exist %} <img class="float-left card-icon mx-1 like-img" src="{% static 'blog/like.png' %}" alt=""> {% else %} <img class="float-left card-icon mx-1 like-img" src="{% static 'blog/favorite.png' %}" alt=""> {% endif %} </button> I'm trying to filter in the template. but post.likes.exists is not what I want. This code below is what I exactly want. x = user.likes.through.objects.filter(blog=obj.id, user__id=user.id).exists() Can I implement this code as a template code? Or is there another solution to this? Thank you! -
Django Rest Framework: URL for associated elements
I have the following API endpoints already created and working fine: urls.py: router = DefaultRouter() router.register(r'countries', views.CountriesViewSet, base_name='datapoints') router.register(r'languages', views.LanguageViewSet, base_name='records') Now, I need to create a new endpoint, where I can retrieve the countries associated with one language (let's suppose that one country has just one associated language). For that purpose, I would create a new endpoint with the following URL pattern: /myApp/languages/<language_id>/countries/ How could I express that pattern with the DefaultRouter that I'm already using? -
Implementing PostgreSQL HStore in Django
I found some couple of packages to implement PostgreSQL HStore in Django from djangopackages.org. The most stared and most forked package was last updated in March 2, 2017. I think it is not maintained regularly. But as it at the top of the list I am confused about that should I use it in my project or there is a better option for me. Which is the best and handy way to implement PostgreSQL HStore in Django? -
Django rest-auth custom login form - not recognising inputted email: "Must include \"email\" and \"password\"."
I wrote a very simple custom login form over the rest-auth LoginView like below: view class CustomLoginView(LoginView): def get(self, request): form = CustomUserLoginForm() print(form.get_user()) return render(request, "api/test_template.html", context={"form": form}) form class CustomUserLoginForm(AuthenticationForm): class Meta: model = CustomUser fields = ('email', 'password') template {% block content %} <div class="container"> <form method="POST"> {% csrf_token %} <div> <label for="{{ form.email.id_for_label }}">Email: </label> <input type="email" {{ form.email }}> </div> <div> <label for="{{ form.password.id_for_label }}">password: </label> <input type="password" {{ form.password }}> </div> <button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Login</button> </form> Don't have an account? <a href="/register" target="blank"><strong>register here</strong></a>! </div> {% endblock %} In my settings.py i am making sure that the email is required and username is not: ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` "django.contrib.auth.backends.ModelBackend", # `allauth` specific authentication methods, such as login by e-mail "allauth.account.auth_backends.AuthenticationBackend", ) When I go to enter my email and password and then submit the form, Django rest-auth framework gives the below error: As a test, I then input the same email address in the provided field in the browserable API and I manage to log-in successfully. Why does rest-auth not recognize the … -
Using multiple models for django ecommerce cart
I'm making a cart for an ecommerce project that I am working on, at the moment the cart does work. However it only works for one model and I'm not sure how to make it work with more than one. This is my contexts.py file in my cart folder: from django.shortcuts import get_object_or_404 from courses.models import Course from food_order.models import Food_order def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 course_count = 0 for id, quantity in cart.items(): course = get_object_or_404(Course, pk=id) total += quantity * course.price course_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'course': course}) return {'cart_items': cart_items, 'total': total, 'course_count': course_count} Here is my views.py from django.shortcuts import render, redirect, reverse # Create your views here. def view_cart(request): """A View that renders the cart contents page""" return render(request, "cart.html") def add_to_cart(request, id): """Add a quantity of the specified product to the cart""" quantity = int(request.POST.get('quantity')) cart = request.session.get('cart', {}) if id in cart: cart[id] = int(cart[id]) + quantity else: cart[id] = cart.get(id, quantity) request.session['cart'] = cart return redirect(reverse('index')) def adjust_cart(request, id): """ Adjust the quantity of the specified product to the specified … -
django default Authenticaiton form shows username rather than email
I implemented my own user login form with django like below from django.contrib.auth.forms import AuthenticationForm class CustomUserLoginForm(AuthenticationForm): class Meta: model = CustomUser fields = ('email', 'password') then as a view this is what I have: from rest_auth.views import LoginView from users.forms import CustomUserLoginForm class CustomLoginView(LoginView): def get(self, request): form = CustomUserLoginForm() return render(request, "api/test_template.html", context={"form": form}) in my template then, I am calling {{form.as_p}} in <form> tag to show the form input details. However, by default, this shows the username and password forms. How can I replace the username with the email? in the rest-auth, browserable api, both the username and the email are present so I know that I can do this since I am using the rest-auth LoginView as backend. Can I manually unpack {{form}} since later I would still like to style this form. How can I do this? -
Django drf_yasg POST with input parameters produces error - cannot add form parameters when the request has a request body
I'm trying to use Django drf_yasg to create a POST api with input parameters like below: x_param = openapi.Parameter('x', in_=openapi.IN_FORM, description='string', type=openapi.TYPE_STRING) @swagger_auto_schema(method='post', manual_parameters=[x_param]) @api_view(['POST']) def another_view(request): x_param = request.POST['x'] logging.debug("x_param = %s", x_param) return Response("I'm OK", status=status.HTTP_200_OK) pass however it produces this error in $ python manage.py runserver raise SwaggerGenerationError("cannot add form parameters when the request has a request body; " drf_yasg.errors.SwaggerGenerationError: cannot add form parameters when the request has a request body; did you forget to set an appropriate parser class on the view? How can I solved this ? -
how to specify in django form that we want certain value to be inserted in database via dropdown list
I am trying to save the name of the students in the database. Right now, it is saving the ID of the student instead of the name. I am using django form and i am not sure hw to tell the django form that i want to insert the student name in the database. Below is my forms.py code: class studentAttendanceForm(forms.ModelForm): class Meta: model = MarkAtt fields = ['studName'] def __init__(self,*args, **kwargs): class_group = kwargs.pop('class_group') super(studentAttendanceForm, self).__init__(*args,**kwargs) self.fields['studName'].label = "Select your name:" self.fields['studName'].queryset = Namelist.objects.filter(classGrp=class_group) Template: <h6 style=" display: inline;"> Lab Group: {{group.classGrp}} </h6> <h6 style="padding-left:70px; display: inline;">Day: {{group.day}} </h6> <h6 style="padding-left: 70px;display: inline;">Time: {{group.time}} </h6> <h6 style="padding-left: 70px;display: inline;"> Today's date: {{date.today}}</h6> <br> <br> {{ form.as_p }} <button type ="submit" class="btn btn-outline-success" >Mark Attendance</button> right now is saving as: id att studName classId week date 42 1 1 1 0 2019-09-15 i want to save as 42 1 testName 1 0 2019-09-15 -
PYTHON - DJANGO - 'ImageFieldFile' object has no attribute 'replace'
The error message is: AttributeError at /projects/ 'ImageFieldFile' object has no attribute 'replace' Request Method: GET Request URL: http://localhost:8000/projects/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'ImageFieldFile' object has no attribute 'replace' Exception Location: .../js-portfolio/venv/lib/python3.6/site-packages/django/utils/encoding.py in filepath_to_uri, line 252 Python Executable: .../js-portfolio/venv/bin/python Python Version: 3.6.8 Python Path: ['.../js-portfolio', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '.../js-portfolio/venv/lib/python3.6/site-packages'] I have a Project MODEL, that takes an image. I added the model to my admin page, and I created an object from admin and can add an image no problem. The problem happens when I try to display my views. I am not even making a reference to the image in base.html. I have been stuck on this for hours, so I figured it's time to get some help. Any hints would be greatly appreciated. Thanks! My Project model(models.py): from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.ImageField(default='default.jpg', upload_to='img') def __str__(self): return self.title My settings.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' base.html: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container"> <a class="navbar-brand" href="{% url 'project_index' %}">JS Portfolio</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> … -
Django how to use request data as form in an html template
I am using Django rest framework rest-auth for login and sign up. But I do not want to use the browseable API as my UI. I am building my own form. so I am using a custom login url like so: path('rest-auth/customlogin', CustomLoginView.as_view(), name='rest_login'), where CustomLoginView is defined as : class CustomLoginView(LoginView): def get(self, request): return render(request, "api/test_template.html") now in test_template.html, I would like to have 2 input fields: email and password. the same fields that are shown in the browserable API if I did not overwrite with the template. I am not sure how to get the request data into the template. (if email and password fields reside in the request data, is this correct?) test_template.html {% block content %} <div class="row"> <h3>Login</h3><hr/> {# I am not sure how to use input fields here where the data inputted goes in the email and password rest-auth fields#} </div> {% endblock %} -
Django background task set Creator content type and creator content id
Using "Django Background Tasks" module. It just set schedule time. Need to set content type and id. @background(schedule=60) def notify_user(user_id): # lookup user by id and send them a message user = User.objects.get(pk=user_id) user.email_user('Here is a notification', 'You have been notified') How to do that -
How to use parse_qs in redirecting from view to another?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. You can check the actual project in applypro.co and applypro.co/programs . please see that how get and … -
Please help - converting html5 into Django2.2.5 template, all worked except JS based img carousel that accepts URL as input parameter
I'm trying to convert an html5 code into django template, using best practices, such as {% static 'url/img.jpg' %} but the function is not getting triggered. I'm not very strong at JS or at css3 transitions. (Below is the actual HTML code that works correctly, calls javascript function and creates a sliding slider gallery): <section id="main-slider"> <div class="owl-carousel"> <div class="item" style="background-image: url(images/slider/bg1.jpg);"> <div class="slider-inner"> </div> </div> <!--/.item--> <div class="item" style="background-image: url(images/slider/bg2.jpg);"> <div class="slider-inner"> </div> </div> <!--/.item--> </div> <!--/.owl-carousel--> </section> (After converting to django template, the code looks like this): (So, the part of the code that successfully resolves into url is this: So, the structure is correct. The original template can be seen at this url: https://themehunt.com/item/1524960-multi-free-responsive-onepage-html-template and the javascript responsible for this image carousel is here: demo.themeum.com/html/multi/js/owl.carousel.min.js So the browser just doesn't show the section with images at all. -
how to add hyperlink href in pandas dataframe table when calling to_html() method using django template
i am using pandas dataframe to pass table to django template html , my python code : def my_get_method(request): q = "SELECT id,data from table" df = pd.read_sql(q,connection) df['id'] = df_products['id'].apply(lambda x: '<a target="_blank" href=' '"https://link_to.com/manage/inside_my_website/{id}/">{id}</a> return render(request,'manage/my_template.html', {'df':df.to_html(index=False,table_id="table-id",escape=False),) my_template.html: ... {% autoescape off %} {{ df }} {% endautoescape %} ... and table does shown but the id column has only one row(where if i don't apply the link it shows multiply rows) and the id is something i don't understand : '); $('input', this).on('keyup change', function () { if (table.column(i).search() !== this.value) { table .column(i) .search(this.value) .draw(); } }); }); var table = $('#table-id').DataTable({ orderCellsTop: true, fixedHeader: true, aLengthMenu: [ [10, 25, 50, 100, 200, -1], [10, 25, 50, 100, 200, "All"] ], iDisplayLength: -1 }); }); and in the python code the link in the dataframe seems ok. -
Converting sqlite db to rest api for android app using django rest framework
I have a sqlite db which consists images and descriptions now how can I create rest api from it using django rest framework. -
How to use form.save(commit=false) with ManyToManytoMany Field
Views.py @login_required def Movies_create(request): form=Create_Movies_form( data=(request.POST), files=(request.FILES or None), ) url=request.path[1:-5] if form.is_valid(): if request.user.is_active: obj = form.save(commit=False) obj.movies_user_id = request.user obj.save() messages.success(request, f'Movies has been created!') else: messages.warning(request, f'Please Login to create movies!') else: print(form.errors) context={ "form":form, "form_name":url } return render(request,'movies_list/list_create.html',context) forms.py class Create_Movies_form(forms.ModelForm): class Meta: model=Movies_list fields=['name','genre','cast','director','writer','awards','country','story_line','cost','release_date','language','imdb_rating','imdb_link','trailer_link','tags','Quality','movies_type',] models.py class Movies_list(models.Model): movies_id=models.AutoField(primary_key=True) name=models.CharField(max_length=50) genre=models.ManyToManyField(Genre_list) cast=models.ManyToManyField(Cast_list) director=models.ManyToManyField(Director_list) writer=models.ManyToManyField(Writer_list) awards=models.ManyToManyField(Award_list) country=models.ForeignKey(Country_list, on_delete=models.PROTECT) story_line=models.TextField(default='') cost=models.PositiveIntegerField(default=0) release_date=models.DateTimeField( blank=False,null=False) created_at=models.DateTimeField(default=timezone.now) language=models.ManyToManyField(Language_list) imdb_rating=models.FloatField() imdb_link=models.TextField() trailer_link=models.TextField() views=models.PositiveIntegerField(default=0) likes=models.PositiveIntegerField(default=0) dislike=models.PositiveIntegerField(default=0) ratting=models.FloatField(default=0.0) tags=models.TextField() Quality=models.ForeignKey(Quality_list,on_delete=models.PROTECT) movies_user_id=models.ForeignKey(User, on_delete=models.PROTECT) movies_type=models.ForeignKey(Movies_type_list,on_delete=models.PROTECT) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural='movies' It work just fine but didn't know why using obj = form.save(commit=False) didn't save ManyToMany modelform field in the sqlite database. It work fine with Foreignkey ,textfield,integerfield,datetimefield. I test it on multiple times to check whether it save the data or not by using update(instance) and template .html file. -
Datetime Field does not displayed on the page?
why does not datetime field error message not display on the page ? validation datetime message error not display on the page like other validation of other clean methods ? at models.py class Todo(models.Model): title = models.CharField(max_length=255) due_date = models.DateTimeField() description = models.TextField(max_length=255) is_done = models.BooleanField(default=False) duedate = models.DateField(default=timezone.now) def __str__(self): return self.title at forms.py class TodoModelForm(forms.ModelForm): class Meta: model = Todo # fields = ['title', 'description', 'due_date'] fields = '__all__' def clean_title(self): print('in title') title = self.cleaned_data['title'] words = title.split() if len(words) > 5: raise ValidationError('Must be Just 5 Words at Max') return self.cleaned_data['title'] def clean_description(self): print('In des') desc = self.cleaned_data['description'] words = desc.split() if len(words) > 5: raise ValidationError('Not Correct') return desc -
DRF, consistent api for foreignkey relations
Suppose you want to show nested data when reading. Also suppose that you want to only allow changing the id of the foreign key. Hence the following definition arises, but the problem is they use the same variable order_case and I get when updating via {"order_case": 477}. ValueError: Cannot assign "477": "OrderCaseRevision.order_case" must be a "OrderCase" instance. class OrderCaseRevisionSerializer(serializers.ModelSerializer): order_case = OrderCaseSerializer(read_only=True) order_case = serializers.IntegerField(write_only=True) I could do the following to mitigate the problem, but I don't like the fact that you usually use foreign key name like order_case to update the foreign key field and here you are making an exception that you have to use order_case_id. class OrderCaseRevisionSerializer(serializers.ModelSerializer): order_case = OrderCaseSerializer(read_only=True) order_case_id = serializers.IntegerField(write_only=True) -
Axios send request twice, 301 and 401 results in Django Rest Framework
I tried to call a REST api endpoint in my Django project. So far its working when using curl, postman. I have the problem when I tried calling it in my django template frontend with Axios. As I inspected network tab, I noticed it calling the api twice, first return 301, sending params and token successfully, and the second request return 401, sending params but not the token. axios.get(url,{headers: {'Authorization': 'Token 0ca677330f947335a72572bdbdfe305ae7dd8ba6'},params:params}) I also noticed the change in url in second request first request(301) - endpoint?param_a=value&param_b=value second request(401) - ?param_a=value&param_v=value I tried to prevent reload by adding modifiers in my form like .prevent, stop, etc nothing works. Any idea? -
Why django go on to clean datetime or date field?
when i use debugger, it does not go on this method, why ? def clean_duedate(self): import datetime date = self.cleaned_data['due_date'] try: date = datetime.datetime.strftime(date, '%m/%d/%Y') except Exception as error: print(error) raise ValidationError('not date') return date