Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in creating Login Function based on Custom ModelForm DB in Django
I didn't want to use Django's inbuilt form, so I made a ModelForm and I was able to implement registering a user based on my ModelForm. But now I want to login using the ModelForm DB to authenticate the user. Is there any way to make a custom authentication based on the ModelForm that I made? I have added code snippets of models.py, forms.py and views.py! hope its enough! models.py from django.db import models # Create your models here. LEVELS = [ ('AD', 'ADMIN'), ('VU', 'VIEW AND UNLOCK'), ('V', 'VIEW ONLY') ] class Clients(models.Model): name = models.CharField(max_length=200, null=True) phone = models.IntegerField(null=True) pswd = models.CharField(max_length=200, null=True) access_level = models.CharField(max_length=2, choices=LEVELS) def __str__(self): return self.name class Meta: verbose_name_plural = "Clients" forms.py from django import forms from django.forms import ModelForm from iot.models import Clients class Clientsform(ModelForm): class Meta: model = Clients fields = '__all__' widgets = {'name': forms.TextInput(attrs={'class': 'form-control', 'required': 'True'}), 'phone': forms.NumberInput(attrs={'class': 'form-control', 'required': 'True'}), 'pswd': forms.PasswordInput(attrs={'class': 'form-control', 'required': 'True'}), 'access_level': forms.Select(attrs={'class': 'form-control', 'required': 'True'})} views.py def register(request): form = Clientsform() if request.method == 'POST': form = Clientsform(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('name') messages.success(request, 'Account was created for ' + user) return redirect('login') context = {'form': form} return render(request, "form.html", context) … -
Iam Having This Error on Django Exception in thread Django-main-thread
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\ABIPRAVI\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '3' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin 'a' in CORS_ORIGIN_WHITELIST is missing scheme or … -
json.dumps return double quotes error in python
I am receiving this kind of json { a: {}, b: 'xyz', c: '1', d: 'hotel', e: '1', f: '1' } when i use json.dumps i receive double quote error. How to add double quote for keys in above json. -
database design for checkout and order table
I am designing a database for e-commerce. I am confused regarding the checkout and order table. I am not sure if I need to create separate order table when most of the things is already done on checkout table. Here is the design as of now class Product(ModelWithMetadata, PublishableModel): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) category = models.ForeignKey( Category, related_name="products", on_delete=models.SET_NULL, null=True, blank=True, ) class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variants") variant_attributes = models.ManyToManyField(VariantAttribute, related_name="productvariants") class Checkout(ModelWithMetadata): """A shopping checkout.""" created = models.DateTimeField(auto_now_add=True) last_change = models.DateTimeField(auto_now=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name="checkouts", on_delete=models.CASCADE, ) email = models.EmailField() token = models.UUIDField(primary_key=True, default=uuid4, editable=False) quantity = models.PositiveIntegerField(default=0) billing_address = models.ForeignKey( Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL ) shipping_address = models.ForeignKey( Address, related_name="+", editable=False, null=True, on_delete=models.SET_NULL ) shipping_method = models.ForeignKey( ShippingMethod, blank=True, null=True, related_name="checkouts", on_delete=models.SET_NULL, ) note = models.TextField(blank=True, default="") currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, default=settings.DEFAULT_CURRENCY, ) country = CountryField(default=get_default_country) discount_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=0, ) discount = MoneyField(amount_field="discount_amount", currency_field="currency") discount_name = models.CharField(max_length=255, blank=True, null=True) voucher_code = models.CharField(max_length=12, blank=True, null=True) # gift_cards = models.ManyToManyField(GiftCard, blank=True, related_name="checkouts") objects = CheckoutQueryset.as_manager() class Meta: ordering = ("-last_change", "pk") class CheckoutLine(models.Model): """A single checkout line. """ checkout = models.ForeignKey( Checkout, related_name="lines", on_delete=models.CASCADE ) variant = models.ForeignKey( … -
The view shop.views.product_list didn't return an HttpResponse object. It returned None instead
Here is my code , I am getting same error again and again. I dont know whats wrong here. category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request,'templates/shop/product/list.html',{'category':category,'categories':categories,'products':products}) -
JQuery AJAX with django getting csrf error 403
Getting Error CSRF verification failed. Request aborted. Missing or Incorrect Token. I am new to JQuery not sure if it is contributing to my error. I think I am passing the request properly. Cookies are accepted and a simpler JQuery request worked earlier. Views def testcall(request): text = request.POST['text'] if request.method == 'POST' and request.POST['action'] == 'start_function1': function1(text) response = text + "has been successful" return HttpResponse(response) if request.method == 'POST' and request.POST['action'] == 'start_function2': function2(text) response = text + "has been successful" return HttpResponse(response) Template <html> <head> <title>Test Data</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script> jQuery(document).ready(function($){ $('demo-form').on('submit', function(event){ event.preventDefault(); var text = document.getElementById('text-to-analyze').value; $.ajax({ url : '{{ 'my-ajax-testsub/' }}', type : "POST", data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: text, action: 'start_function1' }, success: function callback(response){ alert(response); }, }); })}) jQuery(document).ready(function($){ $('demo-form').on('submit', function(event){ event.preventDefault(); var text = document.getElementById('text-to-analyze').value; $.ajax({ url : '{{ 'my-ajax-testunsub/' }}', type : "POST", data: { csrfmiddlewaretoken: '{{ csrf_token }}', text: text, action: 'start_function2' }, success: function callback(response){ alert(response); }, }); })}) </script> </head> <body> <form name="demo-form" method="POST" action="{% url 'home' %}"> <p>Input field: <input type="text" id="text-to-analyze" value="name@gmail.com"></p><br> <button class="btn btn-success" name="start_function1">Function</button> <button class="btn btn-success" name="start_function2">Function</button> </form> </body> </html> -
Django web email client
How can I embed a web email client in Django App? The users in the systems should be able to send mails to each others. I have tried django messages but that is not the solutions I'm looking. -
Efficient Design of DB with several relations - Django
I want to know the most efficient way for structuring and designing a database with several relations. I will explain my problem with a toy example which is scaled up in my current situation Here are the Models in the Django database 1.) Employee Master (biggest table with several columns and rows) class Emp_Mast(): emp_mast_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) desgn_mast = models.ForeignKey("hr.Desgn_Mast", on_delete=models.SET_NULL, null=True) qual_mast = models.ForeignKey("hr.Qualification_Mast", on_delete=models.SET_NULL, null=True) office_mast = models.ManyToManyField("company_setup.Office_Mast", ref_mast = models.ForeignKey("hr.Reference_Mast", on_delete=models.SET_NULL, null=True) refernce_mast = models.ForeignKey("hr.Refernce_Mast", on_delete=models.SET_NULL, null=True) This is how the data is displayed in frontend 2.) All the relational field in the Employee Master have their corresponding models 3.) Crw_Movement_Transaction Now I need to create a table for Transaction Data that that stores each and every movement of the employees. We have several Offshore sites that the employees need to travel to and daily about 50 rows would be added to this Transaction Table called Crw_Movement_Transaction The Crw_Movement Table will have a few additional columns of calculations of itself and rest of the columns will be static (data would not be changed from here) and will be from the employee_master such as desgn_mast, souring_mast (so … -
Issue with connecting to MongoDB docker container with another container
Having an issue with connecting to a docker container to another container. I'm able to connect to it locally outside the container but from within the container doesn't work. This is the stack trace pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9cf7b6d9d395e79548d42a, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> My docker-compose.yml file is pretty straight forward and simple. Nothing unique mongod: restart: always image: mongo:latest volumes: - ./mongodb/mongod.conf:/etc/mongod.conf ports: - "27017:27017" command: mongod app: build: ./app container_name: django-gunicorn restart: always env_file: - ./app/django.env ports: - "8000:8000" command: "gunicorn --workers=2 --bind=0.0.0.0:8000 webapp.wsgi:application" I've binded the port to 0.0.0.0 in the mongod.conf. What else am I missing? -
How to filter and paginate in ListView Django
I have a problem when I want to paginate the filter that I create with django_filter, in my template it shows me the query set and filter but paginate does not work, I would like to know why this happens and if you could help me. I'll insert snippets of my code so you can see. This is my views.py PD: i have all the necesary imports. @method_decorator(staff_member_required, name='dispatch') class EmployeeListView(ListView): model = Employee paginate_by = 4 def dispatch(self, request, *args, **kwargs): if not request.user.has_perm('employee.view_employee'): return redirect(reverse_lazy('home')) return super(EmployeeListView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = EmployeeFilter(self.request.GET, queryset = self.get_queryset()) return context filters.py import django_filters from .models import Employee, Accident class EmployeeFilter(django_filters.FilterSet): class Meta: model = Employee fields = { 'rutEmployee' : ['startswith'] } and employee_list.html {% extends 'core/base.html' %} {% load bootstrap %} {% load static %} {% block title %}EMPLEADOS{% endblock %} {% block content %} <main role="main"> <div class="row"> <div class="col-md-12 stretch-card"> <div class="card"> <div class="card-body"> <p class="card-title">Lista de Empleados</p> <div class="table-responsive"> <form method="GET"> {{ filter.form|bootstrap }} <button type="submit" class="btn btn-primary">Filtrar</button> </form> <hr> <table class="table table-bordered"> <thead> <tr> <th>Rut</th> <th>Nombre</th> <th>Apellido Paterno</th> <th>Detalle</th> </tr> </thead> <tbody> {% for employee in filter.qs|dictsort:"id" reversed %} … -
Backend interfering with load times - Django
I am working on a project where a backend function in my Django project pulls data and then runs a data analysis on it. The issue I am encountering is that while this is happening the frontend shows a 404 error until the analysis is complete. As this will be client-facing is there a way to fix this without rewriting the analysis in Javascript? -
Django Video Wont Play How To Fix?
I am trying to load my basic video that I recored with gyazo but it wont load my video the video is a mp4 and the name is correct as well I loaded my {% static %} on top and made sure the video was in my static image file and in my setting is STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] correct as well I am not sure how to fix this problem this is how I load my videos from gyazo <video width="430" height="340" controls autoplay> <source src="{% static dam.mp4 %}" type="video/mp4"> </source> damcool </video> my full code <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Learn To Code</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> * { box-sizing: border-box; } body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } body {font-family: "Times New Roman", Georgia, Serif;} h1, h2, h3, h4, h5, h6 { font-family: "Playfair Display"; letter-spacing: 0px; color: white; } /* Style the header */ .header { background-color: #58D68D; padding: 10px; text-align: center; font-size: 35px; } /* Create three equal columns that floats next to each other */ .column { float: left; width: 73.33%; padding: 10px; … -
Javascript runs in template html file but not extended html file in Django application
I am writing a website in Django and Vanilla JS I have 2 html pages, I want them both to share css but I want them to use different javascript. Both pages extend a layout.html. The layout.html looks begins like this {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" rel="stylesheet"> </head> My index.html (which extends my layout.html) begins like this {% extends "network/layout.html" %} {% load static %} <script src="{% static 'network/messages.js' %}"></script> and my Javascript file looks like this: document.addEventListener('DOMContentLoaded', function() { console.log("page loaded!") document.addEventListener('click', event => { const element = event.target; console.log("Something was clicked") }) }); It simply prints out a line when the page is loaded and when something is clicked. However, when I go to index.html with the code like this, the javascript file is not loaded, nothing is printed out when the page is loaded or when anything is clicked. However, if I modify the layout.html page to be like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Social Network{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'network/styles.css' %}" … -
SMTPSenderRefused at /accounts/signup/
I tried to configure sending email on registration using gmail server and i get these error: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError u2sm3847520edr.70 - gsmtp', 'webmaster@localhost'). These are my configurations in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') -
Django ImageField tamplate tag not displaying
The image is correctly saved to the static filed that I set in the setting filed. The image will display properly if I use a static path. But when I use a dynamic path, the image would not show and no error is given. As you can see the path, when called outside of , works correctly. But when puted inside of the , both {{item.image_1.path}}, nor {{item.image_1}},would show any picture. (item is the name of the model while image_1 is the name of the image_field) -----------For the not working dynamic path: {{item.image}} {{item.image.path}} <img src='{{item.image}}' alt=''> <img src='{{item.image.path}}' alt=''> [![for the not working method[1]][1] -----------For the working static path: {% static 'arrival7.png' as pic %} <img src='{{pic}}' alt=''> -
How can I restrict inserting data on behalf of another user in Django?
I have the following code in my django project. models.py from django.db import models class Doctor(models.Model): hospital = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(primary_key=True, max_length=256, unique=True) education = models.CharField(max_length=256) class Patient(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) name = models.CharField(max_length=256) age = models.CharField(max_length=200) height = models.CharField(max_length=6) sex = models.CharField(max_length=12) serializers.py from rest_framework import serializers from .models import Doctor, Patient class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = [ 'name', 'education' ] class PatientSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = '__all__' views.py from rest_framework import status, permissions from rest_framework.response import Response from rest_framework.views import APIView from .models import Doctor, Patient from .serializers import DoctorSerializer, PatientSerializer class DoctorList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = DoctorSerializer def get(self, request): doctors = Doctor.objects.filter(hospital=request.user) serializer = DoctorSerializer(doctors, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = DoctorSerializer(data=request.data) if serializer.is_valid(): serializer.save(hospital=request.user) return Response({"message": "Doctor inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class PatientList(APIView): permission_classes = [permissions.IsAuthenticated] serializer_class = PatientSerializer def get(self, request): patients = Patient.objects.filter(doctor__hospital=request.user) serializer = PatientSerializer(patients, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request): serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "Patient inserted!"}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) These views are then wired up with endpoints doctors/ and patients/ respectively. The problem I am having is restricting the owner … -
blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. in django
I am making a django blog app. But when i run python manage.py makemigrations blog, I get this error: SystemCheckError: System check identified some issues: ERRORS: blog.Post.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. Here is my models.py: from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.name} on {self.post}' At first I thought that this error means I had not installed django-taggit. But when I … -
Logging with django rest framework with WSGI
I am fairly new in backend development. I was trying to write some log with Django rest framework. I set up the WSGI mode and the 000-default.conf file is <VirtualHost *:80> ServerAdmin user@gmail.com DocumentRoot /home/ubuntu/myproject_backend/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/myproject_backend/myproject/static <Directory /home/ubuntu/myproject_backend/myproject/static> Require all granted </Directory> <Directory /home/ubuntu/myproject_backend/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/ubuntu/myproject_backend/myproject python-home=/home/ubuntu/myproject_backend/env WSGIProcessGroup myproject WSGIScriptAlias / /home/ubuntu/myproject_backend/myproject/myproject/wsgi.py WSGIPassAuthorization On </VirtualHost> I added the LOGGING in the setting.py LOGGING = { 'version': 1, # Version of logging 'disable_existing_loggers': False, #disable logging 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'my_log.log', } }, 'loggers': { 'django': { 'handlers': ['file'], 'level': env("LOG_LEVEL"), 'propagate': True, }, }, } I tried with a simple warning log logging.warning("Logging Tutorials") Now the log is working when I was testing locally with the runserver command. However, when I pushed the code to the server it's getting permission denied writing the error.log file. PermissionError: [Errno 13] Permission denied I was wondering how do I give the permission and which user? the server is a ubuntu OS. I know there are a few posts about this issue. However, I could not figure out what exactly do I have to … -
How can I re-direct a user from the login page to the sign up page?
So, I have been trying to do this problem for a couple of days, but I seem to be having no luck, in actually solving it. For my side-project, I am creating a student grade management system in Django, and the problem that I am getting is that everytime the user clicks on the signup button on the homepage/login page, I get an error, because I haven't re-routed the user successfully. Specifically, the error I get is that it says, Page not Found. The page that I am trying to re-route the user to is in another app. So, I'm trying to route the user to the base url of that app, which from there, it will pop open a view. Here is the code for my urls.py on the loginpage/homepage (App1) from django.urls import re_path from django.shortcuts import redirect # import signUpPage.views as signupview from . import views urlpatterns = [ re_path(r'^$', views.login, name='login'), # re_path('signUpPage', signupview.register, name='signUpPage') # re_path('') ] Here is the code for my forms.py on the loginpage/homepage (App1) from crispy_forms.helper import FormHelper from crispy_forms.layout import Fieldset, Layout class loginForm(forms.Form): UserName = forms.CharField( label="Username", help_text="Please enter your username", widget=forms.TextInput(attrs={"placeholder":"Username"}), required=False ) Password = forms.CharField( label="Password", help_text="Enter … -
how to mock the django model?
i have to test a block of code ,like this: model: ''' class LoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'login_table' ''' test model: ''' class TestLoginHistory(models.Model): id = models.AutoField('ID', primary_key=True) class meta: db_table = 'test_login_table' ''' util: ''' def registLoginHistory(self, loginId): model = LoginHistory(login_id=loginId) model.save() ''' test method: ''' def test_registLoginHistory(self): loginId = '003136130001' self.util.registLoginHistory(loginId) ''' now,i want to use TestLoginHistory(a django model) to change LoginHistory, so i try to use mock to do that. but it didnt work. it is the code i tried: ''' def test_registLoginHistory(self): loginId = '003136130001' LoginHistory = mock.MagicMock() LoginHistory.return_value.save = mock.MagicMock(side_effect=TestLoginHistory.save) self.util.registLoginHistory(loginId) ''' what should i do ? thx in advance. -
I can access my database with django and query it with objects.get() but objects.filter() will not work
I am just making a simple website as I am learning django. I have a view function that looks like this: def vieworkout(request): date= datetime.today() obj = userworkouts.objects.filter(userid=52) date = request.POST['date'] context = { 'exercise': obj.exercise } return render(request, 'clientIndex.html', context) when I use userworkouts.object.get() I can pass the exercise object no problem. When I change it to filter I get an error, "'QuerySet' object has no attribute 'exercise'". Does anyone know why this is happening? -
is there a way of defining function in models and save them to database as default by also filtering the fields? in Python Djnago
what i want to do is compute the value in percent for each learning styles there are and save them as default value to the field **result** on AssessmentLearningStyle model here is the model #MODEL_FOURTEEN class QuestionResults(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) question = models.ForeignKey(to=QuestionLearningStyle, on_delete=models.SET_NULL, null=True, blank=True) agree = models.BooleanField(null=False) disagree = models.BooleanField(null=False) def __str__(self): return str(self.question) #MODEL_FIFTEEN class AssessmentLearningStyle(models.Model): @property def test(self): u = self.learning_style s = 0 if u == QuestionResults.question.learning_style: k = int(QuestionResults.objects.filter(agree=True, question__learning_style=self.learning_style).count()) l = int(QuestionResults.objects.filter(question__learning_style=self.learning_style).count()) if l != 0: s = (k/l) * 100 else: s = 0 return float(s) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey(to=FacilityUser, on_delete=models.SET_NULL, null=True, blank=True) assessent_date = models.DateField(blank=True, null=True) learning_style = models.ForeignKey(to=LearningStyle, on_delete=models.SET_NULL, null=True, blank=True) result = models.FloatField(default=test, editable=False) def __str__(self): return str(self.student) i want to save the value of test function to the result field...but it says float can't accept the value of property...and if i remove property... this method doesn't work at all...can you guys help me to fix this or show me a better way of doing this? Blockquote -
What would be the better way to write this class based view memcached caching
I am trying to do some caching in Django Here is what I have so far... # Jobs List View @method_decorator([vary_on_cookie, cache_page(900)], name='dispatch') class JobsListView( ListView): template_name = 'jobs_list.html' context_object_name = 'jobs' model = Job paginate_by = 6 def dispatch(self,request,*args,**kwargs): cache_key = 'my_jobs' # needs to be unique cache_key_featured = 'my_featuredjobs' # needs to be unique cache_time = 900 # time in seconds for cache to be valid datajobs = cache.get(cache_key) datafeatured = cache.get(cache_key_featured) if not datafeatured: cache.set(cache_key_featured, Discuss.objects.featured()[:5], cache_time) if not datajobs: cache.set(cache_key, super().get_queryset(), cache_time) return super(JobsListView,self).dispatch(request,*args,**kwargs) def get_context_data(self, **kwargs): context = super(JobsListView, self).get_context_data(**kwargs) cache_key = 'my_featuredjobs' # needs to be unique context["featured_discuss"] = cache.get(cache_key) if not context["featured_discuss"]: context["featured_discuss"] = Discuss.objects.featured()[:5] return context def get_queryset(self, *args, **kwargs): cache_key = 'my_jobs' # needs to be unique data = cache.get(cache_key) if not data: data = super().get_queryset() return data This looks awry to me. The fact that I have to do the cache.get() in all three methods, dispatch(), get_context(), get_queryset(). There must be a better way of doing this. What would be the better way to rewrite this class for better performance. -
"ValueError: year is out of range" with Django
When I started my current position, I inherited a Django Rest API that sits on top of our Postgres database. It was still running on Django v.1.7.11. Now almost two years later, I decided it's finally time to upgrade. I first upgraded to Django v1.11.29 (planning on getting it more current, but wanted to upgrade somewhat incrementally). I fixed any errors caused by the upgrade and was all set. I was able to access it and everything worked properly, except for reading data from one table. This table contains four date fields, and when accessing it's API endpoint, I get the following error: Request Method: GET Request URL: http://obis.twalk.tech:81/api/obis/occurrence/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: year is out of range Exception Location: /usr/local/lib/python2.7/site-packages/django/db/utils.py in inner, line 101 Python Executable: /usr/local/bin/python Python Version: 2.7.18 From what I could tell initially with the debug output, this error was caused by having a null values in one of the date fields. I'm working in a personal development environment so I was able to change, at the database level, each instance of a null value in any of the date fields to be a properly formatted date. I still got the same … -
Got AttributeError when attempting to get a value for field `user` on serializer
I am trying to upload a csv file and then using it to populate a table in the database (creating multiple objects). serializers.py: class FileUploadSerializer(serializers.ModelSerializer): filedata = serializers.FileField(write_only=True) class Meta: model = WorkData fields = ['user', 'filedata'] def create(self, validated_data): file = validated_data.pop('filedata') data_list = csv_file_parser(file) # utility method batch = instantiate_batch_objects(data_list, validated_data['user']) # utility method work_data_objects = WorkData.objects.bulk_create(batch) # print(work_data_objects[0]) return work_data_objects views.py: class FileUploadView(generics.CreateAPIView): queryset = WorkData.objects.all() permission_classes = [IsAuthenticated] serializer_class = FileUploadSerializer def get_serializer(self, *args, **kwargs): print(kwargs.get('data')) if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) models.py class WorkData(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='work_data', ) work = models.IntegerField(blank=False, null=False) recordTime = models.DateTimeField(blank=False, null=True) When I upload the file and post it I get this error: Got AttributeError when attempting to get a value for field user on serializer FileUploadSerializer. The serializer field might be named incorrectly and not match any attribute or key on the list instance. Original exception text was: 'list' object has no attribute 'user'. But I can see table is populated successfully in the database. What could be the source for this error?