Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin TeaxtArea 100% width
I've made my CharField view as Text area as foolows: # admin.py class PostAdminForm(forms.ModelForm): text = forms.CharField(widget=forms.Textarea) class Meta: model = Post fields = '__all__' class PostAdmin(admin.ModelAdmin): form = PostAdminForm And it looks like this: admin page So I want to set area's width to 100% - to make it occupy all side from the rigth, how should I to do this? -
How can I show all the images of a model in one page?
I followed This tutorial to set up the model for my gallery page where I'll be showing pictures related to each topic. In the tutorial, the images were shown in a separate page to where the post titles was displayed. However, I want to display all the images , organized by placing them under their respective titles, in one page. How can I do this? Thank you in advance -
Can't link leaflet js file to my html in django
I am new to leaflet and have just created my first mapping app using Django. It is an awesome program but I just wanted to change the style of my map. I am drawing from this amazing resource however I am having trouble linking the js file with the HTML. I have never connected JS to HTML particularly within Django (not sure if it makes a difference). But I am returning 404s 24/Aug/2020 12:19:16] "GET /static/js/leaflet-providers.js HTTP/1.1" 404 1695 I have stored the js file in a folder called static, based on some good practise I read about (please disabuse me of this if it is not good practise!) My relevant chunk of code is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Anybody</title> <!---leaflet css ---> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <!---leaflet JS --> <!-- Make sure you put this AFTER Leaflet's CSS --> <script src="http://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script> <script src="static/js/leaflet-providers.js"/> </script> -
Is there a way I can solve this syntax error?
Am getting SyntaxError: 'return' outside function on my code. I have checked the indentation and it's fine, can someone help me? Here's my code. from django.shortcuts import render from .forms import form from django.core.mail import send_mail from django.http import HttpResponse, HttpResponseRedirect def index(request): return render(request, 'index.html', {}) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['name'] message = form.cleaned_data['name'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['hillariouskelly@gmail.com'] if cc_myself: recipients.append(sender) send_mail(name, email, message, sender, recipients) return HttpResponseRedirect('/thanks/') -
Django : reference to models in view --> Local variable might be referenced before assigment
I have a small Django-app were I want to manage two stock portfolios. I created two tables (SecuritiesSVR and SecuritiesAHT) with the same structure (based on an abstract model). In the url I added an argument 'ptf' : portfolio/str:ptf/change_position Now I want to access these two tables via a view as underneath: @login_required def change_position(request, ptf, symbol): if ptf == 'aht': Securities = SecuritiesAHT if ptf == 'svr': Securities = SecuritiesSVR security = Securities.objects.get(pk=symbol) ... In PyCharm I get a warning on my variable Securities : "Local variable might be referenced before assigment'. However, the view seems to work correctly. Does anyone know why I get this warning? -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in Python Django
Traceback (most recent call last): File "C:\users\xx.virtualenvs\xx-SFDz4XJ_\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\users...virtualenvs\xx-SFDz4XJ_\lib\site-packages\django\core\handlers\base.py", line 115, in ge t_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xx.virtualenvs\xx-SFDz4XJ\lib\site-packages\django\core\handlers\base.py", line 113, in ge t_response response = wrapped_callback(request, callback_args, *callback_kwargs) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\contextlib.py", line 74, in inner return func(*args, **kwds) File "C:\Users\xx.virtualenvs\xx-SFDz4XJ\lib\site-packages\django\views\decorators\csrf.py", line 54, in w rapped_view return view_func(*args, **kwargs) File "D:\xx\ProjectSourceCode\xx\xx\xx\views.py", line 1942, in post_product post_response = requests.post(post_url, json=data_post, headers=headers).json() File "C:\Users\xx.virtualenvs\xx-SFDz4XJ_\lib\site-packages\requests\models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json_init_.py", line 348, in loads return _default_decoder.decode(s) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\users\xx\appdata\local\programs\python\python37-32\Lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Note: it's work fine in Window server but it's got this error in Linux server. -
How to create another user (students and teachers) table in django
I'm using django and have some confusion right now. I want to build something where teachers table will be in a onetomany relationship with students table. But I could not create another student table. Any advice or resource,please? -
Getting error converting data type nvarchar to numeric while saving django form to mssql database
I'm using django-pyodbc-azure with mssql and i have set some fields as foreign key in my models.py: class Production(models.Model): date = models.CharField(max_length=10, null=True) dateGr = models.DateField(auto_now=False, auto_now_add=False, null=True) comName = models.CharField(max_length=100, null=True) comId = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) prodName = models.CharField(max_length=100, null=True) prodId = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) gradeId = models.ForeignKey(ProductGrade, on_delete=models.CASCADE, null=True) gradeName = models.CharField(max_length=100, null=True) gradeType = models.CharField(max_length=3, null=True) gradeTypeId = models.ForeignKey(GradeType, on_delete=models.CASCADE, null=True) qty = models.FloatField(null=True) cap = models.FloatField(null=True) designCap = models.FloatField(null=True) plan = models.FloatField(null=True) unitId = models.ForeignKey(QtyUnit, on_delete=models.CASCADE, null=True) unit = models.CharField(max_length=20, null=True) And i have written my forms.py like this: class CreateProduction(forms.ModelForm): class Meta: model = Production fields = ['date', 'comId', 'prodId', 'gradeId', 'gradeTypeId', 'unitId', 'qty'] widgets = { 'date': forms.TextInput(attrs={'class': 'form-control', 'name': 'tdate', 'id': 'input-tdate'}), 'comId': forms.Select(attrs={'class': 'form-control'}), 'prodId': forms.Select(attrs={'class': "form-control"}), 'gradeId': forms.Select(attrs={'class': 'form-control'}), 'gradeTypeId': forms.Select(attrs={'class': 'form-control'}), 'unitId': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control', 'id': 'qty', 'type': 'number', 'value': '0'}), } def __init__(self, user, comId, *args, **kwargs): super(CreateProduction, self).__init__(*args, **kwargs) self.fields['comId'].queryset = Company.objects.filter(userId=user) self.fields['prodId'].queryset = Product.objects.filter(comId=comId) products = Product.objects.filter(comId=comId) self.fields['gradeId'].queryset = ProductGrade.objects.filter(prodId__in=products) The function that handles saving my form's data to database is as following: @login_required(login_url='login') @allowed_users(allowed_roles=['editor']) def create_production(request): print(request) if request.method == 'POST': comId = Company.objects.values_list('id', flat=True).get(userId=request.user) form = CreateProduction(request.user, comId, request.POST) if form.is_valid(): production = … -
update vue-chartjs yaxis max value
I am working on a project where i am implementing some charts. I need the Y-axis max value to change everytime the user changes the filters given. I Import an existing barchart from the vue-chartjs library. In the code there is a javascript file that has some defaults already: import { Bar } from 'vue-chartjs' import { hexToRGB } from "./utils"; import reactiveChartMixin from "./mixins/reactiveChart"; let defaultOptions = { tooltipFillColor: "rgba(0,0,0,0.5)", tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipFontSize: 14, tooltipFontStyle: "normal", tooltipFontColor: "#fff", tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", tooltipTitleFontSize: 14, tooltipTitleFontStyle: "bold", tooltipTitleFontColor: "#fff", tooltipYPadding: 6, tooltipXPadding: 6, tooltipCaretSize: 8, tooltipCornerRadius: 6, tooltipXOffset: 10, }, legend: { display: false }, scales: { yAxes: [{ ticks: { fontColor: "#9f9f9f", fontStyle: "bold", beginAtZero: true, stepSize: 10, padding: 10, display: true, min: 0, }, gridLines: { zeroLineColor: "transparent", display: false, drawBorder: false, color: '#9f9f9f', } }], xAxes: [{ barPercentage: 1, gridLines: { zeroLineColor: "white", display: false, drawBorder: false, color: 'transparent', }, ticks: { padding: 20, fontColor: "#9f9f9f", fontStyle: "bold" } }], legend: { display: true } } }; export default { name: 'BarChart', extends: Bar, mixins: [reactiveChartMixin], props: { labels: { type: [Object, Array], description: 'Chart labels. This is overridden when `data` … -
Creating a linked hashtag in markdown
I'm currently trying to parse markdown in django/python and linkify hashtags. There are some simple solutions to this: for tag in re.findall(r"(#[\d\w\.]+)", markdown): text_tag = tag.replace('#', '') markdown = markdown.replace( tag, f"[{tag}](/blog/?q=%23{text_tag})") This works well enough, but converts everything with a # into a link. Eg: https://example.com/xyz/#section-on-page gets linkified. It also gets linkified if it is currently inside of a link itself. Internal links are also broken as Link get linkified. Here's a comprehensive case: #hello This is an #example of some text with #hash-tags - http://www.example.com/#not-hashtag but dont want the link #hello #goodbye #summer #helloagain #goodbye This is #cool, yes it is #radaf! I like this #tool. [Link](#not-a-hashtag) [Link](https://example/#also-not) <a href="#this-neither">Hai</a> Thanks -
Django render Dictionary
Why cant i acsess the dict that i am making here: def kalkuler(request): fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister") kalkuler = ProduktKalkureing.objects.all() beregning = {} if request.method == "POST": omkrets = request.POST['omkrets'] print(omkrets) for i in kalkuler: kalk = math.ceil((int(omkrets)/i.lengde)*1000) add = ({'produkt_tittel': i.produkt.produkt_tittel, 'produkt_bilde': i.produkt.produkt_bilde, 'produkt_info': i.produkt.produkt_info, 'produkt_link': i.produkt.produkt_link, 'pris_heltall': i.produkt.pris_heltall, 'antall_kalk': kalk, 'total_kost': kalk * i.produkt.pris_heltall }) beregning.update(add) print(beregning) context = {'kalkuler': kalkuler, 'beregning': beregning} return render(request, 'frontend/kalkuler/fotlist_kalkuler.html', context) With the standard django code? {% for b in beregning %} {{b.produkt_bilde}} {% endfor %} Also when i make the dictionary it only adds the last value. How do i make it so it adds every value. -
Django graphene GraphQL mutation to create foreign key with get_or_create
Is it possible to write a Graphql mutation with get_or_create I have models: class Person(models.Model): name = models.CharField() address = models.CharField() class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() name = models.CharField() and for schema.py class PersonType(DjangoObjectType): class Meta: model = Person class BlogType(DjangoObjectType): class Meta: model = Blog I want to create a mutation for Blog where I create Person if it is missing: class CreateBlog(graphene.Mutation): blog = graphene.Field(BlogType) class Arguments: person=graphene.String() name = graphene.String(required=True) text = graphene.String() @staticmethod def mutate(root, info, **input): person = Person.objects.get(name=person) blog = Blog.objects.get(person=person, name=name,text=text) blog.save() return CreateBlog(blog=blog) Mutation query: mutation{ CreateBlog(name:"Harry Potter", person:"JK Rowing", text:"HI HI HI"){ blog{ name text person{ name } } } } Is it possible to use get_or_create to create the foreign key person if unavailable and get the id if it is with a single query? I tried the following but got "local variable 'doc' referenced before assignment" class CreateBlog(graphene.Mutation): blog = graphene.Field(BlogType) class Arguments: person=graphene.String() address =graphene.String() name = graphene.String(required=True) text = graphene.String() @staticmethod def mutate(root, info, **input): person, _ = Person.objects.get_or_create(name=person, address = address) blog, _ = Blog.objects.get_or_create(person=person, name=name,text=text) blog.save() return CreateBlog(blog=blog) Query: mutation{ CreateBlog(name:"Harry Potter", person:"JK Rowing", address: "address", text:"HI HI HI"){ … -
How redirect to alogin page in html Django if user is not authinticated
How to in HtMl to redirect user if it is noit registered using this template. I want to redirect if not registered to Login page {% if user.is_authenticated %} <p>Authenticated user</p> {% else %} redirect to 'login' page {% endif %} I have in settings.py LOGOUT_REDIRECT_URL = 'login' -
Install django-simple-captcha have some error
Install Django-simple-captcha via pip: pip install Django-simple-captcha - success Add captcha to the INSTALLED_APPS in your settings.py - Done! Run python manage.py migrate - have some problem File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\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 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'captchausers' Who can tell me what can I do? -
In Django for loop in html template is not working correctly
i want the report name in the dropdown menu but i'm not able to fetch the items for dictionary views.py def add(request): report_item = {} if request.method == "POST": src=request.POST['src'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] report_item = {'src':src, 'width':width, 'height':height, 'name':name} #template = loader.get_template('report_one.html') #context={'report_item':report_item} return render(request, 'report_one.html', report_item) else: return render(request, 'report_one.html', report_item) index.html {% for key, value in report_item.items %} <li> <a href="{% url 'report:add' %}">{{ value.name }}</a> </li> {% endfor %} -
How to iterate on Django prefetch related queries?
So I have written a query which is : queryset = Professional.objects.filter( slug=slug ).prefetch_related( Prefetch('educations', queryset=ProfessionalEducation.objects.filter(is_archived=False).order_by('-enrolled_date')), Prefetch('skills', queryset=ProfessionalSkill.objects.filter(is_archived=False).order_by('skill_name')), Prefetch('work_experiences', queryset=WorkExperience.objects.filter(is_archived=False).order_by('-start_date')), Prefetch('portfolios', queryset=Portfolio.objects.filter(is_archived=False).order_by('created_at')), Prefetch('memberships', queryset=Membership.objects.filter(is_archived=False).order_by('created_at')), Prefetch('certifications', queryset=Certification.objects.filter(is_archived=False).order_by('-issue_date')), Prefetch('references', queryset=Reference.objects.filter(is_archived=False).order_by('created_at')) ) I can iterate on this queryset like: for obj in queryset: print(obj.full_name) print(obj.email) etc. But How can I able to get the value of like prefetch educations value or skills value? I am tried many way but couldn't succeed. -
Django Rest framework request.data is not working
I have gone through several solutions on stackoverflow but couldn't solve this that's why asking this type of question again: My code : @api_view(['POST']) def RegisterUserAPI(request): print("\n\n=================== 1 =====================") print("Request : ",request) print("DATA : ",request.data) print("================ 2 ========================= .... .... I was trying to debug but request.data is the reason for the error, I want take some values from request and want to perform some other tasks that's why trying to see request.data Error: =================== 1 ===================== Request : <rest_framework.request.Request object at 0x000001F800E3C978> Internal Server Error: /api/register/ Traceback (most recent call last): File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response response = response.render() File "D:\LocalProject\myvenv\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 680, in get_context 'content': self.get_content(renderer, data, accepted_media_type, renderer_context), File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 413, in get_content content = renderer.render(data, accepted_media_type, renderer_context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\91762\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\91762\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", … -
Django admin not loading individual app pages
I've just set up a new local version of my django application, and all working fine until I checked on the django admin. 127.0.0.1:8000/admin works fine and brings up the usual Django Admin homepage with full list of apps, but when I click into any of the individual app elements it breaks. The URL changes, but instead of displaying that app's admin site it shows an oddly rendered version of the admin homepage, with the app list collapsed on left side of screen (see screenshots below) Can't immediately see which parts of codebase could be relevant here, so please request copies of any code you want to see. The correctly displayed Django Admin homepage How it renders when I click into any of the individual app/model admin sites As above, with list of all apps expanded from left -
Django custom added permissions is not working - Django
I have implemented some custom permissions for my model. Custom added permissions are reflecting on Admin panel and im able to assign the same to Group/User. But when im trying to use those permissions in template then its not working. Please find the below codes and help. Thanks in advance. Model : class Painter(models.Model): user = models.OneToOneField('main.CustomUser', on_delete=models.CASCADE, related_name='+') code = models.CharField(max_length=100, unique=True) painter_or_not = models.CharField(choices=(('Yes', 'Yes'), ('No', 'No')), null=True, max_length=20) tse_verified = models.CharField(choices=(('Yes', 'Yes'), ('No', 'No')), max_length=20) registration_via = models.CharField(choices=(('App', 'App'), ('Admin', 'Admin'), ('Offline', 'Offline')), max_length=20) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile = models.CharField(max_length=10, unique=True) dob = models.DateField(null=True) address = models.CharField(max_length=300) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) pincode = models.CharField(max_length=6) dealer = models.ForeignKey(Dealer, on_delete=models.SET_NULL, null=True) balance = models.FloatField(default=0) bank_ac = models.CharField(max_length=50, null=True) ifsc = models.CharField(max_length=11, null=True) bank_name = models.CharField(max_length=100, null=True) aadhar = models.CharField(max_length=20, null=True) aadhar_front = models.ImageField(upload_to='media/addhar', null=True, blank=True, default=None) aadhar_back = models.ImageField(upload_to='media/addhar', null=True, blank=True, default=None) tse = models.ForeignKey(TSE, on_delete=models.SET_NULL, null=True) date_created = models.DateField(auto_now=True, null=True) profile_image = models.ImageField(upload_to='profile_pic', default='user.png') class Meta: permissions = ( ('edit painter', 'Can edit painter'), ('upload painter', 'Can upload painter'), ('download painter', 'Can download painter'), ) Template: {% if perms.users.upload_painter %} <li><a href="{% url 'upload_painter' %}" style="margin-right: 5px;" class="pull-right btn … -
Django referencing object ID before object creation
I have a question about object creation in django. I have a generator, for simplicity's sake say it is a list, of strings: ['a','b','c'...'n'] Additionally I have a model class which shall reference its id against this list. i.e. model.id = 1 | list[1] = 'b' But my problem is, self.id is only created after saving the object, not upon calling the init method. So overwriting the classes' __init__(self) method and calling self.list_ref = self.id does not work, because model is not yet saved. Also creating a method which may be called afterwards and returns the referenced list entry afterwards does not work properly. def get_list_ref(self): list_ref = list[self.id] self.save() # does nothing, should enter list_ref=list[self.id] into db return list_ref # returns correct referenced list entry So my question is: How do I go about this? I thought of adding a method which overwrites the save method. Is this good practice? Because I always add info to the model which needs not to be updated with every query. A global variable as a counter of the created models (which counts parallel to the db entries) could be another option. I see some possible shortcomings with this, such as keeping objects … -
How to patch value of instance?
I have web-application. On Frontend I do patch request to Backend to update value. On Backend I have class in views that manages user. views.py class ManageUserView(generics.RetrieveUpdateAPIView, mixins.CreateModelMixin): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): """Retrieve and return authenticated user""" return self.request.user def perform_create(self, serializer): """Create a new company""" serializer.save(company=self.request.company) The error is in perform_create function. How can I modify it? Or should I use CreateApiView class? class CreateApiView(generics.CreateAPIView): """Create a new user in the system""" serializer_class = UserSerializer On Frontend I do patch to '/me/' url. urls.py from django.urls import path from user import views app_name = 'user' urlpatterns = [ path('create/', views.CreateApiView.as_view(), name='create',), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), path('logout/', views.LogoutView.as_view(), name='logout'), ] Server response 400 Bad Request with message - company: ["Incorrect type. Expected pk value, received str."]. And my serializers.py file, but I think you do not have to need this code to help me :) class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('id', 'email', 'name', 'surname', 'company') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def … -
Django User Model Inheritance not working
In my Django app, i have two models Retailer and Customer. The model fields for both are different but for authentication the common fields are email and password. So for that I used User Model Inheritance. This is my code looks like Reason for Inheritance : I want to implement Token Authentication models.py class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Retailer(User, PermissionsMixin): name = models.CharField(max_length=255) phoneNUMBER = models.CharField(max_length=10) verificationSTATUS = models.BooleanField(default=False) dateJOINED = models.DateField(default=timezone.now) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'phoneNUMBER',] objects = RetailerManager() def __str__(self): return self.name class Customer(User, PermissionsMixin): name=models.CharField( max_length=255, null=False,) phone_Number=models.CharField( max_length=10, null=False) address=models.TextField(max_length=255,null=False) pin_Code=models.CharField( max_length=6,null=False ) anniversary_Date=models.DateField(blank=True,null=True) hobbies=models.TextField(blank=True,null=True) profession=models.CharField(blank=True,max_length=20,null=True,) created_At=models.DateField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'phoneNUMBER', 'address', 'pin_Code'] objects = CustomerManager() def __str__(self): return (self.name) managers.py class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() … -
Errors with Django LoginView
I'm fairly new to coding & Django. I'm following a tutorial that uses an older version of Django. In the tutorial there is the following code in the views.py from django.contrib.auth import views as auth_views def login(request, **kwargs): if request.user.is_authenticated: return redirect('/cadmin/') else: return auth_views.login(request, **kwargs) I have tried replacing the auth_views.login(request, **kwargs) with auth_views.LoginView(request, **kwargs) and also auth_views.LoginView.as_views(request, **kwargs) but both of theses give me errors. Please can anyone tell me what I should be putting. Thankyou -
SERVER 500 error in my django app through heroku
Showing SERVER ERROR 500 When my django app is deployed through heroku and when i try to enter details through post method into postgresql database `def register(request): ' if (request.method=="GET"): return render(request,'register.html',{'curl':curl,'output':''}) else: name=request.POST.get('name') email=request.POST.get('email') password=request.POST.get('password') address=request.POST.get('address') mobile=request.POST.get('mobile') city=request.POST.get('city') gender=request.POST.get('gender') dt=time.asctime(time.localtime(time.time())) query="insert into(name,email,password,address,mobile,city,gender,role,status,dt) register values('%s','%s','%s','%s','%s','%s','%s','user',0,'%s')" %(name,email,password,address,mobile,city,gender,dt) models.cursor.execute(query) models.db.commit() import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText me = "hellomatcraft@gmail.com" you = email msg = MIMEMultipart('alternative') msg['Subject'] = "Verification Mail MatCraft" msg['From'] = me msg['To'] = you html = """ Welcome to MatCraft You have successfully registered , please click on the link below to verify your account Username : """+email+""" Password : """+str(password)+""" Click here to verify account """ s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() #login() part2 = MIMEText(html, 'html') msg.attach(part2) s.sendmail(me,you, str(msg)) s.quit() print("mail send successfully....") return render(request,'register.html',{'curl':curl,'output':'Verification Mail Successfully Send....'})' 2020-08-24T10:44:19.917608+00:00 heroku[router]: at=info method=POST path="/register/" host=matcraft.herokuapp.com request_id=9255fbcd-a4dd-4be2-a059-5473259002ca fwd="157.34.125.241" dyno=web.1 connect=2ms service=58ms status=500 bytes=473 protocol=https THIS IS ERROR ` -
How to save name of superuser as an author of a post?
I have two fields i.e 'title' and ' content' which come from the form. When a form is submitted, I want these two fields stored in the database along with the name of superuser as author.