Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using inlineformset_factory with different querysets in CreateView
I am trying to use inlineformset_factory to create instances of the same model. models.py class Skill(models.Model): employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name="employee_skills") technology = models.ForeignKey(Technology, on_delete=models.CASCADE) year = models.CharField('common year using amount ', max_length=4) last_year = models.CharField('Last year of technology using ', max_length=4) level = models.CharField("experience level", max_length=64, choices=LEVELS) class Techgroup(models.Model): """ Group of technology """ name = models.CharField('group_name', max_length=32, unique=True) class Technology(models.Model): """Technologies.""" name = models.CharField('technology name', max_length=32, unique=True) group = models.ForeignKey(Techgroup, on_delete=models.CASCADE, related_name="group") In the Administrator pane I created 2 instances of the Techgroup model: - Framework - Programming language All Skill models belong to one of two groups. On the front I display 2 forms, one containing queryset with instances belonging to the Framework, the other with instances belonging to the Programming language. I divide Querysets using ModelsForm: forms.py class SkillBaseCreateForm(forms.ModelForm): YEAR_CHOICES = [(r, r) for r in range(1, 11)] LAST_YEAR_CHOICES = [(r, r) for r in range(2015, datetime.datetime.now().year + 1)] year = forms.CharField( widget=forms.Select(choices=YEAR_CHOICES), ) last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES)) class Meta: model = Skill fields = ['technology', 'level', 'last_year', 'year'] class SkillCreatePLanguageForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreatePLanguageForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Programming language") class SkillCreateFrameworkForm(SkillBaseCreateForm): def __init__(self, *args, **kwargs): super(SkillCreateFrameworkForm, self).__init__(*args, **kwargs) self.fields['technology'].queryset = Technology.objects.filter(group__name="Framework") SkillFrameworkFormSet = … -
Problem with custom django admin listview editable field
Django 2.1.2 I've almost successfully added a checkbox to a django admin listview which doesn't link to a field in the underlying model. Instead I want to update fields in the model based on the checkbox value. My code's almost working after reading a post here. My problem is that if I override save() in my form, django breaks somewhere else saying that "'NoneType' object has no attribute 'save'". I have a TrainingSession model with a submitted_date and an accepted_date. The below code shows a checkbox in the listview which defaults to checked if accepted_date is set, and the checkbox is disabled if submitted_date is not set. My plan is then to set the accepted_date to today if you check the checkbox: class TrainingSessionListForm(forms.ModelForm): accept = forms.BooleanField(required=False) class Meta: model = TrainingSession fields = '__all__' def __init__(self, *args, **kwargs): instance = kwargs.get('instance') if instance: initiallyApproved = instance.accepted_date is not None submittedForApproval = instance.submitted_date is not None initial = kwargs.get('initial', {}) initial['accept'] = initiallyApproved self.base_fields['accept'].disabled = not submittedForApproval kwargs['initial'] = initial super(TrainingSessionListForm, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): instance = kwargs.get('instance') if instance: accepted = self.cleaned_data['accept'] if accepted and instance.accepted_date is None: instance.accepted_date = datetime.date.today() super(TrainingSessionListForm, self).save(*args, **kwargs) class TrainingSessionAdmin(admin.ModelAdmin): list_display … -
How to fix "ModuleNotFoundError: No module named 'DEGNet'"?
I'm trying to "python3 manage.py runserver" on MacOS and get this error. I run the web-application in virtual environment, where Django is installed. The problem appears both on non-virtual environment also. What is DEGNet itself? I can't even find it in directory. Thats what I got after "python3 manage.py runserver" ''' Traceback (most recent call last): File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/konstantingolubtsov/newproject/newenv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'DEGNet' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line … -
Import data from sql database into django models
I have SQL database connected with my Django project. I want to import all the data from SQL database into my new created Django models ie I want to import data into new tables created via Django models. -
Accessing Variable from nested loops
I need to access variable from a nested loop in django, but I got empty data instead Here is the piece of code def connections(request): """get service connections from api""" brand_res = requests.get(url+'?method=api.brand_list', auth=HTTPBasicAuth(name, token)) brands = brand_res.json() for key, brand in brands['data'].items(): services = [] service_plans = requests.get( url+'?method=api.service_plan_list&code=SDNCCNNIRTTTT&brand_id='+brand['class_id'], auth=HTTPBasicAuth(name, token)) plans = service_plans.json() if isinstance(plans['data'], dict): """if dict""" for m, plan in plans['data'].items(): """ get all plan_ids""" services_connected = requests.get( url+'?method=client.service_list&plan_id=' + plan['plan_id'], auth=HTTPBasicAuth(name, token)) sho = services_connected.json() services.append(sho) else: """if list""" for plan in plans: print('') print('') print('') return HttpResponse(services) But I have no luck in returning the data to pass in html as json Any ideas? -
Django can't find static folder
I am looking to add a css file to Django but it can't find the static folder. Here is my settings.py file: """ Django settings for opengarden project. Generated by 'django-admin startproject' using Django 2.2.3. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p4(nadg3%7^2raxg3u5rkkk18(1z363dxcyr2cj8znefm+&5$9' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'opengarden.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'wx', 'templates'),], 'APP_DIRS': True, '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', ], }, }, ] WSGI_APPLICATION = 'opengarden.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': … -
how to send payload with identifier using django api rest framework
i'm trying to get a result something like this when someone order more than one product at the same time be able to select different quantities for each product does api can solve this kind of problem ?this the same as subquery in sql how to perform something like this payload = {"identifier":"Order_id", "items":[{"product":"name of item 1","quantity":324},{"item_name":"name of item 2", "quantity":324}]} models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True) quantity = models.IntegerField(default=1) serializer.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = ProductOrder fields = ['product','quantity','ordering'] viewsets.py class CreateOrderSerializer(generics.CreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer permission_classes = [] authentication_classes = [] when a customer visit to the restaurant , the cashier be able to fill a receipt,for example (3 pizza with 2 sandwich) then calculate quantities with its prices! -
What does contrib stand for in django? and why?
I am learning Django. I came across the term "contrib" but I don't know what it actually means It obviously seems from the word "contribution" but why is it named like that? Thank you -
How can I avoid a redirection to the home page?
I'm working on a website for an internship. I've implemented a logout button but when I logout, after the user deconnection, I have a redirection on the home page, but I don't want this, for example if I'm in url.com/toto/tata, after the logout I would like to stay in this path and not have a rediction to url.com/home. <form method="POST" action="{% url "account_logout" %}" class="form-horizontal"> {% csrf_token %} <div class="form-actions"> <button type="submit">Logout</button> </div> </form> -
how to receive modelform_instance.cleaned_data['foreign key field'] in view?
Here is the situation: I have a model as below: class Permit(Model): permit_option = BooleanField() Permit model has two objects: Permit.objects.create(permit_option=False) Permit.objects.create(permit_option=True) I have another model: Interest(Model): permit_interest = ForeignKey(Permit, default=True, null=True, blank=True, on_delete=CASCADE, ) I then build a ModelForm using Interest: class InterestForm(ModelForm): class Meta: model = Interest fields = '__all__' I have a view: def interest(request): template_name = 'interest_template.html' context = {} if request.POST: interest_form = InterestForm(request.POST) if interest_form.is_valid(): if interest_form.cleaned_data['permit_interest'] == 2: return HttpResponse('True') elif interest_form.cleaned_data['permit_interest'] == 1: return HttpResponse('False') else: return HttpResponse('None') else: interest_form = InterestForm() context.update({interest_form': interest_form, }) return render(request, template_name, context) and in interest_template.html I have: <form method="post"> {% csrf_token %} {{ interest_form.as_p }} <button type="submit">Submit</button> </form> I expect to see True when I choose True in the form field and submit it. Or see False when I choose False in the form field and submit it. I have tested numerous methods: if request.POST: interest_form = InterestForm(request.POST) if interest_form.is_valid(): if interest_form.cleaned_data['permit_interest'] == True: return HttpResponse('True') elif interest_form.cleaned_data['permit_interest'] == False: return HttpResponse('False') else: return HttpResponse('None') or if request.POST: interest_form = InterestForm(request.POST) if interest_form.is_valid(): if interest_form.cleaned_data['permit_interest'] == 'True': return HttpResponse('True') elif interest_form.cleaned_data['permit_interest'] == 'False': return HttpResponse('False') else: return HttpResponse('None') or if request.POST: interest_form = InterestForm(request.POST) if … -
no such table: news_commentmodel
I make comments on the site and when I fill out the form I send it to me gives an error The above exception (no such table: news_commentmodel) was the direct cause of the following exception. And shows an error in saving the form After filling out the form, all comments (data) should be shown below. I display them through the template. views.py def ArticleDetailView(request, pk, tag_slug=None): tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'tag': tag, 'comment_form': comment_form, 'comments': commentss, }) models.py class CommentModel(models.Model): name = models.CharField(max_length=100) text = models.TextField(default='') dates = models.DateTimeField(auto_now=True) class Meta: ordering = ['-dates'] def __str__(self): return self.name forms.py class Meta: model = CommentModel fields = ('name', 'text') post.html <form action="" method="post"> {% csrf_token %} <div style=" margin-left: 35% ; border: 3px solid #4242A3; border-radius: 15px; width: 400px ; " > <br> <br> {{ comment_form }} <br> <input type="submit" value="оставить коммент"> <br> </div> {% if commentss %} {% for comment in commentss %} <div class="container" > <div class="panel panel-default" style="color: #4363A3 ;" id="Comment"> <div style="color: #4363A3 ;" … -
How to use mysql database data into FusionCharts in Django
I want to Use the data which is store in MySQL database by running queries and show the data with the help of FusionCharts. Now the fusionCharts uses json data format but MySQL data does not. How can I display my database data with fusionCharts.I need help with the code. This is my views.py (This is not all of the views.py just the relevent one.) from .fusioncharts import FusionCharts def chart(request): # Create an object for the column2d chart using the FusionCharts class constructor monthly = FusionCharts('column2d', 'ex1', '600', '400', 'chart-1', 'json', """{ "chart": { "caption": "Monthly offense", "subcaption": "Month of July", "xaxisname": "Country", "yaxisname": "Offenses", "numbersuffix": "", "theme": "fusion" }, "data": [ { "label": "Jan", "value": "290" }, { "label": "Feb", "value": "260" }, { "label": "Mar", "value": "180" }, { "label": "April", "value": "140" }, { "label": "May", "value": "115" }, { "label": "June", "value": "100" }, { "label": "July", "value": "30" }, { "label": "Aug", "value": "30" }, { "label": "Sept", "value": "30" }, { "label": "Oct", "value": "30" }, { "label": "Nov", "value": "30" }, { "label": "Dec", "value": "30" } ] }""") context = { 'all_count': all_count, 'total_high': total_high, 'total_medium': total_medium, 'total_low': total_low, 'monthly': monthly.render(), … -
WSGIPassAuthentication does not take affect with customized authentication
i' ve the following setup: django: 2.2.1 python: 3.5.2 mysql-server: 5.7 apache2: 2.4.25-3+deb9u7 and i use my own authentication backend: common/backends.py class MyOwnAuthenticationBackend(ModelBackend): def authenticate(self, username=None, password=None): ... def get_user(self, username): ... . /etc/apache2/sites-enabled/sprj.conf <VirtualHost *:80> ServerName 127.0.0.25 ServerAlias sprj.localhost sprj.somedomain1.hu sprj.somedomain2.hu DocumentRoot /usr/share/sprj <Directory /usr/share/sprj> Order allow,deny Allow from all WSGIPassAuthorization On </Directory> WSGIDaemonProcess sprj.djangoserver user=sprj processes=10 threads=20 display-name=%{GROUP} python-path=/usr/share/sprj:/home/sprj/.virtualenvs/sprj/lib/python3.5/site-packages WSGIProcessGroup sprj.djangoserver WSGIPassAuthorization On WSGIScriptAlias / /usr/share/sprj/sprj/wsgi.py CustomLog ${APACHE_LOG_DIR}/sprj-access.log combined ErrorLog ${APACHE_LOG_DIR}/sprj-error.log LogLevel debug </VirtualHost> This works well, but i' d like to see the logged in username in the apache2 log files. For this i' ve the WSGIPassAuthorization On line in the conf file, but nothing seems to be changed (of course apache2 is restarted). What did i miss here? I read many other questions about it, but i can' t figure out how to dig deeper. It seems the header is not really changed (checking with tcpflow with and without the option). The wsgi.py file is the default one: wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sprj.settings') application = get_wsgi_application() . How can i check what do i miss? My goal would be to see the logged in username in the apache2 log files. -
Creating Custom FileField Datatype in Django
I want to create custom FileField which can store multiple files link in the single FileField and if possible I want to create a Custom Upload_to that can satisfy my need and there should not be any multiple entries for a single user in my Database. I have tried other Approaches such as Arrayfield with FileField but they don't work together as it is a limitation in Django I want to create custom FileField which can store multiple files link in the single FileField and if possible I want to create a Custom Upload_to that can satisfy my need and there should not be any multiple entries for a single user in my Database. or is there any other approach. -
How can I update a user field using this function on sign up in django?
I want to update field CustomUser (Custom User Model) field Origin_ip with a function like this, where would I place and call this? def get_client_signup_ip(reuqest): g = GeoIP2() x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for ip2 = '192.227.139.106' city = g.city(ip2) else: ip = request.META.get('REMOTE_ADDR') ip2 = '192.227.139.106' city = g.city(ip2) return ip I've tried placing this in my forms.py but request is not defined there, so I am unable to pass it. I'm not sure how to properly call this function from views.py in order to update a user field. urls.py urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] forms.py class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True) captcha = ReCaptchaField() class Meta: model = CustomUser fields = ("username", "email", "password1", "password2") def save(self, commit=True, request=True): # what is request=True doing here? user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] if commit: user.save() return user views.py class SignUp(generic.CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'signup.html' -
Receiving an error that my dict object has no attribute META in a Django app
I am trying to pull json data and display it on a page using Django. I am receiving the following error: 'dict' object has no attribute 'META' on line 36 of my views.py file which is the following: return render(request, 'base_generic.html', context=context) This came up in a search but I have the correct brackets for my context and I also found this but it is honestly just confusing me even further. Do you have any suggestions as to why this is happening or what I am doing wrong? Thank you so much and if there is anything else I can provide to make my question more clear I will do so. Thank you all for your time. views.py from django.shortcuts import render from datetime import datetime import requests def index(request): request = requests.get(MY_URL_IS_HERE).json() current_temperature = request['currently']['temperature'] current_cloud_cover = request['currently']['cloudCover'] current_humidity = request['currently']['humidity'] current_near_storm_distance = request['currently']['nearestStormDistance'] current_near_storm_bearing = request['currently']['nearestStormBearing'] current_precip_intensity = request['currently']['precipIntensity'] current_uv_index = request['currently']['uvIndex'] current_sunrise = datetime.fromtimestamp(request['daily']['data'][0]['sunriseTime']) current_sunset = datetime.fromtimestamp(request['daily']['data'][0]['sunsetTime']) test = 'test' context = { 'current_temperature':current_temperature, 'current_cloud_cover':current_cloud_cover, 'current_humidity':current_humidity, 'current_near_storm_distance':current_near_storm_distance, 'current_near_storm_bearing':current_near_storm_bearing, 'current_precip_intensity':current_precip_intensity, 'current_uv_index':current_uv_index, 'current_sunrise':current_sunrise, 'current_sunset':current_sunset, } return render(request, 'base_generic.html', context=context) generic_base.html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>weather</title>{% endblock %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" … -
Supervisorctl add environment variables
Is there a way on how to put/add environment variables in the staging server? Because in my local server, I have my api key inside .bash_profileand retrieving the key with API_KEY = os.getenv('API_KEY') The program works fine in localhost but when in the staging server, it raises an ImproperlyConfigured error and says that my API_KEY in settings.py is missing. -
Django sitemap urls http to https
py file is; class PostSitemap(Sitemap): changefreq = "never" priority = 0.5 def items(self): return Post.objects.published() def lastmod(self, obj): return obj.created_date I'm using SSL Certificate but sitemap.xml urls are http like; <sitemap> <loc>http://www.name.com/sitemap-post.xml</loc> </sitemap> How can i change http to https? -
Create Project Structure Using Python and Djagno
I created a small project using python, django, Html, css, javascript. So I created one project folder and two applications like(django pro, account app, projectapp). i don't know where to write code signup, login, forget password and reset password. Can anyone suggest a good structure? -
Django render and redirect URL
Hello i'm a newbie to Django, i'm currently having problem figure out how to redirect and return value I have a url with 2 parameters that are month and year . After clicking on it , it should redirect to page with url like so "list-working-sessions/year/month" with year and month parameters base on the action. urls.py url(r'^list-working-sessions/(?P<year>\w+?)/(?P<month>\w+?)/$', views.list_working_sessions, name='list_working_sessions') base.html <ul class="treeview-menu"> <li id="list-daily-task"> <a href="{% url 'list_working_sessions' %}"> <i class="fa fa-circle-o"></i>List Working Session</a> </li> </ul> The page have a table and a form to search by month and year: list_working_sessions.html <div class="box"> <div class="box-header"> <center> <h3 class="box-title">List Working Sessions</h3> </center> </div> <!-- /.box-header --> <div class="box-body"> <form class="form-horizontal" action="/list-working-sessions" method="GET"> {% csrf_token %} <div class="table-responsive"> <table class="table table-borderless" id="dynamic_field"> <tr> <th style="width:20%; border-top:none">Month</th> <th style="width:20%; border-top:none">Year</th> <th style="width:20%; border-top:none"></th> <th style="border-top:none"></th> </tr> <tr> <td style="border-top:none"> <select name="month" class="form-control" id="month" required> <option value="1" selected>1</option> <option value="2" selected>2</option> <option value="3" selected>3</option> <option value="4" selected>4</option> <option value="5" selected>5</option> <option value="6" selected>6</option> <option value="7" selected>7</option> <option value="8" selected>8</option> <option value="9" selected>9</option> <option value="10" selected>10</option> <option value="11" selected>11</option> <option value="12" selected>12</option> </select> </td> <td style="border-top:none"> <select name="year" class="form-control" id="year" required> <option value="2019" selected>2019</option> <option value="2020" selected>2020</option> </select> </td> <td style="border-top:none"><button type="submit" id="submit" class="btn btn-info">Send</button></td> … -
How display the model in the use i put a permissions
i want to do is like the admin i created a model and i create a user and i assign the user a permission and it display the model when i login it. My problem is i create my own login page connected to the username and password from the admin and when i login they directed to the html file i created. how to display the model in the html file like in the admin page ? is it like in the login file i create ? Login.View ? path('', auth_views.LoginView.as_view(template_name='login/Login.html'), name="login"), -
How do I optionally add results generated in my view to database?
I honestly don't really know how to describe this problem so I'll list out the steps I want it to accomplish. Django displays web page with a single form User enters something into that form and presses Submit Django takes that input and generates something dynamic and that is then shown to the user. This is what I've accomplished so far, but I'm having trouble figuring out what to do for the steps below. The dynamically generated output has a button next to it called "Save", which will optionally save that output to the users database. Can someone give me hints on how to tackle this? -
SSR + CSR (?) can I add SSR to a vue-cli 3 project? (vue-cli 3 + django)
I'm using the Vue-CLI 3 and Django together. I think it might be a basic question, I can't sure that is right structure. Vue-CLI vue vue-router vuex Django (Django restframework) router (we have url.py for each page) API _base.html (_base.html included on every page, and main.js located in frontend/dist/static/main.js) <body> {{% static main.js %}} </body> It can be access every pages with SSR x CSR load vue component on routed in Vue-CLI without page loading(=CSR) when I click a link that defined router-link. Django return 404 when try to access not defined page url (e.g. GET http://localhost:8000/aaa). I would be great if you could give me some advice. thanks. -
pass serializer errors as a response in a list format
I am using graphene_django alongside rest_framework serializers. When i get validation issue, I am getting the error as follow "{'email': [ErrorDetail(string='user with this Email Address already exists.', code='unique')]}", How can I pass the error in a List way like I am passing when password do not match? here is how I am doing right now class Register(graphene.Mutation): class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) user = graphene.Field(UserQuery) token = graphene.String() success = graphene.Boolean() errors = graphene.List(graphene.String) @staticmethod def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: serializer = RegistrationSerializer(data={'email': email, 'password': password, 'is_confirmed': False}) print('#########Serializer########', serializer) if serializer.is_valid(raise_exception=True): print('serializer is valid') user = serializer.save() auth = authenticate(username=email, password=password) login(info.context, auth) return Register(success=True, user=user, token=get_token(auth)) print('############serializer errors##########', serializer.errors) return Register(success=False, token=None, errors=['email/password', 'Unable to login']) except ValidationError as e: print("validation error", e) return Register(success=False, errors=[e]) return Register(success=False, errors=['password', 'password is not matching']) -
High memcached connections after django upgradation
We recently upgraded our django site from 1.6 to 1.11 which is running on python2. Recently we have observed memcahed down and we have found in error log below message. [Thu Jul 25 12:56:58.342182 2019] [:error] [pid 32575:tid 140131889002240] ServerDown: error 47 from memcached_get(key): (140131092682816) SERVER HAS FAILED AND IS DISABLED UNTIL TIMED RETRY, host: localhost:11211 -> libmemcached/get.cc:314 I am using memcached default configurations and django default settings. Can any one suggest me fix for this? And best configurtation for django settings? Thanks