Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When adding urlpatterns in Django, why is views.index called instead of views.index()?
I was wondering, in the url.py-files, why are parentheses not used when calling methods from the view.py-files? For example, why does the following code not have a parenthesis at the end of views.index? urlpatterns = [ url(r'^$', views.index, name='index'), ] -
django inline_formset - set queryset for a field based on another field
I have three models - Item, Invoice and InvoiceItem. Each Item may have one or more tax-groups (name,rate, etc) associated with them. class Item(models.Model): name=models.CharField(max_length=100, unique=True, db_index=True) tax_group=models.ManyToManyField(TaxGroup) class Invoice(models.Model): number=models.CharField("invoice number",max_length=20,unique=True,default=invoiceIncrement, ) date=models.DateField("invoice date") contact=models.ForeignKey(Contact, on_delete=models.CASCADE) total=models.DecimalField(decimal_places=2, max_digits=12) class InvoiceItem(models.Model): invoice=models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='invoice_items') item=models.ForeignKey(Item, on_delete=models.CASCADE) tax=models.ForeignKey(TaxGroup, on_delete=models.CASCADE) quantity=models.PositiveIntegerField() rate=models.DecimalField(decimal_places=2, max_digits=12) total=models.DecimalField(decimal_places=2, max_digits=12,null=True) I have made an inline_formset using the following form, as given below. class InvoiceItemForm(forms.ModelForm): class Meta: model=InvoiceItem exclude=() ItemInlineFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=1, can_delete=False, validate_min=True, min_num=1) Now, I need to make sure that, corresponding to each selected Item in the formset, the field tax should contain only the taxes associated with them. For the client side, I have added some ajax code to populate the tax fields based on selection of each item field. How do I make sure that the selected tax field is one among the ManyToMany value of the Item object? I have tried specified a custom formset to set a queryset to the field, like class BaseItemFormSet(forms.BaseInlineFormSet): def __init__(self, *args, **kwargs): super(BaseItemFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.fields['tax'].queryset = Item.objects.get(form.fields['item']).tax_group.all() This doesn't work (and I'm not sure whether this is the right way to proceed). Do I need to use a … -
Data table in Django template - Check data with multiple table
I'm building a subscription function using Django. Type A users create a lot of "program", Type B users can join this program. (Actually, Type B user need to provide their own website information to us first and they can have multiple website. So, it should be a user's website join a "program") I want to create a program list that show all the existing program and it has a "join button" / "joined label" after each program name. However, the join/joined label function is not work... Here is the related models.py # Type A users add program to this table class Program(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=128, unique=True, null=True, blank=True, default=None) program_id = models.AutoField(primary_key=True) status = models.PositiveSmallIntegerField(null=True, blank=True, default=1003) slug = models.SlugField(blank=True, unique=True) # Type B users add their website's info to this table class Website(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=128, unique=True, null=True, blank=True, default=None) website_id = models.AutoField(primary_key=True) url = models.URLField(max_length=200, null=True, blank=True, default=None) slug = models.SlugField(blank=True, unique=True) # When a Type B user join a program, it will write to this table class Subscription(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, null=True, blank=True) website = models.ForeignKey(Website, on_delete=models.CASCADE, null=True, blank=True) status = models.PositiveSmallIntegerField(null=True, blank=True, default=1003) created = … -
how to upload multiple images to a blog post in django using Ajax
Trying to add multiple images to BlogPost. The code below is for single image. I want to use the below link to change it to multiple images upload. Can anyone advise what changes I need to make to my code so I can add multiple images. I am new to django and this has been challenging me for a while https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html This is my Model for single image: class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') created_at = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() message_html = models.TextField(editable=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title) self.message_html = self.message super().save(*args, **kwargs) class Meta: ordering = ['-created_at'] unique_together = ('message', 'user') Below is my View.py for single image: class Postlist(SelectRelatedMixin, ListView): model = Post select_related = ('user', 'group') class UserPostList(ListView): model = Post template_name = 'posts/user_post_list.html' def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get(username__iexact=self.kwargs.get("username")) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super(UserPostList, self).get_context_data() context['post_user'] = self.post_user context['object_list'] = Group.objects.all() return context class PostDetail(SelectRelatedMixin, DetailView): model = Post select_related = ('user', 'group') def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user__username__iexact=self.kwargs.get('username')) class PostCreate(LoginRequiredMixin, … -
Django: Filter for Product Colour
I am trying to create a filter for product colours. Products are imported by csv and each colour drastically varies e.g camo, lilac, auburn. I want to create a filter with a selection of standard colours e.g red, blue green. When one of the standard colours is selected, I would like to query the database and return all products that contain that colour (or that are in that colour category). For instance if the colour blue was selected, the filter would return queryset of any products that contained the colours: blue, teal, turquoise, cyan, denim. I have tried to do this with django filter (choices) but have been unable to come up with a solution. Does anyone know the best approach for this? current product model class Product(models.Model): aw_deep_link = models.CharField(max_length=500, default='') product_name = models.CharField(max_length=500, default='') aw_image_url = models.CharField(max_length=500, default='') search_price = models.DecimalField(max_digits=6, decimal_places=2, null=True) merchant_name = models.CharField(max_length=500, default='') display_price = models.CharField(max_length=500, default='') brand_name = models.ForeignKey('Brand', on_delete=models.CASCADE) size = models.ForeignKey('Size', on_delete=models.CASCADE) colour = models.CharField(max_length=500, choices=COLOURS, default='') rrp_price = models.DecimalField(max_digits=6, decimal_places=2, null=True) category = TreeForeignKey('Category',null=True,blank=True, on_delete=models.CASCADE) description = models.CharField(max_length=500, default='') def __str__(self): return self.product_name current filters import django_filters from .models import Product, Brand, Category from django.forms import CheckboxSelectMultiple class ProductFilter(django_filters.FilterSet): search_price__gt … -
Display Code from ckeditor to website properly, django
So i want to display well formatted code as we see in stackoverflow, in my blog. While I paste my code in ckeditor under the code section, it is pretty good and well formatted. Like in the picture below. I want something like that to appear on my website. But when I save it and view it on my website, I get unformatted code. Like the picture below. Am I doing anything wrong here. Please help -
what does means?:NoReverseMatch at /post_detail/12/
this is traceback, Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post_detail/12/ Django Version: 2.0.4 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogs'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/am/Documents/PycharmProjects/practice/19.1_Blog/blogs/templates/blogs/base.html, error at line 0 Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>\\d+)/'] 1 : <p> 2 : <a href="{% url 'blogs:index' %}">My blogs</a> - 3 : 4 : <a href="{% url 'blogs:all_post' %}">All Post</a> 5 : </p> 6 : 7 : {% block content %} 8 : 9 : {% endblock content %} Traceback: File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/blogs/views.py" in post_detail 32. return render(request, 'blogs/post_detail.html', context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/loader.py" in render_to_string 62. return template.render(context, request) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/backends/django.py" in render 61. return self.template.render(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render 175. return self._render(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in _render 167. return self.nodelist.render(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render_annotated 910. return self.render(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/loader_tags.py" in render 155. return compiled_parent._render(context) File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in _render 167. … -
dictionary binding two different list
>>> a=[2,1] >>> b=['app','applied'] >>> f={} >>> for id in a: for name in b: f[id]=name the output is {2:'app', 1: 'app'} after i generated another for loop for c in f: print(c) Then output is 2,1 not show value and I tried for c,k in f: print(c,k) return error But i need both key and value Please help me I Tried many time cannot get solution. I bind two different list in dictionary but get only key value but value should only one value to bind in key. Please help me -
DRF Saving nested object and updating the other
I want to update entity and simultaneously create the other one using DRF and nested serializers. Both entities are connected with one-to-one relation with common "root" My models looks like: class Root(Model): ... class Node1(Model): root = OneToOneField(Root) class Node2(Model): root = OneToOneField(Root) In my scenario entity of Root and Node1 exists and I want to update node1 and create node2 in one HTTP request. I tried use serializers like this: class Node1Serializer(ModelSerializer): class Meta(object): model = Node1 fields = '__all__' class Node2Serializer(ModelSerializer): node1 = Node1Serializer(partial=True) # here I want update just few fields of node1 class Meta(object): model = Node2 fields = '__all__' I'm sending data by post like: {root: 1, entity2_param1: "...", "node1": {root: 1, id:1, entity1_param1: "..."}} In response I get that root must be unique. What is correct approach for this task? -
Django add comma in an array field using admin
I am working on a Django project on Postgres. I have added an ArrayList of CharField but would would like to insert data which contains sentences including the commma(',') but django admin separates the data of an ArrayField by using comma's. Tried using backslash but that didn't work. -
Django Postgres Make Migration Error
I have just deployed some code onto a production server from my local. I have set up a postgres database with a django app. The issue is when I run: $ python3 /usr/Apps/manage.py makemigrations I get the below error ################################################## Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.5/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "api_neli_report" does not exist LINE 1: ...ort"."price", "api_neli_report"."prediction" FROM "api_neli_ api_neli_report is a model I have set up that has not been migrated, as I can't migrate it without getting the error. Any idea how to fix this one? -
ValueError at / Invalid format string
i am making a blog website through Django! While adding the strftime for dates in my project, I am getting Value error! Here are the code in which i get error: models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField() body = models.TextField() image = models.ImageField(upload_to='images/') def summary(self): return self.body[:100] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') Here are the HTML code in which i get error: {% for blog in blogs.all %} <a href=""><h3 >{{ blog.title }}</h3></a> {{ blog.pub_date_pretty }} <br /> <img class="img-fluid" src="{{ blog.image.url }}" height =200 width=200 /> <br /> <p>{{ blog.summary }}</p> {% endfor %} -
Django Template Tag - how to check something in dictonary
I have a dict and I want to check for whether 'Life Style' exists or not when I simply write- {{result.object.category.main_category_of_sub.all}} it displays <QuerySet [<MainCategory: Life Style>]> for checking I tried this {% for x in result.object.sub_category.main_category_of_sub.all %} {% if x is 'Life Style' %} YES {% else %} {{x}} {% endif %} {% endfor %} but unfortunately nothing displayed ! -
Python tags in index.html ignored in Django project
I have the following in my views.py file def index(request): all_destinations = Destination.objects.all() template = loader.get_template('plan/index.html') context = { 'all_destinations': all_destinations, } return HttpResponse(template.render(context, request)) and the following index.html file in my templates directory. <ul> {% for destination in all_destinations %} <li><a href="/plan/{{ destination.id }}/"> {{ destination.destination_title }} </a></li> {% endfor %} </ul> The issue is anything between the {% %} and {{ }} tags is ignored by the browser. Any tips on why is this happening? -
serve() got an unexpected keyword argument 'docment_root'
from admin(http://127.0.0.1:8000/admin/) when i try to upload a image it show uploaded but when i click on link ( Currently: products/dd_nSSrD3Y.png) it show me serve() got an unexpected keyword argument 'docment_root',but when i check insite directory it show image. from admin(http://127.0.0.1:8000/admin/) when i try to upload a image it show uploaded but when i click on link ( Currently: products/dd_nSSrD3Y.png) it show me serve() got an unexpected keyword argument 'docment_root',but when i check insite directory it show image. from admin(http://127.0.0.1:8000/admin/) when i try to upload a image it show uploaded but when i click on link ( Currently: products/dd_nSSrD3Y.png) it show me serve() got an unexpected keyword argument 'docment_root',but when i check insite directory it show image. seetings.py STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,"static_my_proj"), ] STATIC_ROOT=os.path.join(os.path.dirname(BASE_DIR),"static_cdn","static_root") MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(os.path.dirname(BASE_DIR),"static_cdn","media_root") models.py from django.db import models class Product(models.Model): title=models.CharField(max_length=120) description=models.TextField() price=models.DecimalField(decimal_places=2,max_digits=20,default=38.25) #image=models.FileField(upload_to='producpts/',null=True,blank=True) image=models.ImageField(upload_to='products/',null=True,blank=True) def __str__(self): return self.title urls.py from django.contrib import admin from django.conf.urls import url from django.urls import path from products.views import ProductListView,ProductDetailView from ecommerce.views import home_page,about_page,contact_page,login_page,register_page from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path(r'home/',home_page), path(r'about/',about_page), path(r'contact/',contact_page), path(r'login/',login_page), path(r'register/',register_page), path(r'products/',ProductListView.as_view()), #path(r'products/(?P<pk>\d+)/$',ProductDetailView.as_view()), url(r'^products/(?P<pk>\d+)/$',ProductDetailView.as_view()), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns=urlpatterns+static(settings.STATIC_URL,docment_root=settings.STATIC_ROOT) urlpatterns=urlpatterns+static(settings.MEDIA_URL,docment_root=settings.MEDIA_ROOT) -
How to describe the many-to-many sql relation in Django models
I've create genres and books tables in mysql database create table genres ( gID varchar(20) not null, gName varchar(100) not null, primary key(gID) ); create table books ( ISBN varchar(20) not null, BookTitle varchar(255) not null, Description text, PageCount int not null, Rating numeric(3, 2), Language varchar(20), CoverImage varchar(255), Price numeric(5, 2), PublishedDate date, publisher_pID varchar(20) not null, VoteCount int default 0, primary key(ISBN), foreign key(publisher_pID) references publishers(pID) ); create table books_genres ( Book_ISBN varchar(20) not null, Genre_gID varchar(20) not null, primary key(Book_ISBN, Genre_gID), foreign key(Book_ISBN) references books(ISBN) on delete cascade, foreign key(Genre_gID) references genres(gID) on delete cascade ); I imported them in django using "python manage.py inspectdb > models.py", and then performed all the needed migrations. The imported models(edited a little bit): class Genres(models.Model): gid = models.CharField(db_column='gID', primary_key=True, max_length=20) # Field name made lowercase. gname = models.CharField(db_column='gName', max_length=100) # Field name made lowercase. class Meta: verbose_name_plural = "Genres" db_table = 'genres' class Books(models.Model): isbn = models.CharField(db_column='ISBN', primary_key=True, max_length=20) # Field name made lowercase. booktitle = models.CharField(db_column='BookTitle', max_length=255) # Field name made lowercase. description = models.TextField(db_column='Description', blank=True, null=True) # Field name made lowercase. pagecount = models.IntegerField(db_column='PageCount') # Field name made lowercase. rating = models.DecimalField(db_column='Rating', max_digits=3, decimal_places=2, blank=True, null=True) # Field … -
Choices in Django model not being translated, possibly due to use of modelform or modelformset?
I am working on a Django project that connects dogs with behavioral issues with people who can help the owner overcome those issues. Most of the project has been translated, but there are a few strings that aren't being translated. Here is the relevant model: from django.utils.translation import ugettext_lazy as _ class Issue(models.Model): PEOPLE = 'PE' OWNERS = 'OW' EXPERIENCED_PEOPLE = 'EX' HELPER_CHOICES = ((PEOPLE, _('People')), (OWNERS, _('Owners')), (EXPERIENCED_PEOPLE, _('People with experience'))) who_can_help = models.CharField(_('Who can help?'), blank=False, choices=HELPER_CHOICES, default=PEOPLE, max_length=2, null=False) doggo = models.ForeignKey(Doggo, on_delete=models.CASCADE) and the relevant bit in forms.py IssueFormSet = modelformset_factory(Issue, fields=['title', 'description', 'plan', 'who_can_help']) Finally, the view (I've left out the part for dealing with POST requests): def doggo_create_view(request): doggo_form = DoggoForm() issue_formset = IssueFormSet(queryset=Issue.objects.none()) return render(request, 'doggos/doggo_form.html', {'form': doggo_form, 'formset': issue_formset}) What I'm seeing is this: Instead of "People", it should say "Mensen" (as in the .po file, which I haven't forgotten to compile). Any ideas? -
Form not being saved when specifying initial data
The following form doesn't get saved and I don't know why. The goal is just to get the initial data so the user doesn't have to enter it again, and upon completion of the form save it to the model. views.py class GetSellData(View): form_class = MakeSale template_name = 'laptops/laptop_sale.html' def post(self, request, *args, **kwargs): #Get post data from 'laptopname' button laptopid = request.POST.get('laptopname') #Store laptopid for use somewhere else request.session['laptopid'] = laptopid #get matching laptop id laptop = Laptop.objects.get(id=laptopid) #specify intital data based on laptop id for pre-populating the form data = {'Name': laptop.Name, 'specification': laptop.specification, 'warranty': laptop.warranty,'condition':laptop.condition} form = self.form_class(initial=data) if form.is_valid(): instance = form.save(commit=False) instance.save() return render(request,'laptops/laptop_list.html') else: return render(request, self.template_name, {'form': form})' -
unable to Insert data in model with DateField in Django 2
Hi I am trying to insert data in student Attendance modelin Django2 but i am getting must be str, not datetime.date error. I tried to convert it to str but even though it work. models class Staff(models.Model): user_name = models.CharField(max_length=100,primary_key=True) StaffType = models.ForeignKey(StaffType, db_column='staff_type', on_delete=models.PROTECT) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) contact = models.CharField(max_length=20, unique=True) #unique can be set details = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.first_name+', '+self.last_name+' : '+str(self.StaffType) class Student(models.Model): Roll_Num = models.CharField(max_length=20,primary_key=True) Name = models.CharField(max_length=150) Address = models.CharField(max_length=200,default='') section = models.ForeignKey(Section, db_column='class_code', on_delete=models.CASCADE) def __str__(self): return self.Roll_Num+', '+self.Name class StudentAttendance(models.Model): student = models.ForeignKey(Student, db_column='Roll_Num', on_delete=models.CASCADE) Attend_date = models.DateField('Date', default=date.today(), auto_now=False, auto_now_add=False, db_index=True) staff = models.ForeignKey(Staff, db_column='user_name', on_delete=models.DO_NOTHING) def __str__(self): return str(self.student)+' : '+str(self.staff) Here is Error Log Django Version: 2.0.3 File "C:\ProgramData\Anaconda3\lib\site-packages\django\contrib\admin\options.py" in log_addition 771. object_repr=str(object), File "C:\Users\sudha\Documents\GitHub\School_Management_System\SMS\students\models.py" in str 130. return str(self.student)+' : '+str(self.staff) Exception Type: TypeError at /admin/students/studentattendance/add/ Exception Value: must be str, not datetime.date -
django, getting url parameter in template
urls.py urlpatterns = [ re_path(r'^(?P<language>arabic|english|spanish)$', views.get_language, name='get_language'), ] views.py def get_language(request, language): if request.method == "GET": return render(request, 'language.html', {"a": "b"}) else: return JsonResponse({'e': 'hello'}) language.html result: {{ language }} I want to use language parameter from django url's (?P<language>arabic|english|spanish). So, If url is 127.0.0.1/english, language.html is to be rendered like this: result: english I know this is possible in views.py. def get_language(request, language): if request.method == "GET": return render(request, 'language.html', {"language": language}) But I wonder whether there is other better way to do this without modifying views.py. How can I use language parameter directly in template? -
Django REST POST with PK to HyperlinkedModelSerializer, how to translate PK to URL?
I'm new to Django and Django REST. I have been creating a simple practice project. Models: class Locker(models.Model): locker_owner = models.ForeignKey(User, related_name='lockers', on_delete=models.CASCADE) locker_desc = models.CharField(max_length=100) locker_rating = models.IntegerField(default=0) Serializers: class LockerSerializer(serializers.ModelSerializer): locker_owner = serializers.HyperlinkedRelatedField( view_name='user-detail', lookup_field='id', queryset=User.objects.all()) # how to add locker owner with id? class Meta: model = Locker fields = ('url', 'locker_desc', 'locker_rating', 'locker_owner') class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'id', 'username', 'email', 'groups') Views: class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class LockerViewSet(viewsets.ModelViewSet): """ API endpoint that allows lockers to be viewed or edited. """ # def create(self, request): queryset = Locker.objects.all() serializer_class = LockerSerializer I use this to POST: ttp -f POST localhost:8000/lockers/ locker_owner_id=2 locker_desc='desc of locker 3' locker_rating=150 But then the response is "locker_owner": [ "This field is required." ] Main Point: I would like to create a new locker, and use User id as its locker_owner, yet still maintain the HyperlinkedModelSerializer. It won't let me, since they need url for locker_owner. Once I use hyperlink in the locker_owner of my POST request it works, but I don't know how to translate locker_owner=2 to its url. Any … -
How to validate the password django rest
I am trying to make a rest application to communicate with my android application but it is stopping me the validation of the password. I use the User model by default of django and I would like to try to make the server validate the password I found some other interesting answers but the truth is that django is not my strong point (my specialty is android) and they do not explain well how to implement them in my view restapp/views.py class postRegister(APIView): def post(self,request): data = JSONParser().parse(request) cencripM=CriptoMovil(KEY_ENC_M) data['username'] = cencripM.decrypt(data['username']) data['email'] = cencripM.decrypt(data['email']) data['password'] = cencripM.decrypt(data['password']) serializer = RegistSerializer(data=data) if serializer.is_valid(): serializer.save() return Response({"message":"save","state":"1"}) return Response({"message":serializer.errors,"state":"2"}) maybe it helps some of the articles that I found but I did not understand how to implement them in the view (I repeat my specialty is android) many options but I did not know how to implement interesting but I did not understand how to implement the view -
Wagtailmedia media lookup fails unexpectedly
I'm working with the wagtailmedia extension to Wagtail within Django, and am unable to find media that I've uploaded to media directories that I'd expect to be accessible. For reference, the wagtailmedia repository can be found here. There are some questions up here about how to configure media for S3, but right now I'm just trying to get things running locally. I followed the configuration steps in the second example of the wagtailmedia README, but am confused about where wagtailmedia searches. Specifically, I have a wagtailmedia.Media field on one of my models: background_video = models.ForeignKey('wagtailmedia.Media', ... And a content_panel to modify it: content_panels = Page.content_panels + [ MediaChooserPanel('background_video'), ] And I have the following line to (in theory), serve media urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my Django settings for when in debug mode, and the value of settings.MEDIA_ROOT is media/. Does this mean that lookups occur at any directory in static called media, any directory called media, or something else? After setting this up, I created a MediaChooserPanel field for one of my models, and see this: (the no match part) when querying for files that I thought were located along the right paths. What can I do to fix … -
Django form the cleaned_data field is None
Django form the cleaned_data field is None. This field has not passed the validation. I want to change the value of this field. Is there another way to get the non-valid fields? def clean(self): cleaned_data = super(Form, self).clean() print(cleaned_data.get('info')) <---- It is None return cleaned_data -
Django Rest Framework doesn't render generics.ListAPIView, model with GM2MField
First, sorry for my english, but it's not my native language. I have the next problem: I'm working in a Django app, I have a model like this: class AlarmEvent(models.Model): # Alarm types USER = 'US' DEVICE = 'DV' NO_DEVICE = 'ND' ALARM_CHOICES = ( (USER, 'User'), (DEVICE, 'Device'), (NO_DEVICE, 'No-Device') ) alarm = models.ForeignKey(Alarm, on_delete=models.CASCADE, null=True) alarm_type = models.CharField(max_length=2, choices=ALARM_CHOICES, default=USER) created = models.DateTimeField(auto_now_add=True) finished = models.DateTimeField(null=True) content_type = GM2MField() description = models.CharField(max_length=255, default='description', null=True) def __str__(self): return self.alarm_type + '-' + str(self.pk) As you can see, I'm using GM2MField() from third-party app: django-gm2m to have generic M2M relations. For this model I have the following serializer: class AlarmEventSerializer(serializers.ModelSerializer): class Meta: model = AlarmEvent fields = ('id', 'alarm', 'alarm_type', 'created', 'finished', 'device', 'variables', 'content_type', 'description') My problem is the next error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/api/alarms/events/ Django Version: 2.0.3 Python Version: 3.6.3 Installed Applications: ['alarms', 'fotuto_models', 'rest_framework', 'django_filters', 'guardian', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'gm2m', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /usr/local/lib/python3.6/dist-packages/rest_framework/templates/rest_framework/horizontal/select_multiple.html, error at line 15 'NoneType' object has no attribute '_meta' 5 : 6 : 7 : {% if field.label %} 8 : 9 : …