Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Как подключить angularjs на django проект
Я не могу подключить angular на django Пробовал подключить через static и даже через сервера cdn. Но почему то django этого не видет. Версия django 1.11.3 Помогите пожалуйста -
Login form Django phone number not showing
When I enter the details in this form and press the submit button , I don't see the values of phoneno and otp getting saved in the database .The fields phone number and otp are not shown at all . SEE image only username is saved and the otp and phone number fields are not displayed nor saved This is my signup/forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Create your models here. class allusers1(UserCreationForm): phoneno1=forms.CharField(label = "phonewa",max_length=10) otp1=forms.IntegerField(label="OTPP",required=False) class Meta: model=User fields=( 'username', 'password', 'phoneno1', 'otp1', ) def save(self,commit=True): user=super(allusers1,self).save(commit=False) user.username1=self.cleaned_data['username'] user.password1=self.cleaned_data['password'] user.phoneno1=self.cleaned_data['phoneno1'] user.otp1=self.cleaned_data['otp1'] if commit: user.save() return user This is mysignup/forms.py from django.shortcuts import render from .forms import allusers1 def signup(request): form1=allusers1(request.POST or None) if form1.is_valid(): form1.save() context = { "form1": form1, } return render(request, "signup.html",context) -
Django forms fields not displaying with include tag
I have spent a few days trying to find an answer to my issue. I have been reading and trying answers given to users with similar problems, but none of them worked. I created a contact form and it works perfectly if I open the html where the code for the form is. But when I try to display it on index using the include tag, it shows the submit button, the structure and the style, but not the form fields. This is what I have in my code: views.py from django.http import HttpResponse from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.mail import send_mail from .forms import ContactForm from django.shortcuts import render # Create your views here. def index(request): return render(request, 'landingpage/index.html', {}) #Contact form def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = request.POST.get ('name') email = request.POST.get ('email') message = request.POST.get ('message') send_mail('Subject here', content, contact_email, [‘xxx@gmail.com'], fail_silently=False) return HttpResponseRedirect('/thanks/') else: form = ContactForm() return render(request, 'landingpage/contact.html', {'form': form}) #Thank you message def thanks (request): return render(request, 'landingpage/thanks.html', {}) urls.py app_name = 'landingpage' urlpatterns = [ # Landingpage urls url(r'^$', views.index, name='landing-index'), url(r'^contact/$', views.contact, name='contact'), url(r'^thanks/$', views.thanks, name='thanks'), ] index.html … -
save upload file to dynamic directory and get the path for store in db
im uploading a file in addition file some data like file's id and file's title is comming to server . i have below view to handle the request and i want save the file to a dynamic path like "upload/user_id/thefile.txt" with below code the file will save in upload folder directly and also my product_video table will create a new record with related id and the title . now i dont have any idea how can i save the file in dynamic directory like upload/user_id/thefile.txt and how save produced path to "video_path" database table column view class: class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): if request.method == 'POST' and request.FILES['file']: myfile = request.FILES['file'] serilizer = VideoSerializer(data=request.data) if serilizer.is_valid(): serilizer.save() fs = FileSystemStorage() fs.save(myfile.name, myfile) return Response("ok") return Response("bad") and serializer clas: class VideoSerializer(ModelSerializer): class Meta: model = Product_Video fields = [ 'p_id', 'title', 'video_length', 'is_free', ] and related model class: def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Product_Video(models.Model): p_id = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id', related_name='product_video') title = models.CharField(max_length=120, null=True,blank=True) video_path = models.FileField(null=True, upload_to=user_directory_path,storage=FileSystemStorage) video_length = models.CharField(max_length=20, null=True, blank=True) is_free = models.BooleanField(default=False) -
angularjs component templateUrl and files from django static
'use strict'; angular. module('myApp'). component('itemList', { templateUrl: 'static/js/app/item-list/item-list.template.html', controller: function ItemListController($http, $scope) { $http.get('/api/item/').then(function(response) { $scope.items = response.data; }); } }); my home.html is under 127.0.0.1:8000/demo/: <div ng-app="myApp"> <item-list></item-list> </div> When I set templateUrl like this: templateUrl: 'static/js/app/item-list/item-list.template.html' I got: http://127.0.0.1:8000/demo/static/js/app/item-list/item-list.template.html 404 (Not Found) correct url should be: http://127.0.0.1:8000/static/js/app/item-list/item-list.template.html (without "demo") How can I handle url in this case? -
Is there a practice of purposefully going with very loose TDD workflow? [migrated]
Does TDD always mean to constantly add implementation inside Test-Develop loop? I saw once an efficient developer, who prototyped a part of big web app in Python. He did a few things in a day or two - wrote multiple broken/empty tests at once, as a way to describe system use cases - wrote only mocks and interfaces (abstract classes) for the code that might go into the above sketchy tests - wrote a few thin implementations inside rare the tests, in order to demo how interfaces and top-down api calls are connected That look quick, and efficient to me. That gave a good understanding of how the design works and I believe that looked like a controllable experiment for him. While I myself follow the TDD very standardly - add test/ add code/ add more asserts into test. I almost immediately jump into development of some function body. Is there a word/name for this efficient and broad development in TDD? Does it look more like a personal experience - or it's the part of TDD that I've somehow missed and practice it very literally instead of doing "smart code sketches"? -
Django Custom Authentication not working
I am trying to implementing django custom authentication with custom user model using JWT. I have written CustomUser model and CustomAuthBackend and configured for using JWT. Below is the snapshot of project's settings.py : AUTH_USER_MODEL = 'users.CustomUser' AUTHENTICATION_BACKENDS = ('project.users.backends.CustomAuthBackend', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_ALLOW_REFRESH': True, } REST_USE_JWT = True LOGGING = { 'version': 1, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } Before using custom authentication, I created 2 users and after implementing custom authentication trying to login (http://127.0.0.1:8000/admin/) using one of those credentials but getting "Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive." message. Trying to debug the custom authentication but even prints are not coming on console. Also tried using logging module but its also not working. So I doubt that my custom authentication function def authenticate(self, request, email, password) itself might not being called. Here is the code for that. from project.users.models import CustomUser from rest_framework import authentication import logging class CustomAuthBackend(object): def authenticate(self, request, … -
Django(PySCADA) : HTML (code fed thru textbox) is not getting Value from Django
I have Text box at backend-admin where admin can add HTML code which is required for display on Users-Screens. HTML code is getting executed but values of Django veriables are not fetched. (Please refer input & output screens) Input Screen Output Screen -
Django- filtering of the filter object
I want to make a complex filtering on the page using the filtersets.This is my filterset, nicely showing me touples from choosen time and with choosen parameters. #filters.py class workFilter(filters.FilterSet): start__gt = filters.DateTimeFilter(name='time_start', lookup_expr='gte') start__lt = filters.DateTimeFilter(name='time_end', lookup_expr='lte') class Meta: model = Work fields = ('machine', 'program') But I want to add charts explaining the queried data. For that I need informations, like overall count of time. I am querying them like that: #views.py def search(request): work_list = Work.objects.all() work_filter = workFilter(request.GET, queryset=work_list) filter_backends = (filters.DjangoFilterBackend,) ... #some queries to add to context, such as sum_work = Work.objects.aggregate(Sum('time'))['time__sum'] ... return render_to_response( TEMPLATE_DIRS + 'index.html',{ 'filter': praca_filter, 'sum_work': sum_work, ... #context}) But sadly, those queries are according to whole database, not to my filtered set of object. How can I make queries on filtered set work_filter? -
Access StructBlock in a StreamField of a Page.get_children in Wagtail
I try to render a StreamField of a child page in a Page. I don't manage to render the different StructField within the StreamField. Here is my code class DefinitionPage(Page): body = StreamField([ ('definition', blocks.StructBlock([ ('heading', blocks.CharBlock(label='Titre')), ('paragraph', blocks.RichTextBlock(label='Paragraphe')), ])) ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] my template. (DefinitionPage is a child of this page.) {% for post in page.get_children %} <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2> {% for block in post.body %} {% include_block block %} {% endfor %} {% endfor %} post.title is ok but it's like there is no block in post.body. I tried so many things and {% include_block block %} is certainly wrong. I also tried to add a custom template for the StructBlock without success. How can I do ? I am using Django 2.0 and wagtail 2.0 (I'm new to wagtail but I read the doc) Best regards -
How to add a dictionary(or some other data type) to an account I'm Django
I know there is a Django shop you can implement but it doesn't seem to fit my need. I have a python code which returns a 2d list, which I then use jinja to display in HTML. Each list in the 2d list contains information about products and I was wondering if its possible to add an add to basket feature which stores that list to the user, I was thinking in a form of a dictionary, so the user can later see their basket. -
How to complete testing views classes with py.test in Django?
I have Django 2.x with py.test plugin (pytest-django). How to build tests for all of my classes in views.py with it? Example views class: # ./app/views.py class PayOrderView(LoginRequiredMixin, View): """ Pay for Order by ID """ def post(self, request, order_id): # Default status for HttpResponse status = 200 # Get Orders object try: order = BasicOrder.objects.get(id=order_id, user_id=request.user.id) cashbox = Cashbox.objects.filter(user=request.user) except (BasicOrder.DoesNotExist, Cashbox.DoesNotExist): return HttpResponse(status=201) # Get Cashbox object with increase increase = cashbox.filter(payment_procedure=0) \ .aggregate(Sum('amount'))['amount__sum'] # Get Cashbox object with decrease decrease = cashbox.filter(payment_procedure=1) \ .aggregate(Sum('amount'))['amount__sum'] # Default values for increase and decrease if increase is None: increase = 0 if decrease is None: decrease = 0 # Make account balance value if increase > decrease: account_balance = increase - decrease else: account_balance = 0 # Make payment if order.total_cost <= account_balance: # Add new object to Cashbox cashbox = Cashbox.objects.create( order_id=order.id, user=request.user, payment_procedure=1, # Decrease money from Cashbox amount=order.total_cost, comments='For Order ID {}'.format(order.id) ) cashbox.save() # Change status to 1 — Paid order.status = 1 order.save() else: # Change HttpResponse status status = 201 # Return HttpResponse with status return HttpResponse(status=status) I want to test states: Failed, if user is not logged in Failed, if user is not … -
Django auto create slug and integrity error
I'm not understanding this. I have seen the posts here Django - Slugs - Key (slug)=() is duplicated and here Django: Key (slug)=(*) already exists. Here is my error message: django.db.utils.IntegrityError: duplicate key value violates unique constraint "caseAT_case_slug_key" DETAIL: Key (slug)=() already exists. In the docs it says: https://docs.djangoproject.com/en/1.8/howto/writing-migrations/#migrations-that-add-unique-fields Applying a “plain” migration that adds a unique non-nullable field to a table with existing rows will raise an error because the value used to populate existing rows is generated only once, thus breaking the unique constraint. But this is NOT a migration. This is a djangoitem pipeline. The model has the slug being created automatically from the title. Therefore, I did not put slug in the pipeline. If it is expecting to create slug, and balks because it is already there, why isn't it also expecting to create all the other keys? If it isn't in the pipeline, why is it trying to create it now? Because it expects to create it? So I should remove the auto create on that field? Then how is it going to get created? I did want my slugs to be unique. It seems circular and crazy to me, but what difference does that … -
disable django rest framework authentication for special functions
I am using django rest framework for authentication. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ), But in my register function. class UserRegister(APIView): @staticmethod def post(request, user_name): . . . . . obviously I do not need token, however I am getting error: "detail": "Authentication credentials were not provided." I tried this possible answer: this answer but I am encountering this error: 'staticmethod' object has no attribute '__name__' and by deleting @staticmethod decorator, I am getting the previous error again: "detail": "Authentication credentials were not provided." How to exclude this special function from requiring token? tnx -
How to use a custom decorator with default Django auth login view
I am using the default Django authentication system. In my urls, I have : urlpatterns = [ ... path('', include('django.contrib.auth.urls')), ... ] Now I have a custom decorator that I want to apply on the login view, similar to how I have applied it on signup. @example_decorator def signup(request): ... But the problem is that I am using default Login View. Is there any way to apply this decorator to the default Auth View? I think that I need to extend the default view but I can't find any example to do so. How can this be done? -
Unable to save model object
I have created a object which I am trying to save in Django admin in myapp>Hello. But the object does not get created under 'Hello' when I run the server. How can I fix it? I have also registered my models in admin.py. models.py: from django.db import models from django.contrib.auth.models import User class Foo(models.Model): foo_id = models.CharField(max_length=10) class Hello(models.Model): user = models.ForeignKey(User, models.DO_NOTHING) foo_id = models.ForeignKey('Foo', models.DO_NOTHING, db_column='foo_id') foo_text = models.CharField(max_length=500, default="Hello!") views.py from django.shortcuts import render,HttpResponse,redirect from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import User,Foo, Hello from django.contrib.auth import settings @login_required def home(request): return render(request, 'index.html') @login_required def sendhello() : Foos=Foo.objects.all() for foo in foos: #Hello(user=user, foo_text='hello there', foo_id=foo).save() xyz, obj=Hello.objects.get_or_create(user=user, foo_text='hello there', foo_id=foo) if xyz is True: obj.save() -
How to update_or_create in django and filter by empty JSON
i'm trying to update a record with the following fields ID : 1441 SN : 1000000 TYPE: flow_meter EXTERNAL_ID: NULL PROPERTIES: {} CONFIGURATIONS: {"filter_ports": [1, 6]} both properties and configurations are JSONField we have a mysql database when i try to update this record with this line of code in django a new record is created though i already have this record in the DB (as i posted above) Sensor.objects.update_or_create( hub_sn=sensor.get('hub_sn'), type=sensor.get('type'), properties=sensor.get('properties') if sensor.get('properties') else {}, configurations=sensor.get('configurations') if sensor.get('configurations') else {}, defaults=sensor) this is the model class Sensor(models.Model): class Meta: db_table = 'sensors' hub_sn = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=200) external_id = models.CharField(max_length=200, blank=True, null=True) properties = django_mysql.models.JSONField(default=None), configurations = django_mysql.models.JSONField(default=None), i noticed that if i run this line Sensor.objects.get(hub_sn=sensor.get('hub_sn'),type=sensor.get('type'),properties__contains=json.dumps({})) i do get the correct record i need to update as i see it there are 2 ways i can work this out: there is a way to make the update_or_create method to work with the correct syntax - i tried different syntax in the properties field it throws errors like "properties cannot be null" some of my searches : how to write a query to get find value in a json field in django https://djangosnippets.org/snippets/1114/ https://docs.djangoproject.com/en/1.9/ref/models/querysets/#update-or-create 2. make … -
Custom context processor doesn't work
I have the following code: context processor def defaults(request): return { 'LOGO_DEFAULT_SRC': LOGO_DEFAULT_CSRC } settings 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # custom processors 'apps.core.context_processors.defaults', ], in template {{ defaults.LOGO_DEFAULT_SRC }} I use Generic Class Based View. I don't understand why is not working. I restarted the server, clean pyc. code formatting it doesn't work in SO - now -
Adding some fields to return value of parent
I have an abstract class in my Django models which have some children. I have a method in my parent model like follows : def get_info(self): return { 'name': self.name, 'username': self.username, 'about': self.about, } I want in my child classes to add some extra fields into this dictionary. How can I get parent output add some fields and return result.( In child method has the same name get_info) -
Error in Coustomizing Defult User Class in Django
I wanted to add some more fields to Django's default User model I imported AbstractUser and inherit it in my User class and added my app to INSTALLED_APPS and added this line in settings.py AUTH_USER_MODEL='music.User' in which music is my app's name and User is my model name but in migration i got this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'music.user', but app 'music' doesn't provide model 'user'. what should i do? -
Django-Rest-Framework-Use of foreign key in a reverse relation
models.py class ProductsDiscription(models.Model): category = models.CharField(max_length=255) name = models.CharField(max_length=255) price = models.DecimalField(max_digits=255,decimal_places=2) discription = models.TextField() specification = models.TextField() photos = models.URLField() class Cart(models.Model): UserId = models.PositiveIntegerField() ProductId = models.PositiveIntegerField() Quantity = models .PositiveIntegerField() Date = models.DateTimeField(auto_now= True) key = models.ForeignKey(ProductsDiscription,related_name='connection') views.py class CartApi(APIView): """adds item to user's cart when post functions is called""" serializer_class = serializers.CartSerializer def post(self,request): a=serializers.CartSerializer(data=request.data) if a.is_valid(): a.save() return Response({'message':'j'}) else: return Response( a.errors, status=status.HTTP_400_BAD_REQUEST) class CartItems(APIView): serializer_class = serializers.CartOnlySerializer def get(self,request): """returns the list of products in user's cart""" z = int(request.GET.get('q','')) queryset=(models.Cart.objects.filter(UserId=z).values()) k=[] for i in queryset: p= i.get("ProductId") print(p) k.append(models.ProductsDiscription.objects.filter(connection__id=p)) print(k) abc = serializers.CartOnlySerializer(k,many=True) return JsonResponse({'pcartlist':(abc.data)}) serializer.py class CartSerializer(serializers.ModelSerializer): """serialiazer for handling the post request for the cart""" class Meta: model = models.Cart fields = ('id', 'UserId', 'ProductId','Quantity',) def create(self, validated_data): user_cart = models.Cart( UserId=validated_data.get('UserId'), ProductId=validated_data.get('ProductId'), Quantity = validated_data.get('Quantity'), key = models.ProductsDiscription(validated_data.get('ProductId')) ) user_cart.save() return user_cart class CartListSerializer(serializers.ModelSeriaizer): class Meta : model = models.ProductsDiscription fields =('id','category','name','price','discription','specification','photos') class CartListSerializer1(serializers.ListSerializer): child = CartListSerializer() allow_null =True many = True class CartOnlySerializer(serializers.ModelSerializer): connection = CartListSerializer1() class Meta: model = models.Cart fields = ('connection',) There is one model ProductDescription which stores all the info about the products and there is model Cart which is used to save the … -
Django: How to redirect with arguments
After submit a form, I want to redirect to an specific view passing one flag=True in order to activate a popup like: def view1(request): if request.method == 'POST': form = Form(request.POST) if form.is_valid(): form.save() return redirect('new_view') # Here I need to send flag=True else: form = Form() return render(request, 'template.html', {'form': form}) How can I do this? -
Receiving error when Obtain Json Web Token
So i'v set up the Django REST framework JWT using the guide from the website https://getblimp.github.io/django-rest-framework-jwt/, but whenever i post a request to obtain a token i get this error: jwt_response_payload_handler() takes from 1 to 2 positional arguments but 3 were given. I'm sending the post request as: axios.post('http://127.0.0.1:8000/api/auth/token/', authData). authData = {username: 'username', password: 'password'} -
Set variable in django templates - Could not parse the remainder error
I am trying to set a variable in Django template but it is giving me error as - Could not parse the remainder. Here is my code {% for result in page_obj.object_list %} {% with {{result.object.blogger.blog_name}} as temp_var %} <h3>{{ temp_var }}</h3> {% endwith %} {% endfor %} when I am only printing {{result.object.blogger.blog_name}} its working but when setting it into variable it shows me error Exception Value: Could not parse the remainder: '{{result.object.blogger.blog_name}}' from '{{result.object.blogger.blog_name}}' -
Not able to configure a DeleteView, getting pattern error
So I have been trying to configure a DeleteView for my Lecture model. For my Course model, each course has its own slug page and on that page, I have all lectures for that course. Problem is, that when I'm trying to delete a lecture, I get this error: Reverse for 'lecture_delete' with no arguments not found. 1 pattern(s) tried: ['courses\\/(?P<slug>[-a-zA-Z0-9_]+)\\/delete\\/$'] I guess it has something to do with my slug. Traceback: http://dpaste.com/02X45B5 class LectureDelete(DeleteView): model = Lecture success_url = reverse_lazy('courses/courses.html') <ul> {% for c in category.list %} ............. <li>{{ c.lecture_title }}</li> <li>{{ c.content }}</li> {% for file in c.files.all %} {% if file.files %} <li><a href='{{ MEDIA_URL }}{{ file.files.url }}'>download</a></li> {% endif %} {% endfor %} Hey, are you sure you want to delete {{ c.lecture_title }}? <form action="{% url "courses:lecture_delete" %}" method="post"> {% csrf_token %} <button type="submit">Yeap, I'm sure.</button> </form> {% endfor %} </ul> class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', ) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', ) lecture_title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField(blank=False, default=None) def __str__(self): return str(self.lecture_title) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, default=None) path('<slug:slug>/', views.courses, name='courses'), path('<slug:slug>/delete/', views.LectureDelete.as_view(), …