Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect a user to previous page django
Let's say we have a simple django app with a blog model. There are only 3 pages: Home page Blog index Blog post detail The blog posts are listed in 3 locations: In a slider on the home page In the blog index (of course) At the bottom of a blog post There are 2 main ways of using breadcrumbs I've seen on a site: Home / Blog / Blog Post < Back I want to be able to have the "< Back" button go back to whichever the original source came from. I'm aware this could be done with JavaScript. But with Django, I've heard people say on another post that "you shouldn't redirect in template, you should do it in view", but to me that makes no sense as how is the view supposed to know which page to go back to automatically? Anyways, I'm trying to see is: How would you link back to the source page you arrived at a blog post from (i.e., another post, the home page, or the blog index) using django views or in the django template? -
i am able to generate unique slugs in admin but cant figure out how to display them in urls
i want my urls to show slug instead of id, after following a youtube video i reached to a stage where admin is automatically creating slugs when i save my products.. but still i can not figure out how to show slug in url of detailsview ..please help i created a utils.py in my project folder which is named as myawesomecart import string from django.utils.text import slugify def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug my models.py file is as under from django.db import models from django.db.models.signals import pre_save #2 slug from myawesomecart.utils import unique_slug_generator # Create your models here. class product(models.Model): title = models.CharField(max_length=50) slug= models.SlugField(max_length = 250, null = True, blank = True) category = models.CharField(max_length=50, default="your category here") subcategory = models.CharField(max_length=50, default= "your subcategory here") price = models.IntegerField(null=True) desc = models.CharField(max_length=500) pub_date = models.DateField() … -
Why to use a url field in serializers in django rest framework?
Hello guys I am new to django rest framework, I have seen lots of posts about rest framework and have seen people adding url fields to the serializer even though it isn't there in the model. Can someone tell me why we should use this? I have a postserializer like this without url field and I am able to get the response in postman when I run the code. class PostSerializer(TaggitSerializer, serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') tags = TagListSerializerField() class Meta: model = Post fields = ['id','title', 'user', 'tags', 'image'] What advantage I get when I add a url field to this? Is it something related to connecting to frontend or a mobile application? Please do enlighten me about this. Thank you -
Implement OKTA login using PKCE Flow for a SPA using Django Backend
I am planing to implement authentication flow using OKTA for a SPA with already written Django Rest api. My idea is to use okta js sdk for handling authentication in front end and the same html will be pushed to locally hosted file in cordova. I have tried implementing oauth 2.0 flow using django-oAuth-toolkit in django. was not able to figure to how to connect both okta, js, and django Ive learnt that i need to use the OAuth 2.0 Authorization Code with PKCE Flow for better security. Im bit confused and stuck where and how to start. Appreciate your thoughts on the same Is there any library that i can use to easily integrate all of them. or put together bits and pieces of Django plugin to make it work? -
django template system returning same id for different posts
shown below is template of blog.when user likes a post,ajax will call a corresponding view function to do job.For every post,it will have a unique id which i use here for reference.Problem is if i like anypost,the like is going to recently uploaded post.I don't know much about ajax..Please help me.Thank you. {% load static %} <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <title>blog page</title> </head> <body> {% for post in posts %} <h1><a href='{% url "blog:blogpostdetails" post.id %}'>{{ post.post_title }}</h1> <p>loc: <a href='#'>{{ post.post_location }}</a></p> <p>{{ post.post_content|truncatewords:7 }}</p> <p>posted on {{ post.post_timestamp }}</p> <p>posted by <a href='{% url "index:userprofile" post.post_id.username %}'>{{ post.post_id }}</a></p> <form method='POST' id='something'> {% csrf_token %} <input type='hidden' id='postid' name='postid' data-id='{{post.id}}'> <input type='submit' value='like this post'> </form> <p>total like {{ post.likes }}</p> <p>-------------------------------------------------------------------</p> {% endfor %} <div class='tooltip'><h3><a href="{% url 'blog:blogpost' %}">new post</a></h3></div> </body> </html> <style type="text/css"> .tooltip { width: 200px; position: fixed; top:0px; right:0px; left:auto; } </style> {% block javascript %} <script type='text/javascript'> $(document).on('submit','#something',function(e){ e.preventDefault(); console.log($('#postid').attr('data-id')) $.ajax({ type:'POST', url:'{% url "blog:blogpostlike" %}', data:{ postid:$('#postid').attr('data-id'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert('you liked post'); } }); }); </script> {% endblock %} -
how to access individual data in for loop in django template
{ a { 0 { item:1, item2:1 }, 1 { item:1, item2:1 }, 2 { item3:1, item5:1 }, 3 { ite6:1, item7:1 } } } Now I wanna display all (item, item2) from 0,1,2,3 in a for loop. for display in a table. how to access individually. -
Django Testing: AttributeError: 'Client' object has no attribute 'get'
I am new to Django framework & I am trying write some tests for my apps in the project.Currently I have two apps hoardings & clients both have same basic CRUD features.For testing purpose I have created a test directory & it looks like this clients - tests -__init__.py - test_views.py That's how I am maintaining my tests for both the apps.My test_views.py has following code, from django.test import TestCase from django.urls import reverse from hoardings.models import State, City from clients.models import Client class ClientManagementTest(TestCase): def setUp(self): self.state = State.objects.create(desc='West Bengal') self.city = City.objects.create(state=self.state, desc='Kolkata') self.client = Client() def test_client_creation_form_can_be_rendered(self): response = self.client.get(reverse('clients:create')) # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # check if csrf token is present self.assertContains(response, 'csrfmiddlewaretoken') # Check that the response contains a form. self.assertContains(response, '<form') # assert the context values self.assertIn('url', response.context) self.assertIn('heading', response.context) self.assertIn('states', response.context) self.assertIn('client_types', response.context) As you can see in the setup method I am creating an object of Client which is used to send the request.But every time I run the tests I get following errors, ERROR: test_client_creation_form_can_be_rendered (tests.test_views.ClientManagementTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ropali/Development/PythonWorkspace/hms_venv/hms/clients/tests/test_views.py", line 19, in test_client_creation_form_can_be_rendered response = self.client.get(reverse('clients:create')) AttributeError: 'Client' object has no … -
i got an Error when i customize the model in django
i am using djoser for my rest api authentication when i try to add phone number functionality to the model the following Error occurs OperationalError at /api/users/ no such table: api_user models.py from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField class User(AbstractUser): email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = PhoneNumberField(unique=True,blank=False,null=False) REQUIRED_FIELDS = [ 'first_name' 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email serializers.py from djoser.serializers import UserCreateSerializer,UserSerializer from rest_framework import serializers from .models import * class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ( 'id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone' ) settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), } AUTH_USER_MODEL = 'api.User' ## Djoser DJOSER = { 'LOGIN_FIELD':'email', 'SERIALIZERS': { 'user_create':'api.serializers.UserCreateSerializer', 'user': 'api.serializers.UserCreateSerializer', }, } i can't find a solution to this,. And ,is there way to remove username from models.i want only email for authentication..?? -
How to scrape data faster with selenium and django
I am working on a web scraping project. In this project, I have written the necessary code to scrape the required information from a website using python and selenium. All of this code resides in multiple methods in a class. This code is saved as scraper.py. When I execute this code, the program takes sometime between 6 and 10 seconds to extract all the necessary information from the website. I wanted to create a UI for this project. I used django to create the UI. In the webapp, there is a form which when submitted opens a new browser window and starts the scraping process. I access the scraper.py file in django views, where depending on the form inputs, the scraping occurs. While this works fine, the execution is very slow and takes almost 2 minutes to finish running. How do I make the execution of the code faster using django faster? can you point me some tutorial on how to convert the scraper.py code into an api that django can access? will this help in making the code faster? Thanks in advance -
Building a django detailview and listview without using <int:pk>
I'm building a django app that displays a database of employees and their salaries. It uses a postgres database. I'm struggling to figure out how to build a DetailView without using a primary key for the url. I think using a slug may be the solution but I'm not sure how to implement that and haven't had much luck searching online. My Listview for the list of all companies: class AllCompanies(FormMixin, generic.ListView): template_name = 'AllCompanies.html' form_class = SearchForm model = bigdatabase queryset = bigdatabase.objects.order_by().values('company').distinct() context_object_name = 'companies' Example Database snippet, bigdatabase: Company EmployeeName Salary Alpha Jim 100000 Alpha Tim 125000 Beta Bim 90000 My list view displays all unique company names as intended. However, I'm not sure how to proceed and build a detailview to display more info on each unique company. I'd like to show things like number of employees, median salary, etc. I've done something similar by building a detailview for employees, but that relied upon using their primary key in the url since each employee is unique. Since I have many entries for many companies in my database, how would I build a detailview and accompanying url structure to support that? Any advice or pointers as to … -
API Versioning: providing different data formats for a resource
PROBLEM: when you write an API for an SPA, If the the API's json response or data changes, the SPA changes accordingly. so there is no need to version the API. But when you write an API for a mobile app, things are different. take a library mobile app for example: in app version 1.0 people see 5 books that have one image each one. but in version 2.0 because of change in design, different images should be passed for these 5 books. in app version 3.0 some other books are added which shouldn't be shown in previous versions for some reason. in this scenario, we should have three different responses for /books API end-point. the solution that comes to my mind is that I should have different for the /books endpoint: /v1/books /v2/books /v3/books you get the idea. QUESTION: what is the best way to handle "providing different data formats for a resource"? is there any best practice or standard for this? If this challenge is not properly handled, the development gets hard as the app grows, -
Why is my React app not loading correctly in Edge 84 (chromium) but does in chrome?
I have tried a django/react app as well as a base react app made using the create-react-app command. Both end up breaking in one way or another. For instance, the align-items tag does nothing (tried center, right, left). On my django/react app I have a header that loads perfectly on chrome but all I see is a background color on edge. -
HyperSkill Task
Hello I have a problem Hypreskill task.Can you Help me Hyper car service Description When the next client's turn is coming up, the operator should process it pushing the button. It happens when one of the mechanics has finished the work and able to serve the next client. You cannot define in the application the exact time, so leave the task to the operator. When the "Process next" button is pushed the application chooses the next client according to the algorithm's priority: Until the line of customers to change the oil is not empty, they served first If "Change oil" queue is empty the line of customers to inflate tires served next Clients who want to get diagnostics served last. Immediately the number of chosen ticket appears on the screen for all the customers and the length of the appropriate queue become one client less. You need not save the ticket further, the only purpose of it now is to show the number on the screen. Objectives Your task is to make a POST handler for processing the next ticket. After the request is received, remove the appropriate ticket from the queue. The handler should process POST requests at "<base_url>/processing", … -
How to link Django and React URLs to perform actions?
In Django, I have my login URL set to 'api/auth/login'. When given a username and password, it will log that user in. Running 'python manage.py runserver', it will put that URL at 'http://127.0.0.1:8000/api/auth/login' However, my React project, when running 'yarn start' is at 'http://localhost:3000/' and giving it the extension 'api/auth/login', the url it attempts is 'http://localhost:3000/api/auth/login'. This does not work, but if I replace the URL extension with 'http://127.0.0.1:8000/api/auth/login', the login works as expected. How can I have the URLs work with my React app? Or is this not something that necessarily needs to be fixed? I do plan to host this project somewhere and am not yet sure how the URLs will work out.. -
How to update a DateTimeField ONLY WHEN a BooleanField is checked from False to True?
# models.py class Appointment(models.Model): # not including some model fields and instead focusing on the model fields that are of concern records_sent = models.BooleanField(default=False) record_sent_date = models.DateTimeField(blank=True, null=True) records_received = models.BooleanField(default=False) record_received_date = models.DateTimeField(blank=True, null=True) # views.py class AppointmentUpdateView(UpdateView): model = Appointment fields = ['records_sent', 'records_received'] def form_valid(self, form): """ Update sent/received datetimes to current time when sent/received is checked from false to true. """ appointment = self.object if form.instance.records_sent: appointment.records_sent_date = timezone.now() if form.instance.records_received: appointment.records_received_date = timezone.now() return super().form_valid(form) My main concern has to do with my if-statement logic in my Class View's form_valid method. Currently, if my BooleanFields are checked True via POST request, the timezone updates to now(), which is fine. But let's say I set records_sent=True on 2:00 pm. If I set records_received=True on 4:00 pm, records_sent ALSO updates its time to 4:00 pm because the POST request sent records_sent AND records_received = True in the form, subsequently triggering the if-statement again when it should be only applying to records_received. How can I make it so that datetime.now() triggers ONLY when booleanfield is set from False to True, rather than having it also trigger from True to True? -
How to change the version of python run on apache for django
I have base GCP instance running Ubuntu 18.04. Running the python install gave me python 3.6.9. No problem initially. Now, I happen to be developing on 3.7 on my local machine. Until now this has not caused any issues with the Django apps I am developing. However, I am now developing an app that uses the module os.subprocess. It turns out that there are differences between 3.7 and 3.6 for this module. So I have successfully installed 3.7 on the server using sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install python3.7 I ran sudo update-alternatives --config python3 and made sure it was active on the correct version. Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/python3.7 2 auto mode 1 /usr/bin/python3.6 1 manual mode 2 /usr/bin/python3.7 2 manual mode Now, I can run programs on the command line and it runs 3.7. However, even after restarting appache (indeed, I even restarted the VM). Django is still running with v 3.6. I even ran this command to see what version the user www-data is running. su - www-data -s /bin/bash -c 'python3 --version' and it confirms Python 3.7.9 (as I expect). What am I missing, why is apache still running 3.6.9 … -
Iam getting an error in the windows power shell when iam trying to install MySQL (pip install mysqlclient)
C:\Users\urs az33z\Desktop\fiza\myproject>pip install mysqlclient Traceback (most recent call last): File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\urs az33z\AppData\Local\Programs\Python\Python36\Scripts\pip.exe_main.py", line 5, in File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal_init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\cmdoptions.py", line 18, in from pip._internal.models.format_control import FormatControl File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\models\format_control.py", line 1, in from pip._vendor.packaging.utils import canonicalize_name ModuleNotFoundError: No module named 'pip._vendor.packaging.utils' C:\Users\urs az33z\Desktop\fiza\myproject>pip install mysqlclient-1.4.6-cp36-cp36m-win_amd64.whl Traceback (most recent call last): File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\urs az33z\AppData\Local\Programs\Python\Python36\Scripts\pip.exe_main.py", line 5, in File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal_init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\cmdoptions.py", line 18, in from pip._internal.models.format_control import FormatControl File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\models\format_control.py", line 1, in from pip._vendor.packaging.utils import canonicalize_name ModuleNotFoundError: No module named 'pip._vendor.packaging.utils' C:\Users\urs az33z\Desktop\fiza\myproject>python Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more … -
How can I do a on_conflict_replace work in Django batch_create operation?
The field account and month are unique togather. And I'm tring to batch_insert db data by bulk_create with Django to speed up my db operation. below is my base table # my db table class MSpendForMonth(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) system_value = models.DecimalField(max_digits=16, decimal_places=2) checked_value = models.DecimalField(max_digits=16, decimal_places=2, null=True) account = models.ForeignKey(MAccount, models.DO_NOTHING, related_query_name="account_month", related_name="account_month" ) month = models.IntegerField(blank=True, null=True) class Meta: db_table = 'spend_for_month' unique_together = (('account', 'month'),) # db operation bulk_data = [] try: with transaction.atomic(): for spend_data in spend_month_date_sum_queryset: bulk_data.append( MSpendForMonth( account_id=spend_data["account_id"], month=month, system_value=spend_data["sum_value"], ) ) MSpendForMonth.objects.bulk_create(bulk_data, ignore_conflicts=True ) # MSpendForMonth.objects.bulk_update(bulk_data, fields="system_value") except: import traceback as tb tb.print_exc() And I want to replace system_value with a new value as it sometimes changed. My question is how can I bulk_create data and replace with new value of system_value if there is a conflict on unique key account-month. It should be something like insert_many().on_conflict_replace() -- peewee Great thanks. -
AttributeError type object 'tickets' has no attribute 'USERNAME_FIELD'
I did not se up custom User class at the beggining. Now the application is done. The bug is that I cant post a ticket from the admin panel due to the error above. Any ideas? -
Django RESTFUL + axios and Vue.js frontend
Here goes nothing... I'm busy with a project where I connected Vuejs and Django with Django Restful and Axios and I created a simple get and post to see if everything works (Bit of a noob with API calls, normally I build static stuff, you will see soon enough) and it works! I can input a subject and message and post it to Django to the DB and call the Subject and message back to vue.js and display it. But this is not the final product and not the problem... I created an AI that is currently running separately with its own API calls The API calls are as follow Prefix Lenght Temperature Now that the AI is running on localhost:8080 I'm trying to point Django Restful API to that port and push get and post calls from the frontend via Django to the AI Here is a flow Vuejs - User requests something in a text field Django - Receives the request via Axios, saves it in the DB passes it to port 8080 AI - gets the request via Django and works its magic, when it's done, it passes the data requested back to Django and then Vuejs … -
How to resolve Django Exception happend during processing of request
Hello so I would love to understand what might be causing this error, so I have Django for my API and I have ReactJS for my Front-end. So when I launch React the homepage instantly makes a GET request to the server-side so to get the info from the database, but then now when I switch between pages within my React my API complains with this error: Exception happened during processing of request from ('127.0.0.1'.50368) I get the following Traceback: Traceback (most recent call last): File "C:\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\JUNIOR\Django Projects\uwcLectureApi\project\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\JUNIOR\Django Projects\uwcLectureApi\project\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host So I do not understand what Is happening here and how I am to resolve this can I please get some assistance -
Point Django RESTAPI to URL and Port and get API calls from there
I currently have a python application running separately from Django that has its own API calls in JSON format on localhost:8080 that is currently in production and cant be taken offline atm So I'm thinking of a momentary workaround until I can make it a better so here is what I'm trying to do I would like to access the API calls in the above application via Restful API in Django so that I can bind them to fields in a frontend that I created. Django is running on port 8081 The only guides I've found on Restful is within Django 'How to create a restful application IN Django' But nothing on telling Restful to look at a URL and port and get the API calls from there. (yes this sounds like the long way around but I don't have a choice atm, will need to make the application a bit better where the application running on port 8080 is within Django but that's going to be a few thousand emails and calls and PT) if I go into Postman and do calls there and export the code under Python - http.client and import it into my models.py and try … -
Django pre fill a form with data from a selected line in a table
This site has been of great help but now I'm stuck. I have a page (allrmview) where the user can filter a table. Once that is done he can select a line. It opens a form (NewrmForm) page which is pre filled with some informations from the selected line in the table. I don't understand how i can send the datas selected to the new form. As I am a beginner a lot of elements are missing. models.py: class Infomp(models.Model): url = models.CharField(unique=True, max_length=150, blank=True, null=True) name = models.CharField(max_length=37, blank=True, null=True) synonyme = models.CharField(max_length=126, blank=True, null=True) chemname = models.CharField(max_length=100, blank=True, null=True) cas = models.CharField(max_length=15, blank=True, null=True) einecs = models.CharField(max_length=15, blank=True, null=True) mweight = models.FloatField(blank=True, null=True) vappress = models.CharField(max_length=31, blank=True, null=True) solublein = models.CharField(max_length=89, blank=True, null=True) insoluble = models.CharField(max_length=12, blank=True, null=True) odortype = models.CharField(max_length=11, blank=True, null=True) odorstrength = models.CharField(max_length=55, blank=True, null=True) substantivity = models.CharField(max_length=44, blank=True, null=True) odordescript1 = models.CharField(max_length=100, blank=True, null=True) odordescript2 = models.CharField(max_length=100, blank=True, null=True) usagelevel = models.CharField(max_length=39, blank=True, null=True) ifra = models.CharField(max_length=24, blank=True, null=True) risk = models.CharField(max_length=20, blank=True, null=True) cosing = models.CharField(max_length=6, blank=True, null=True) class RmStock(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') num = models.IntegerField(unique=True) n_tgsc = models.SmallIntegerField(blank=True, null=True) nom_mp = models.CharField(max_length=60) quantite = models.FloatField(blank=True, null=True) fournisseur = models.IntegerField(blank=True, … -
Can't create Super user in Custom Multi User
I was trying to implement registration for 3 types of users: Parent, School and Vendor. from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager) class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=True, is_parent=False, is_school=False, is_vendor=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not parent: raise ValueError("Users must have a role") if not school: raise ValueError("Users must have a role") if not vendor: raise ValueError("Users must have a role") user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) # change user password user_obj.parent = is_parent user_obj.school = is_school user_obj.vendor = is_vendor user_obj.active = is_active user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_parentuser(self, parent, school, vendor, email, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_parent=True ) return user def create_schooluser(self, email, parent, school, vendor, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_school=True ) return user def create_vendoruser(self, email, parent, school, vendor, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_vendor=True ) return user def create_staffuser(self, parent, school, vendor, email, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_staff=True ) return user def create_superuser(self, email, parent, school, vendor, password=None): user = … -
Getting Attribute Error after adding html file in django
I am trying to build a website on cPanel using django. My models were working fine untill I created my first html page and tried to render it. Now whenever I try to load my site I get "AttributeError at /admin/ module 'artclBlog.views' has no attribute 'home'" pic of error message my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def home(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/home.html', {'blogs': blogs}) my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from artclBlog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('blog/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=200, default='') summary = models.CharField(max_length=200, default='') pageOne = models.TextField(default='') pageTwo = models.TextField(default='') pageThree = models.TextField(default='') pageFour = models.TextField(default='') date = models.DateField(default='') def __str__(self): return self.title