Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Ajax: HTTP404: NOT FOUND - The server has not found anything matching the requested URI
I'm beginner in Jquery. This way doesn't work. (Could not find URL) urls.py path('groups/<int:group_pk>/do_something', views.... js function doSomething(this) { var $this = $(this) var groupId = $group.data('id')[0] var userId = $group.data('id')[1] $.ajax({ url:'/groups/' + groupId + '/do_something', method: 'POST', data: { 'user_pk': userId}, beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } But this way did work. urls.py path('groups/<int:group_pk>/do_something/<int:user_pk>', views... js function doSomething(this) { var $this = $(this) var groupId = $group.data('id')[0] var userId = $group.data('id')[1] $.ajax({ url:'/groups/' + groupId + '/do_something/' + userId, method: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } What is wrong with the first way? I don't want to include userId in url if possible. Or do I have to include all parameters I want to pass to views in url? -
How to connect to the Database with Django but without web-server architecture?
My goal is to launch a piece of Python(2.7) + Django code in AWS with no web-server architecture. I need Django only to make requests to the Database. I am looking to some tutorial or article to connect the Database via Django, but without Django web-server architecture. I didn't find any tutorials about it. Please, advice me where to read about it ? -
I have list of N items. need to show every four item in different divs
I need to implement a carousel/slider. which has to display max four items in a row and than next slides have 4 items and so on. I have a list of items from back end and want to show first 4 elements of it in 1st slide and than next 4 items in next slide and so on. I have html template which is showing hard coded items but I want to show dynamic data here (Loop on item div for next slides and inside loop on col-md-3 div to show 4 items in a slide ). <div class="carousel-inner"> <div class="item active"> <div class="row"> <div class="col-md-3"> <div class="item-slider"> <a class="thumbnail" href="#"><img alt="" src="{% static 'images/t1.jpg' %}"></a> <div class="item-cont"> <h3>Title</h3> <p>Description</p> <a href="#" class="btn orange-btn btn-block more-btn" data-toggle="modal" data- target="#tenants1">More Details</a> </div> </div> <div class="col-md-3"> <div class="item-slider"> <a class="thumbnail" href="#"><img alt="" src="{% static 'images/t1.jpg' %}"></a> <div class="item-cont"> <h3>Title</h3> <p>Description</p> <a href="#" class="btn orange-btn btn-block more-btn" data-toggle="modal" data- target="#tenants1">More Details</a> </div> </div> </div> </div> /// AGAIN LOOP ITERATION ON ITEM DIV FOR NEXT SLIDE. <div class="item active"> <div class="row"> <div class="col-md-3"> <div class="item-slider"> <a class="thumbnail" href="#"><img alt="" src="{% static 'images/t1.jpg' %}"></a> <div class="item-cont"> <h3>Title</h3> <p>Description</p> <a href="#" class="btn orange-btn btn-block more-btn" data-toggle="modal" … -
How to fix Django error while sending emails
I've been trying to integrate django's smtp emails into my project but I can't seem to get it to work. I set Fail_Silently = False and it's not returning any errors when I send the email when means it's working but the email isn't going through to the email. SETTINGS.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'xxxxxxxxxx@gmail.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxxx' ` views.py: from django.core.mail import send_mail from django.conf import settings datatuple = ( ('hello there', 'Message.', 'xxxxxxx@gmail.com', ['xxxxxxxx@yahoo.com']), ('hello there', 'Message.', 'xxxxxxx@gmail.com', ['xxxxxxxx@gmail.com']), ) send_mass_mail(datatuple) As I said it won't fail and it also won't send the email -
Django: Form doesn't render first_name and last_name fields
I've a form for signing up users. It extends from User model. And I'm adding just first_name and last_name fields = ('first_name', 'last_name', 'username', 'password1', 'password2') But only last 3 fields render normally, first_name and last_name render when submitting because these are required fields and are shown only when the error messages appear. Why? from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) class Meta: model = User fields = ('first_name', 'last_name', 'username', 'password1', 'password2') ḦTML that renders: <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="dcvbbunvCBGL8Vttys2B4Gww1KWF6OcAX89RqU8pP5GmUGW3M9JwsTKZ7hU8CZ8r"> <div class="row"> <div class="col-md-6"> <tr><th><label for="id_username">Username:</label></th><td><input type="text" name="username" maxlength="150" autofocus required id="id_username"><br><span class="helptext">Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.</span></td></tr> <tr><th><label for="id_password1">Password:</label></th><td><input type="password" name="password1" required id="id_password1"><br><span class="helptext"><ul><li>Your password can&#39;t be too similar to your other personal information.</li><li>Your password must contain at least 8 characters.</li><li>Your password can&#39;t be a commonly used password.</li><li>Your password can&#39;t be entirely numeric.</li></ul></span></td></tr> <tr><th><label for="id_password2">Password confirmation:</label></th><td><input type="password" name="password2" required id="id_password2"><br><span class="helptext">Enter the same password as before, for verification.</span></td></tr> </div> </div> <div class="row"> <button class="btn btn-secondary" type="submit">Registrarse</button> </div> </form> But when I do this in manage.py shell, I get the correct fields: >>> from shop.forms import SignUpForm >>> user_form = SignUpForm() >>> user_form.as_p() … -
Django [Errno 22] Invalid argument
I am new to Django. Please excuse me if this is too silly a question. I'm running into OSError at /topics/ when trying to navigate to the topics page. Below is my urls: from django.conf.urls import url from . import views urlpatterns = [ # Home Page url(r'^$', views.index, name = 'index'), #Topics Page url(r'^topics$', views.topics, name = 'topics'), ] views: from django.shortcuts import render from .models import Topic # Create your views here. def index(request): '''This function returns the requested view of index to the browser. ''' return render(request, 'learning_logs\index.html') def topics(request): '''This function is to show all the topics. ''' topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs\topics.html', context) The error I'm getting is on the page and not when running python manage.py runserver The error comes only when I open the topics page and appears on the page itself. I have not had this issue when I open the index page. -
how to access User and UserProfile in TemplateView
User Model is inbuilt auth table and UserProfile Model is extended OneToOneField. Now i am get user_company from url which is stored in UserProfile but i also want data from User Model also. The bellow code i am trying but it gives error type object 'User' has no attribute 'UserProfile' User.UserProfile.objects.filter(user_company=id_) -
Not deploying on pythonanywhere
I have tried to deploy according to this : https://tutorial.djangogirls.org/en/deploy/ But it is not deploying . I think the problem is that in my repo the whole django project is present inside a folder which cannot directly accesible. So how can i overcome this problem. -
how to fixed 'page not found' using django forms
Please help with the following error: I get the error after posting the form Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/beam_diagram/ I want to redirect to another view after saving data using a form. everything works fine without the test_id views.py def new_beam(request, test_id): if request.method == 'POST': print("test1") beam_lengthform = beam_lengthForm(request.POST) if beam_lengthform.is_valid(): beam_length = beam_lengthform.cleaned_data['beam_length'] beam = beam_lengthform.save(commit=False) beam.beam_length = beam_length beam = beam_lengthform.save() return redirect('new_beam:beam_diagram', beam_id=91) else: beam_lengthform = beam_lengthForm() context = { 'beam_lengthform': beam_lengthform, } return render(request, 'new_beam.html', context) urls.py app_name = 'new_beam' urlpatterns = [ url(r'^(?P<test_id>\d+)$', views.new_beam, name='new_beam'), ] -
NoReverseMatch at URL after adding url.py entries for shopping cart
I have a basic django site with two apps, 'main page' and 'shopping cart'. I recently added in a shopping cart after following a basic tutorial, and it sems the url entries for the cart have broken the existing url entries I had. I had it setup so that a url could be visitied such as /bedroom/collection/id, and it would show details for the collection that matched id, which is passed in the url. My urls.py from my main page app: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^bedroom/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'), url('bedroom/', views.bedroom_view, name='bedroom_view'), ] This all worked fine. However, now after adding in my urls.py from my shopping cart application: urlpatterns = [ url(r'^$', views.cart_detail, name='cart_detail'), url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'), url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'), ] I get the following error: NoReverseMatch at /bedroom/collection/181 Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['add/(?P<product_id>\\d+)/$'] Why are the cart urls affecting my urls for my main_page app, and how can I resolve this? -
Multiple Model data to display in single template
i am using django detail view to display single company detail. But now i want to display on the same template list of users who are employee of that company. But i am using User Auth table. How can i display multiple view like detail view for company and list view for users of that company. class CompanyDetailView(LoginRequiredMixin, generic.DetailView): model = Company template_name = 'company/company-detail.html' context_object_name = 'companies' class UserListView(LoginRequiredMixin, generic.ListView): model = User template_name = 'users/users.html' context_object_name = 'users' User should be displayed only of that company -
Monkeypatching clean() method in a django Form Class
I use Django 2.1 on python 3.6 with pytest-django 3.4 I like to test the clean() method of a form defined like this : from django.forms import HiddenInput, ModelForm, ValidationError from log.models import Entry class EntryForm(ModelForm): class Meta: model = Entry fields = ['user', 'contact', 'title', 'desc'] widgets = { 'user': HiddenInput(), 'contact': HiddenInput(), } def __init__(self, *args, **kwargs): """ Get back user & contact obj for `self.clean()` """ user = kwargs.pop('user') contact = kwargs.pop('contact') super(EntryForm, self).__init__(*args, **kwargs) self.fields['user'].initial = user self.fields['contact'].initial = contact def clean(self): """ Checks if a entry is added on a contact owned by the connected user """ cleaned_data = super(EntryForm, self).clean() if 'user' in self.changed_data or 'contact' in self.changed_data: raise ValidationError("Hidden input changed") if cleaned_data['contact'].user != cleaned_data['user']: raise ValidationError("Not allowed") Outside tests, in a browser, this work as charm even if I change the values of hidden inputs : the ValidationError is raised. I think about using monkeypatch but I did not understand how to inject my test conditions in a django class… I use my feelings to build this test, but I cannot raise the expected ValidationError : def fake_entry_form__init__(): self.fields['user'].initial = 'initial user' self.fields['contact'].initial = 'initial contact' def fake_entry_form_unvalid_changed_data(): return { 'user': 'foo … -
Displaying Audio/Video in Python Django Website
I am building a blog website where I can upload audio/video files to the database and then run a for loop to output the files in HTML audio/video tags. I have succeeded in saving the files to the database and also output them on the website but for some reason I can't get them to play. I am still pretty new to Python/Django and I would appreciate it if anybody can help me figure this one out. Thanks in anticipation Here is my models.py from django.db import models class Track(models.Model): track_title = models.CharField(max_length=250) track = models.FileField(upload_to='album/') def __str__(self): return self.track_title Here is my index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> {% for track in tracks %} <figure> <figcaption>Audio</figcaption> <audio controls> <source src="{{ track.track.url }}" type="audio/mp3"> </audio> </figure> {% endfor %} This is my views.py from django.shortcuts import render from .models import Track def songView(request): tracks = Track.objects.all() context = { 'tracks':tracks } return render(request, 'album/index.html', context) And my urls.py from django.urls import path from . import views app_name = 'album' urlpatterns = [ path('', views.songView, name='song'), ] -
Django 'dict' object has no attribute
I make the queries to get the total of apple by month. Now I want get and print the data of total_apple. fruits= Fruits.objects\ .annotate(month = TruncMonth('sold_date'))\ .values('month')\ .annotate(total_apple=Sum('apple'))\ .order_by('-month') I've tried many ways to print it but returned an error. I've tried: 1) total_apple= fruits['total_apple'] print(total_apple) 2) context['total_apple'] = total_apple print(context) An error returned: No exception message supplied 3) print(fruits.total_apple) Error returned: 'QuerySet' object has no attribute 'total_apple' But when I tried print(fruits), it returned queryset that contain the attributes that I want. <QuerySet [{'month': datetime.date(2018, 10, 1), 'total_apple': 1636}, {'month': datetime.date(2018, 9, 1), 'total_apple': 1658},.....> -
AttributeError: 'tuple' object has no attribute 'get' in views.py
i want to create a registration form but i m getting an attribute error while running the application from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoForm def index(request): return render(request,'basic_app/index.html') def register(request): registered=False if request.method=="POST": user_form=UserForm(data=request.POST) profile_form=UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_from.is_valid(): user=user_form.save() user.setpassword(user.password) user.save() profile=profile_form.save(commit=False) profile.user=user if 'profile_pic' in request.FILES: profile.profile_pic=request.FILES['profile_pic'] profile.save() registered=True else: print(user_form.errors,profile_form.errors) else: user_form=UserForm() profile_form=UserProfileInfoForm() return(request,'basic_app/registration.html', {'user_form':user_form, 'profile_form':profile_form, 'registered':registered}) output attribute error: 'tuple' object has no attribute 'get' -
Tutorial to create basic django shopping cart incorrect? No models added just migrations?
I am following the tutorial here to create a basic shopping cart. Something I noticed is there is no step to modify models.py in the new shopping cart app, and instead to modify cart.py in the migrations folder of the new app. I named my app shop_cart instead of just cart, and if I try to run makemigrations or migrate, I get an error in shop_cart/views.py that: ModuleNotFoundError: No module named 'shop_cart.cart' Is this a mistake in the tutorial, or am I doing something wrong? -
Is there anything in koa working as transaction.atomic() in django?
We need some atomic code segment in nodejs(we use koa2) when dealing with db(we use MySQL) with lock, but it seems we can only use 'select xxx for update' in sql. We need to lock more before 'xxx for update', just like 'with transaction.atomic():' in django. But we only find 'redlock' to solve it. However, redlock seems to terminate the process instead of blocking it when the resources are locked. We have to use polling method after catching the exception. We just need a better way to implement this, just like transaction.atmoc() in django. So what should we do? -
When trying to install JWT package for Django getting error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
I was working on django project where i had received an error ImproperlyConfigured: Error importing middleware erp.middleware: "No module named jwt" So that i tried to install jwt package by typing pip install jwt which leads to an error build/temp.linux-x86_64-2.7/_openssl.c:3551:13: warning: ‘_ssl_thread_locking_function’ defined but not used [-Wunused-function] static void _ssl_thread_locking_function(int mode, int n, const char *file, ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Rolling back uninstall of cryptography Command "/home/charles/.virtualenvs/virtualenvpython/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-hU6Fxe/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-h5K4aB/install-record.txt --single-version-externally-managed --compile --install-headers /home/charles/.virtualenvs/virtualenvpython/include/site/python2.7/cryptography" failed with error code 1 in /tmp/pip-install-hU6Fxe/cryptography/ i dont what issue is going on please help me to solve this issue i am using ubuntu 18.04 LTS python 2.7.15rc1 django 1.3.7 -
Django custom user model : User creation issue
I am have created a custom user model to replace username with email. But when I am trying to add user from Django Admin I get error: Please correct the errors below. There is no other information with that error message. The code for custom user: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="email_address", max_length=255, unique=True, ) name = models.CharField(max_length=255) is_staff = models.BooleanField( default=False, ) is_active = models.BooleanField( default=True, ) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_full_name(self): return self.name def __str__(self): return self.email Custom User Manager Code: class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) and the admin code for same: class CustomUserAdmin(BaseUserAdmin): add_form = CustomUserCreationForm form = CustomUserCreationForm list_display = ('id', 'email', 'is_superuser') list_filter = ('is_superuser',) fieldsets … -
django-exel : Save to model.FileField a generated xls
Using the package django-excel, I have generated an xls file: sheet = excel.make_response(sheet, 'xls', file_name="myfile") It creates an HttpResponse in order to download the file. But I want to save this generated file in a model with a FileField. How can I pass the file from this HttpResponse to my FileField? -
Async in django rest framework
How to implement asynchronous tasks in Django rest framework? After python3.7 async.io became part of the python language and coroutines are embedded in the language . But I can’t make use out of it i had to use celery and a redis server for such async behavior. -
How to Filter foreign key id on the base different foreign Key ID
My Models: from django.db import models # Create your models here. class Heads(models.Model): head=models.CharField(max_length=100,unique=True,verbose_name="Head") def save(self, *args, **kwargs): if Heads.objects.count() ==5: return super(Heads, self).save(*args, **kwargs) def __str__(self): return self.head class Sub_Heads(models.Model): head=models.ForeignKey(Heads,on_delete=models.CASCADE) sub_head=models.CharField(max_length=100,unique=True,verbose_name="Sub Head") def __str__(self): return '%s %s' % (self.head, self.sub_head) class Elementary_Heads(models.Model): elementary_head=models.CharField(max_length=100,unique=True,verbose_name="ELementary Head") head=models.ForeignKey(Heads,on_delete=models.CASCADE) sub_head=models.ForeignKey(Sub_Heads,on_delete=models.CASCADE) I want to filter my sub_head on the base of head. Is there any way i can achieve this task. Let me know My admin.py from django.contrib import admin from .models import Heads,Sub_Heads,Elementary_Heads # Register your models here. admin.site.register(Heads) admin.site.register(Sub_Heads) admin.site.register(Elementary_Heads) -
Django filter by many to many exact same query
Is there any way in django to filter objects with many to many relation by query set or ids list. Get query with exactly same values in many to many. model class Parent(models.Model): name = models.CharField(max_length=1000) child = models.ManyToManyField(Child, blank=True) views def filter_parents(request): children = Child.objects.filter(id__in=[1,2,3]) parents = Parent.objects.filter(child=child) return parents expected: I am looking for filtered parents with exact same children in many to many field -
Django Crispy Form Not Show Django-Multislelectfield Required Error
I have a Crispy Form and a simple CreateView that have some fields. all field validations work correctly but crispy form does not show validation errors raised by Django-Multiselectfield I can see errors in the template with {{ form.errors }} that returns: available_guarantee - This field is required. deal_type - This field is required. status - This field is required. MyForm Code: class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout( Fieldset( _('About the Project'), 'name', 'location', 'location_type', 'sector', Div('status', css_class='with-checkbox'), 'revenue_generation_year', 'total_cost', 'previous_fund', ), Fieldset( _('Transaction'), 'fundraising_goal', Div('deal_type', css_class='with-checkbox'), 'payback_duration', 'collateral_rate', Div('offered_stake', css_class='with-checkbox'), Div('available_guarantee', css_class='with-checkbox'), ), Fieldset( _('Financial Details'), 'adscr', 'debt_equity_ratio', 'irr', ), Fieldset( _('About You'), 'owner_role', Div('have_mandate', css_class='with-checkbox'), ), Fieldset( '', 'description', ), Div( FormActions( Submit('save', _('Save changes'), css_class='btn-primary')), css_class='form-actions')) class Meta: model = Project fields = '__all__' ProjectCreateView: class ProjectCreateView(LoginRequiredMixin, CreateView): model = Project form_class = ProjectForm def get_success_url(self): return reverse('accounts:user-projects') def form_valid(self, form): form.instance.owner = self.request.user form.instance.state = Project.DRAFT_STATE form.instance.language = get_language() return super(ProjectCreateView, self).form_valid(form) Versions: Django 2.0 django-multiselectfield 0.1.5 django-crispy-forms 1.7.2 (with bootstrap4 pack) things I did until now: Tried to add Required to Model Field (result: django-multiselect not get required attribute) played with crispy form … -
Django Rest Framework: serializer response error
i have a problem with my viewset in DRF: def get_queryset(self): """ :return: filtered queryset based on request query_param """ # todo#amedeo: improve the readability code qs = super(ChecklistViewSet, self).get_queryset() _pk = self.kwargs['pk'] if self.request.method == 'PUT': instance = qs.filter(pk=int(_pk)).first() # pass in the instance we want to update serializer = ChecklistSerializer(instance, self.request.data) # validate and update if serializer.is_valid(): serializer.save() serializer_dict = serializer.data serializer_dict["message"] = "Checklist updated successfully." return response.Response(serializer_dict, status=status.HTTP_200_OK) else: return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) in my code the objetc was saved, but the response give an error that say: AttributeError: 'Response' object has no attribute 'model'