Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form with variable type
How would you make a price field in Django form? The input could be either price (float) or value from select (for free, offer, by agreement, etc). In database, it's stored in FloatField (negative values has special meaning). Is there a way to make it through Django form model? -
django passing a csv to another function that downloads this csv
i'm trying to pass a pandas dataframe (changed to csv file) to another fucntion(the download function) in django. the user should push a button and the dataframe(in csv format) should be ready to download for the user. i'm getting a missing 1 required positional argument: 'x' error. i've looked around on Stack but could not find an answer for this question. I think the problem is located in the def export because of the error I've got. but i've no idea how to fix it. views.py def result(request): if request.method =='POST': # some code to create the dataframe def process_file(file): data = file return data.to_csv x = process_file(df) #df for the dataframe created above return render(request, 'results.html', {'somedata':somedata,}), x def export(request, x): csv = x response = HttpResponse(csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export.csv"' return response -
Django Log to Telegram is not working and not creating model table
So, I have been working on utilizing this package: https://pypi.org/project/django-log-to-telegram/ I went through the exact steps the manual has: pip installing django log to telegram package, Added the telegram bot token after creating the telegram bot LOG_TO_TELEGRAM_BOT_TOKEN = '1489551033:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' And adding LOGGING onto the settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'handlers': { 'telegram_log': { 'level': 'ERROR', 'filters': [], 'class': 'django_log_to_telegram.log.AdminTelegramHandler', 'bot_token': LOG_TO_TELEGRAM_BOT_TOKEN, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['telegram_log'], 'level': 'ERROR', 'propagate': True, }, }, } Then I ran 'python manage.py migrate' to create the django-log-to-telegram models. It's supposed to create the django-log-to-telegram table in the database. However, I do not see any new database. -
Exclude by table name - django
I have raw query: select n.nspname as table_schema, c.relname as table_name from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.relkind = 'r' and n.nspname not in ('information_schema','pg_catalog') and c.reltuples = 0 order by table_schema, table_name; which return all empty tables and I saved table names to models array. Now I would like exclude models from queryset: ContentType.objects.all().exclude(table_name__in=models) but I havn't access to table name in queryset. How can I do it? -
use django model's field value inside href tag in template
Here the issue that I am facing. Let's say I have a model with two field. Field1 is a string value and Field2 one contains a url link. I want to render Field1 and the user can click on Field1 and gets redirected to template at Field2 url. Here is what I have been trying: <td>{{class.Class}}<a href="{{ class.extra_details_view }}"></a></td> #class = Field1 #extra_detail_view = Field2 (link) this renders Class values just fine but does not let me click it. I don't know what else to try to get the desired output. -
My code fail to loop the single card on the template but the entire thing works fine
Hi there! this code fail to for loop in </d {% for user in userprofile %} {{ user.userprofile.title}} R{{ user.userprofile.price }} Mobile Phones » Brand {{ user.userprofile.publish_date}} {{ user.userprofile.City }} {% endfor %} my views class ClassifiedsView(ListView): model = UserProfile paginate_by = 10 # if pagination is desired template_name = 'all_classifieds.html' def get_context_data(self): context = super().get_context_data() objects = UserProfile.objects.all() context['object'] = objects return context then temple i call it a temple it work but can't for-loop and on my urlemphasized text class UserProfile(models.Model): user = models.OneToOneField(User, null='True', blank='True',related_name='userprofile' ,on_delete=models.CASCADE) title = models.CharField(max_length=120, blank=True,)path('<all_classifieds>/', ClassifiedsView.as_view(), name='all_classifieds'), any suppurt -
Error with Django Class 'City' has no 'objects' member
I'm learning Django and having a blast, I'm trying to build a weather app using Django and the Open Weather API. I seem to have run into an error that's making my head spin and I can't figure it out, I am trying to return a list of all the data in the database but I get this error Class 'City' has no 'objects' member" Here is my models.py file from django.db import models class City(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name And here is my views.py file import requests from django.shortcuts import render from .models import City from .forms import CityForm def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q{}&units=imperial&appid=YOUR_API_KEY' if request.method == 'POST': form = CityForm(request.POST) form.save() form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather = { 'city' : city.name, 'temperature' : r['main']['temp'], 'description' : r['weather'][0]['description'], 'icon' : r['weather'][0]['icon'], } weather_data.append(city_weather) context = {'weather_data' : weather_data, 'form' : form} return render(request, 'weather/weather.html', context) Any help will be greatly appreciated! -
Django RecursionError: maximum recursion depth exceeded while building a query
I am trying to build complex query this way: q = Q() if contacts: for contact in contacts: q |= Q(phone__icontains=contact) for contact in contacts: q |= Q(email__icontains=contact) if name: q |= Q(full_name__icontains=name) duplicates = Candidate.objects.filter( q ).values_list('pk', flat=True) But I get RecursionError: maximum recursion depth exceeded on this area. Not sure, what part of these code is recursive, and have no idea where to look for answer. -
Where is this self.add_error adds the error to?
I'm having a hard time trying to figure out the following code: from django import forms from django.contrib.auth.hashers import check_password class CheckPasswordForm(forms.Form): password = forms.CharField(label='password_check', widget=forms.PasswordInput( attrs={'class': 'form-control',}), ) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user def clean(self): cleaned_data = super().clean() password = cleaned_data.get('password') confirm_password = self.user.password if password: if not check_password(password, confirm_password): self.add_error('password', 'password is wrong') here, I don't get the self.add_error('password', 'password is wrong') part. In the documentation, it says that the password here is the field in add_error('field', 'error'). So, is the error being added to the password field? or is it being added to the following part? def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user because if I have to access this error in the html template, I would have to do something like this, {% if password_form.password.errors %} and if it means accessing errors from password field, it should mean that the error is added to the password field... but the self.add_error part confuses me -
I am not able to link pages in Django
I believe I have linked my urls, views and templates very well but I don't why I am getting the error. urls.py from django.urls import path from .views import * urlpatterns = [ path('', home, name='home'), path('legal/', legal, name='legal') ] views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'base/base.html') template <nav class="nav-menu d-none d-lg-block"> <ul> <li><a href="{% url 'home' %}">Inicio</a></li> <li><a href="{% url 'about' %}">Quienes somos</a></li> </ul> </nav> -
XML error while visiting the localhost:8000/sitemaps.xml | Django
When I visit the localhost:8000/sitemap.xml It shows This XML file does not appear to have any style information associated with it. The document tree is shown below. The tree <urlset> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> Where I expected this tree to be more like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> I have followed the django documentation as well as seen other websites. But every time I get the same result. Can you please help. How can I remove the XML error and show my xml like this <?xml version="1.0" encoding="utf-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://127.0.0.1:8000/en/product/detail/health-and-care/beauty/cream/dcaad0bb-4e30-4166-b447-508e6ad12ddf/</loc> <lastmod>2020-11-16</lastmod> <changefreq>weekly</changefreq> <priority>0.9</priority> </url> </urlset> settings.py INSTALED_APPS = [ # # "django.contrib.sites", "django.contrib.sitemaps", # # ] SITE_ID = 1 sitemaps.py from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from .models import Product # Inherting the Sitemap class of the sitempas module. class ProductSitemap(Sitemap): # These two attributes indicate the change frequency # and the relevencae in the webiste. changefreq = 'weekly' priority = 0.9 def items(self): # This method return the QuerySet of objects # to include in the sitemap products = Product.objects.all() products = products.prefetch_related('seller_product') return products def lastmod(self, obj): # receives each object returned by … -
GIS plugin in Django is throwing openssl error. undefined symbol: EVP_md2
I am trying to use the Geodjango plugin django.contrib.gis for my project. But as soon as I add it to the INSTALLED_APPS I am getting the following traceback. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 24, in ready self.module.autodiscover() File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/ec2-user/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/admin/widgets.py", line 3, in <module> from django.contrib.gis.gdal import GDALException File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/__init__.py", line 28, in <module> from django.contrib.gis.gdal.datasource import DataSource File "/home/ec2-user/anaconda3/lib/python3.8/site-packages/django/contrib/gis/gdal/datasource.py", line 39, in <module> from … -
How to implement Search/Filter and Pagination in FBV
I am trying to implement Search Functionality and Pagination for Django based (model) table.1. At a time only one is working please find the views.py and I am not able to figure out how to manage logically in views.py so that both of them work together. Views.py from .filters import ShiftChangeFilter from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def retrieve_view(request): # if not request.user.email.endswith('@apple.com'): # return redirect('/logout') # post_list = ShiftChange.objects.all() # for pagination allgenesys = ShiftChange.objects.all() paginator = Paginator(allgenesys,10) page_number = request.GET.get('page') try: allgenesys = paginator.page(page_number) except PageNotAnInteger: allgenesys = paginator.page(1) except EmptyPage: allgenesys = paginator.page(paginator.num_pages) # allgenesys = ShiftChange.objects.filter(EmailID=request.user.email) #For filtering using 'django_filters', genesys_list = ShiftChange.objects.all() genesys_filter = ShiftChangeFilter(request.GET, queryset=genesys_list) allgenesys = genesys_filter.qs return render(request, 'apple/shift2.html', {'allgenesys': allgenesys,'genesys_filter':genesys_filter}) pagination.html <style> .pagination { float: left; </style> {% if page.has_other_pages %} <ul class="pagination"> {% if page.has_previous %} <li><a href="?page={{ page.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in page.paginator.page_range %} {% if page.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page.has_next %} <li><a href="?page={{ page.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif … -
Custom login using Django user model
I'm trying to make my custom login form using Django's user template. What i'm trying to do is the authentication of a user using username and password. Register works, every user is registered correctly, but when i'm trying to login using the correct fields, my: user = authenticate(request, username=username, password=password) returns None as value. Here is my def login_view in views.py (i'm using logger to know what is going on) def login_view(request): import logging logging.basicConfig(filename='mylog.log', level=logging.DEBUG) logging.debug('start') title = 'LOGIN' form = UserLoginForm() if request.user.is_authenticated: return redirect('board.html') if request.method == 'POST': form = UserLoginForm(request=request, data=request.POST) username= request.POST.get('username') password= request.POST.get('password') print(form.errors) if form.is_valid(): logging.debug('form is valid') logging.debug('called form.save(), result=%s', UserLoginForm) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) user = authenticate(request, username=username, password=password) logging.debug('user, result=%s', user) #### if user is not None: login(request, user) logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) messages.info(request, "You are now logged in as {username}") return redirect('board.html') else: messages.error(request, "Invalid username or password.") logging.debug('first else') return redirect('/') #### else: print(form.errors) logging.debug('errore form: , result=%s', form.errors) messages.error(request, "Invalid username or password.") logging.debug('second else') username = request.POST.get('username') password = request.POST.get('password') messages.error(request, "Invalid username or password.") logging.debug('username, result=%s', username) logging.debug('password, result=%s', password) return redirect('/') return render(request=request, template_name="login.html", context={"form": form , "title":title}) And that's … -
i want to count the number of correct answers in jS or jquery
I want to count the number of correct answers and display it.i tried many ways but couldn't go through.will appreciate if anybody can help me .Thanks in advance. {% extends 'base.html' %} {% block title%}Quiz{% endblock title %} {% block content %} <div class=" text-danger mt-5 text-center"> <!-- <h2><b id="count">Timer</b></h2> --> <h3>+++Quiz on Indian Politics+++</h3> <hr> </div> <div class="pt-5"> {% for item in obj %} <table> <tr> <h2>Q{{item.id}}. {{item.question}}</h2><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt1" value="{{item.opt1}}">&nbsp;{{item.opt1}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt2" value="{{item.op2}}">&nbsp;{{item.opt2}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt3" value="{{item.opt3}}">&nbsp;{{item.opt3}}</input><br> </tr> <tr> <input type="radio" class="rd" name="{{item.id}}" id="opt4" value="{{item.opt4}}">&nbsp;{{item.opt4}}</input><br> </tr> <tr> <label id="lb" class="rd" name="{{item.id}}" value="{{item.cor_ans}}" style='display:none;color:green'><b>The correct answer is: {{item.cor_ans}}</b></label> </tr> <tr> </tr> </table> <hr> {% endfor %} <div class="pt-4"> <button type="submit" class="btn btn-success" id="btn">Submit</button> </div> <div class="pt-3"> <b id="counter"></b> <b id="ans"></b> </div> </div> {% endblock content %} {% block scripts %} <script> const rad = document.getElementsByClassName('rd') const input = document.getElementsByTagName('input') const bt = document.getElementById('btn') const label = document.getElementsByTagName('label') const counter = document.getElementById('counter') var score = 0; bt.onclick = function() {} // JQuery code $(document).ready(function() { $('#btn').click(function() { $('.rd').show(); $('.rd').attr("disabled", true); }); }); // # javascript code bt.addEventListener('click', function() { for (i = 0; i < input.length; … -
Docker-compose with Django, MongoDB using Djongo ERROR - pymongo.errors.ServerSelectionTimeoutError
I want to get a django app running using djongo with mongo, and docker. My setup looks like this: docker-compose.yml version: '3.7' services: webserver: build: context: . ports: - "8000:8000" volumes: - ./webserver:/webserver command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 links: - mongo depends_on: - migration mongo: image: mongo:latest restart: unless-stopped volumes: - ./mongo/data/db:/data/db environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: raspicam ports: - "27017:27017" migration: build: . image: app command: sh -c "python manage.py migrate" volumes: - ./webserver:/webserver links: - mongo depends_on: - make_migrations make_migrations: build: . image: app command: sh -c "python manage.py makemigrations" volumes: - ./webserver:/webserver links: - mongo depends_on: - mongo Dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" ENV LIBRARY_PATH=/lib:/usr/lib COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers jpeg-dev libjpeg-turbo RUN apk add build-base python3-dev zlib-dev RUN pip install --upgrade pip RUN pip install --no-cache-dir -r /requirements.txt RUN apk add libjpeg RUN apk del .tmp RUN mkdir /webserver COPY ./webserver /webserver WORKDIR /webserver COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] settings.py DATABASES = { "default": … -
Class 'staffdata' has no 'objects' memberpylint(no-member)
from django.shortcuts import render,redirect from staff.forms import StaffdataForm from staff.models import staffdata imported staffdataform and staff data module from staff app. # Create your views here. def home(request): return render(request,'home.html') def stafflists(request): allstaffs=staffdata.objects.all() return render(request,'stafflists.html',{'staff':allstaffs}) created two functions home and stafflist . getting error in second function. please help me -
Retrivieng data from database using objects.all() not working
I am new to django and python and I am trying to retrieve some entries from a a database, but when calling Criminal.objects.all() I don't get anything, hence "Nothing" is displayed. However, I checked and I have 2 entries in my table. models.py from django.db import models # Create your models here. class Criminal(models.Model): cid = models.CharField(max_length=20) cssn = models.IntegerField() cfirst_name = models.CharField(max_length=20) clast_name = models.CharField(max_length=20) cdob = models.DateField() cpob = models.CharField(max_length=15) class Meta: managed = True db_table = "criminal" views.py from django.http import * from django.shortcuts import render from .models import * # Create your views here. def home(request): return render(request, 'home.html', {'name': 'SE mini project'}) def index(request): criminals = Criminal.objects.all() return render(request, 'home.html', {'obj': criminals}) home.html {% extends 'base.html' %} {% block content %} <h1> {{name}} </h1> {% if obj %} {% for v in obj %} {{v.cfirst_name}}<br> {{v.clast_name}}<br> {{v.cdob}}<br> {{v.cpob}}<br> {% endfor %} {% else %} Nothing {% endif %} {% endblock %} -
Send email using Django management command
I want to send emails using Django management commands and o365 (outlook) settings.I have achieved sending normal email via the application earlier but how to do the same from command line. Any ideas on how to achieve this? -
Save an InMemoryUploadedFile to OS in Django
I want to save a temporary uploaded file in the django os. How can I do that ? The file is received as the following: file_obj = request.FILES['document'] I tried the following method but it saves the file in my AWS account but I just want to save it in the os and delete is as soon as I am done with it. file_name = default_storage.save(file_obj.name, file_obj) file_url = default_storage.url(file_name) when I pass the file_url in a function and try to read it I get the following error: OSError: [Errno 22] Invalid argument: 'https://xxxxxxxx.s3.amazonaws.com/media/Sample%20PFEP%20(2).xlsx' I face no problem when I read the same file from local in my jupyter notebook. Why is that ? -
Reactjs- React cannot resolve module in my directory
this is how my react app looks like right now. So I want to import the css file app_style.css into status_bar.jsx How can I do this? When I try importing the file like this import React, { Component } from 'react'; import '.../static/css/app_style.css' I get the following error: Compiling... Failed to compile. ./src/components/general_interface/status_bar.jsx Module not found: Can't resolve '.../static/css/app_style.css' in 'C:\Users\iyapp\OneDrive\Desktop\python projects\PixSirius\PixSirius\react-app\src\components\general_interface' Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp' Why is this happening? How can I fix this? Also, I am using Django for the backend. This is my static_files configuration: # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'react-app/src/static'), ] Is there any better area/ way to store my static css files and import them into react-js? Please help me, thanks a lot! -
django.template.exceptions.TemplateSyntaxError: Unclosed tag on line 2: 'block'. Looking for one of: endblock. in django
I am making a django app. This is my index.html template: {% extends "blog/base.html" %} {% block content %} {% if latest_post %} <div class="jumbotron p-4 p-md-5 text-white rounded bg-dark"> <div class="col-md-6 px-0"> <h1 class="display-4 font-italic"> {{ latest_post.title }} </h1> <p class="lead my-3"> {{ latest_post.body|truncatewords:30 }} </p> <p class="lead mb-0"> <a href="{% url 'blog:post' post.pk %}" class="text-white font-weight-bold">Continue reading...</a> </p> </div> </div> {% endif %} {% for post in posts %} <div class="row mb-2"> <div class="col-md-6"> <div class="row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative" > <div class="col p-4 d-flex flex-column position-static"> <h3 class="mb-0">{{ post.title }}</h3> <div class="mb-1 text-muted">{{ post.date_posted }}</div> <p class="mb-auto"> {{ post.body|truncatewords:30 }} </p> <a href="{% url 'blog:post' post.pk %}" class="stretched-link">Continue reading</a> {% endfor %} {% endblock %} However, I am getting this error: django.template.exceptions.TemplateSyntaxError: Unclosed tag on line 2: 'block'. Looking for one of: endblock. in django I have made sure: All the blocks are closed There is no whitespaces between the percent signs and the block names I am not missing any percent signs Please help me -
getting error while using model form for model in model_or_iterable: TypeError: 'ModelFormMetaclass' object is not iterable
i was using model form in a django project but while registering model in admin i m getting this error my admin.py from django.contrib import admin from .models import contactForm class contactFormAdmin(admin.ModelAdmin): model = contactForm admin.site.register(contactForm, contactFormAdmin) my model.py from django.db import models from django.forms import ModelForm from django.core.validators import RegexValidator class contactForm(models.Model): name = models.CharField(max_length=255) Phonenumber = models.CharField(max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) email = models.EmailField(max_length=254) def __str__(self): return self.name class contactForm(ModelForm): class Meta: model = contactForm fields = '__all__' -
Django importError (cannot import name 'six')
serializer.py: from .models import stock from rest_framework import serializers class StockSerializer(serializers.ModelSerializer): class Meta: model = stock fields = ('id', 'stock_name', 'price', 'stock_gain', 'market_name') views.py: from django.shortcuts import render from rest_framework import viewsets, filters from .seriaizer import StockSerializer from .models import stock from django_filters.rest_framework import DjangoFilterBackend class StockViews(viewsets.ModelViewSet): queryset = stock.objects.all() serializer_class = StockSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) search_fields = ('stock_name',) ordering = ('stock_gain',) urls.py: from django.contrib import admin from django.conf.urls import url from django.urls import path, include from rest_framework import routers from restapp.views import StockViews from restapp import views router = routers.DefaultRouter() router.register('stock', views.StockViews) urlpatterns = [ url(r'', include(router.urls)), path('admin/', admin.site.urls), ] this error comes to me: ImportError: cannot import name 'six' from 'django.utils' (C:\Users\hajar\OneDrive\Desktop\stockm\env\lib\site-packages\django\utils_init_.py) i installes six pip install six but not work???? may any one can help my?! -
Domain name redirects to ip:port after page loads
I am using nginx for reverse proxy. Here is my .conf configuration: listen 80 default_server; server_name xyz.com; return 301 http//:www.xyz.com$request_uri; } server { listen 80; listen [::]:80; access_log /var/log/nginx/reverse-access.log; error_log /var/log/nginx/reverse-error.log; location / { proxy_pass http://xx.xxx.xxx.xxx:8000; } } when I type xyz.com it serves my content but shows the ip and ports. How can I stop my ip and ports to appear on browser and show only domain name even after site is loaded.