Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Encoding error when trying to open json file from django app
I have a json file in the same directory with my app where i have saved some names and passwords. When a user clicks a button, i m trying to retrieve these data and compare it with the input he gave. However, i get an encoding error JSONDecodeError: Expecting value: line 1 column 1 (char 0) The thing is i can normally run the code and read from the json without problems when i dont use Django, so it has to do with it probably. I tried adding errors='ignore' and change encoding withotu succcess My login function which opens the json file: def login(name,password): with open('data.json', 'r', encoding='utf-8', errors='ignore') as f: try: data = json.loads(f.read()) print(data) except ValueError: # includes simplejson.decoder.JSONDecodeError print('Decoding JSON has failed') return False f.close() -
Do checkboxes have to be under one div to work properly?
I have some checkboxes which are generated dynamically with django template. Some of them are under one div and some under another. When making the first or last one required and clicking submit on my form it says that at lease one of the checkboxes from the second div has to be checked and vice versa. The name of the checkboxes are the same. Here's the code <div class="row"> <div class="col"> {% for value in key.categories %} #code.. if first half of items <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}"> <label for="{{ value.id }}">{{ value.value }}</label><br> #code.. if middle item <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}" required> <label for="{{ value.id }}">{{ value.value }}</label><br> </div> <div class="row"> #code.. if second half of items <input type="checkbox" name="{{ key.id }}[]" value="{{ value.id }}" id="{{ value.id }}"> <label for="{{ value.id }}">{{ value.value }}</label><br> {% endfor %} </div> </div> As stated on the question, my question is whether the checkboxes have to be under one div. If so, how can I print the items in two columns of the same length? -
cant see my blog post on my django website
im trying to follow this django tutorial, there a three section on my website called home blog and content. what should happen, is i click on blog and it list out the blog post i made in the admin and i can click on the post and read what the blog post says, but when i click on blogs nothing shows up, its just blank. i have already installed apps in settings i added the url in the url.py folder urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), I went into the models folder and created a model from django.db import models class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title in my blogs/urls folder i have from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post from django.urls import path urlpatterns = [ path('', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html")), path('<int:pk>/', DetailView.as_view(model=Post, template_name='blog/post.html'))] in my blog folder i made a new directory called templates and in templates i made another directory called blog and in the folder i made an html file called blog.html and it is in a notepad++. this is what is in that blog.html notepad {% extends "personal/header.html" %} … -
Searching data stored in Dictionary and Display in same HTML document
This is attendance.html file I want to display details of the student on the right side, searched as per their Class and Roll number displayed on the left column ( from a dictionary) Searched data is to be displayed here on click of search button.(on the same page) HTML code : <HTML> <BODY bgcolor='cyan'> {% block content %} Showing student data ... <br><br> <div> <table style="width:100%"> <td> <table border=1 align=center> <tr> <th>Roll</th><th>Class</th><th>Student name</th><th>Father's name</th> {% for record in records %} <tr> <td>{{record.RollNo}}</td><td>{{record.ClsName}}</td><td>{{record.StudentName}}</td><td>{{record.FatherName}}</td> </tr> {% endfor %} </table> </td> <td> <form action="#" method="POST"> {% csrf_token %} Select your class : <select name="class"> <option value="IX">IX</option> <option value="X">X</option> <option value="XI">XI</option> <option value="XII">XII</option> </select> Enter roll number :<input type="text" name = "roll" size="4"/><br><br> <button type="button">Search student</button> <br> <br> Date : {{ mydate }} Select <b>(if present)</b> <input type="checkbox" name ="attd" value="1"/> <button type="submit" name="submit">Submit data</button> </form> </td> </table> </div> {% endblock %} </BODY> Code in views.py def output(request): with open('./studata.csv', 'r') as csvfile: csv_file_reader = csv.DictReader(csvfile) records = list(csv_file_reader) mydate = datetime.datetime.now() return render(request,'attendance.html',{'records':records,'mydate':mydate}) studata.csv file :- StudentName,FatherName,ClsName,RollNo Nancy Saha,Kuch Bhi Saha,XII,46 Maitreyee Sarkar,Nahi Pata Sarkar,XII,32 Ayush Gupta,Unknown G,XII,45 Tapan Gogoi,Mr Gogoi,X,11 Nirmit Chaliha,Mr Chaliha,IX,29 After the name of the student is displayed I … -
Django, setting custom password field after creating a custom user model from existing database table
I have to integrate my application with an existing one. The user table in the existing database (postgresql) is this: code: Integer (Primary key) login: varchar (actual username) pwd: varchar (the password field) I ran a python manage.py inspectdb and modified the auto-created model like this: class LegacyDBUsers(AbstractBaseUser): code = models.AutoField(primary_key=True) login = models.CharField(max_length=255) pwd = models.CharField(max_length=255) objects = MyUserManager() USERNAME_FIELD = 'login' REQUIRED_FIELDS = ['login', 'pwd'] class Meta: managed = False db_table = 'legacy_db_users' Created MyUserManager() as per documentation (https://docs.djangoproject.com/en/2.2/topics/auth/customizing/) and added AUTH_USER_MODEL in settings.py when I try to authenticate like this: user = authenticate(username="test", password="123") I get this error: django.db.utils.ProgrammingError: column legacy_db_users.password does not exist How can I set the 'pwd' column to be the 'password' column? -
Django rest serializer JSON field sets field to None on valid data
I have a model named project that contains a JSON field named pilot_circles, I am trying to patch that field using a detail_route view, and a model serializer that only contains that field. When the serializer is provided with invalid data, which is invalid JSON, the response is 400 then, but when the provided data is valid, the value of pilot_circles in the validated_data dict is None. here is my detail_route view: @detail_route( methods=['PATCH'], serializer_class=PilotCirclesSerializer,) def my_view(self, request, pk=None): project = self.get_object() serializer = self.get_serializer(project, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializer: class PilotCirclesSerializer(serializers.ModelSerializer): pilot_circles = serializers.JSONField() class Meta: model = Project fields = ('pilot_circles',) model field: from jsonfield import JSONField pilot_circles = JSONField(verbose_name='Pilot Circles', null=True, blank=True) test that's sending the data: def test_endpoint(self): valid_data = { 'circle_1': { 'long': 25, 'lat': 50, 'radius': 2}, 'circle_2': { 'long': 100, 'lat': 250, 'radius': 10} } self.assertIsNone(self.project.pilot_circles) response = self.client.patch(path=self.draw_guide_path, data=valid_data, format='json') self.assertEqual(200, response.status_code) self.project.refresh_from_db() self.assertIsNotNone(self.project.pilot_circles) I am using a 3rd party library called jsonfield, that helps with representing a json field in django models. I am using python 3.5.5, django 1.11 and djangorestframework 3.7.7 My question is: What is causing this behavior of having pilot_circles to be None in the validated … -
Impossible to export static in django production
I'm trying to put in production a website using nginx and gunicorn but after a lot of attempt, my css and js are not visable. The project root is /root/ouverture My static files root is /root/ouverture/coloc/static here it's what i have written in my settings.py STATIC_ROOT = "/static/" STATIC_URL = '/static/' here is my /etc/nginx/sites-available/coloc server { listen 80; server_name 51.91.111.135; root /root/ouverture/; location /static { root /root/ouverture/coloc/; } location / { proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://127.0.0.1:8000; } } Can you help me please, I don't see where is my error. Thank you -
Change readonly fields inside django adminmodels based on a condition
I need to Change readonly fields inside django adminModel based on a condition.. There is a BooleanField inside this mode. I want to check if it is valued is True then show a list of read-only field. if it is false should show another list. here is my ModelAdmin code: @admin.register(PurchaseRequest) class PurchaseRequestAdmin(admin.ModelAdmin): change_form_template = 'prc_custom_change_admin.html' form = PurchaseRequestForm ordering = ['-date_solicited'] # list_filter = (StatusFilter,) autocomplete_fields = [ 'project', 'budget', 'company', 'branch', 'location', 'management', 'effort_type' ] fieldsets = [ ('General', {'fields': [ 'project', 'budget', 'company', 'etp', 'branch', # 'region', # 'management', 'effort_type', 'observations', 'solution_description', 'justifications', 'provisioned_capex', 'contact_information' ]}), ('Status', {'fields': [ 'solicitor', 'date_solicited', 'analizer', 'receiver', 'issuer', 'approver', 'date_approval', ]}), ] readonly_fields = [ 'date_solicited', 'solicitor', 'approver', 'date_approval', ] inlines = [PRCItemInline, ] list_display = ( 'project', 'prc_status', 'check_analizer', 'approval_view', 'issued', 'received', 'installed', 'id', 'budget', 'company', 'branch', 'item_count', 'print_link') search_fields = ['items__product__product_code__oracle_code', 'branch__name'] list_filter = ( 'completed', 'is_received', 'is_approved', 'is_issued', ) list_per_page = 10 I've used get_readonly_fields to let admin able to change anything: def get_readonly_fields(self, request, obj=None): user = request.user if user.is_superuser: # Admin can change anything return self.readonly_fields return self.readonly_fields # + list(disabled_fields) but the problem is that i need to access the current changing object to check … -
DRF POST Request return 201 but nothing get's created
I'm trying to create a new Attendance object using the POST method through the python requests library. Here's part of my model: class Attendance(models.Model): class Meta: verbose_name = 'Attendance' verbose_name_plural = 'Attendances' work_employee = models.ForeignKey('Employee', on_delete=models.CASCADE, verbose_name='Employee') work_start_time = models.DateTimeField(verbose_name='Clock-in Time') work_end_time = models.DateTimeField(null=True, verbose_name='Clock Out Time') My standard serializer: class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance fields = ("work_employee", "work_start_time", "work_end_time") This is what my view looks like: class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = AttendanceSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) And here's my python code sending the request: timezone = "Europe/Berlin" tz = pytz.timezone(timezone) def add_attendance(employee_id): set_headers() #Gets the tokens, sets the headers timezone_now = datetime.now(tz) #Speaks for itself. #timezone_now = str(timezone_now).split("+")[0].split(".")[0] (Ignore this) now = datetime.strftime(timezone_now, "%Y-%m-%d %H:%M:%S") print(now) request = server + "/time/api/attendance/" #The url. response = req.post(request, data={"work_employee":employee_id, "work_start_time":now}, headers=headers["AUTH"]) return response print(add_attendance(2)) Now, I can tell you one thing that the headers are just fine and working dandy. I do get a 201 response and when I do the same thing using post man, it also returns the object just created. But when I … -
Django Djoser: Email address reset
I am using username for primary identification. However, users also have email addresses. I would like to know how can I set up "email address reset" so that users can change their email addresses. This functionality seems obvious to me but I did not find anything - am I missing something or maybe my approach is not correct? Oh, and I would like to keep the username as is, I just want to make it possible to change the email with confirmations etc. I think it is important to have an email sent to the new address first and only then change it. Any help will be much appreciated. Thank you in advance. -
How to define model clean method if a modelform does not include some fields of the model?
I have this model: class StudentIelts(Model): SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)] IELTS_TYPE_CHOICES = [('General', 'General'), ('Academic', 'Academic'), ] student = OneToOneField(Student, on_delete=CASCADE) has_ielts = BooleanField(default=False,) listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) overall = FloatField(choices=SCORE_CHOICES, null=True, blank=True, ) # This should be changed to autmoatic calculation or for validation exam_type = CharField(max_length=10, null=True, blank=True, choices=IELTS_TYPE_CHOICES, ) exam_date = DateField(null=True, blank=True, ) file = FileField(upload_to=student_directory_path, null=True, blank=True, ) student_ielts_non_empty_fields = \ { 'listening': 'please enter your listening score', 'reading': 'please enter your reading score', 'writing': 'please enter your writing score', 'speaking': 'please enter your speaking score', 'overall': 'please enter your overall score', 'exam_type': 'please enter your exam type', 'exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_ielts: for field_name, field_error in self.student_ielts_non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) and have this modelform class StudentIeltsFilterForm(ModelForm): class Meta: model = StudentIelts exclude = ('file', 'exam_date', 'student', ) when I submit this form in template, I get the below error: ValueError at / 'StudentIeltsFilterForm' has no field named 'exam_date'. and During handling … -
Am i missing something?
cmd showing failed to push some refs to 'https://git.heroku.com/sibnathweb.git I have updated "setuptools" and done all the requirements in requirements.txt -
Azure login using Django webapp
So, here is my question's overview:- I basically want to login into azure account. I have created my azure login credentials from azure portal. And now i want to login into azure account but not from portal.azure.com site, I want to login through a webapp which i have developed using Django. I have a webapp developed which has login and password textbox on my django site, now i want to enter my azure credentials here on this webapp and it should also get logged in on azure portal, rendering azure portal after login is not necessary. Could anyone help me out here? Thank you in advance. -
Datatable integration with Django
I am new in web development so, I do not have any idea about how to use dataTable in a Django project. I have json data and I want to display the data into a table using DataTable Created a Django project and Django set up and all is working fine. I look into some source but, couldn't find any blog or other website to integrating DataTable for beginners. I would be a great if any help to find the same for beginners. -
how to convert string into django ORM query
I defined a string and and adding values in while loop and creates Django query. When i'm going to save in database it says 'str' object has no attribute 'save' caste = request.POST.getlist("caste") caste_name = ['GOPENS','GSCS','GSTS','GVJS','GNT1S','GNT2S','GNT3S','GOBCS','LOPENS','LSCS','LSTS','LVJS','LNT1S','LNT2S','LNT3S','LOBCS'] print(len(caste)) cast_counter=0 cut_off = "cut_off(" for i in range(len(Courses)): j=0 while(cast_counter<len(caste)): cut_off += caste_name[j] +"="+ caste[cast_counter] if(j!=15): cut_off += "," if(j == 0): cast_counter += 1 j += 1 continue if(j%15 == 0): cut_off += ")" cast_counter += 1 break j += 1 cast_counter += 1 cut_offf=cut_off cut_offf.save() OUTPUT of cut_of string: cut_off(GOPENS=1,GSCS=2,GSTS=3,GVJS=4,GNT1S=5,GNT2S=6,GNT3S=7,GOBCS=8,LOPENS=9,LSCS=10,LSTS=11,LVJS=12,LNT1S=13,LNT2S=14,LNT3S=15,LOBCS=16) and i want to store it database That's why I written like this cut_offf=cut_off cut_offf.save() but it says 'str' object has no attribute 'save' so any other method?? -
Permission to edit exact instance's subclesses in Django admin page
I need to show user only instances of subclassconnected to exact class instance/ I am learning Django by creating a website for university. Website wiil be used for checking homework. I want to give monitirs of every group in university acces to admin page in order to add/adit/delete subjects they learn and tasks for every subject. I simply don't know where to start so I need your advice. views.py class Group(models.Model): group_name = models.CharField(max_length=20) class Subject(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) subject_name = models.CharField(max_length=200) class Task(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) task_name = models.CharField(max_length=200) About expected result. I need that every group monitor could see and edit only subjects of his Group instance, while I am able to edit all of them. -
Problems with Django Url Patterns
I am having some difficulty with Django url patterns. I am relatively new to Django. So, I am trying to get used to best practices when it comes to building apps using Django. Now, here is my problem. Often time I did notice when two of my urls have kind of similarity, Django often confuses them and I have to make one of the url extremely distinct so that it can work. Why is that ? Even though I have explicitly mentioned as to which url a specific form should be posted. Here is a bug that I am facing url(r'book/collection/read/$', ReadBookList.as_view(), name='read_book_list'), url(r'book/(?P<pk>\w+)/$', BookDetail.as_view(), name='book_detail'), <li class="nav-item active"> <a class="nav-link" href="{% url 'library:read_book_list' %}"> <i class="fa fa-check-circle"></i> <span>Books You Read</span></a> </li> Now, when I navigate to that link, it keeps going to detailview instead of the other url. What could I be doing wrong ? And what is a better way to work with url patterns so that Django doesn't confuse mapping to a wrong url. E.g list of urls in my library app # Book urlpatterns url(r'book/$', BookList.as_view(), name='book_list'), url(r'book/add/$', BookCreate.as_view(), name='book_create'), url(r'book/(?P<pk>\w+)/$', BookDetail.as_view(), name='book_detail'), url(r'book/(?P<pk>\w+)/edit/$', BookUpdate.as_view(), name='book_update'), url(r'book/(?P<pk>\w+)/delete/$',BookDelete.as_view(), name='book_delete'), url(r'book/collection/read/$', ReadBookList.as_view(), name='read_book_list'), url(r'book/mark/read/$', book_mark_read, name='mark_read'), url(r'book/search/results/$',BookSearch.as_view(), name='book_search'), … -
How to use PUT to update something in Vue using Django REST framework
I am new to Vue but have experience with Django. I am using this boilerplate from Github: https://github.com/gtalarico/django-vue-template I really like the structure of that boilerplate because it is not overwelming at all and not a lot of code is written to succesfully interact with the back-end API of Django. It has GET, POST & DELETE already pre-installed and connected to Django REST. So far so good. However I try to add a PUT method to it so I can update models. I try to follow the same structure but I can't get it to work. My productService.js: import api from '@/services/api' export default { fetchProducts() { return api.get(`products/`) .then(response => response.data) }, postProduct(payload) { return api.post(`products/`, payload) .then(response => response.data) }, deleteProduct(proId) { return api.delete(`products/${proId}`) .then(response => response.data) }, updateProduct(proId) { return api.put(`products/${proId}`) .then(response => response.data) } } The updateProduct is the new code I added. Then in store --> products.js: const actions = { getProducts ({ commit }) { productService.fetchProducts() .then(products => { commit('setProducts', products) }) }, addProduct({ commit }, product) { productService.postProduct(product) .then(() => { commit('addProduct', product) }) }, deleteProduct( { commit }, proId) { productService.deleteProduct(proId) commit('deleteProduct', proId) }, updateProduct( { commit }, proId) { productService.updateProduct(proId) commit('updateProduct', … -
jquery code from base.html not working in other pages
I am working on a django application. The application contains multiple html template pages. I used a base.html page which will contain all the common code that I want in other pages. for example, the base template holds the code for a navbar that is common for all the pages in the website. base.html {% load staticfiles %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <!-- bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <!-- fonts --> <link href="https://fonts.googleapis.com/css?family=Anton|Open+Sans&display=swap" rel="stylesheet"> <!-- base.css --> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- base.js --> <script src="{% static 'js/base.js' %}"></script> <title>{% block title %}base{% endblock %}</title> {% block header %}{% endblock %} </head> <body> {% block content %} {% endblock content %} <!-- navbar --> <nav class="navbar fixed-top navbar-expand-lg"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-center" id="navbarSupportedContent"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'home' %}">Home</a> </li> <li class="nav-item active"> <a class="nav-link hover_effect" href="{% url 'about' %}">About Us</a> </li> <li class="nav-item"> <a class="nav-link hover_effect" href="{% url 'contact_us' %}">Contact Us</a> </li> </ul> </div> </nav> </body> </html> base.js $(document).ready(function() { $('.nav-link').css('color', … -
Is the django documentation wrong here?
https://docs.djangoproject.com/en/2.2/ref/models/expressions/#aggregate-expressions It seems to mention aggregate functions but then use annotations as an example, am I going crazy or is there something I'm missing here? I'm having a hell of time trying to figure it out! -
Serializers vs views to retrieve object by foreign key field
I'd like to allow users to perform POST request to create a blog post, and to use the topic name instead of the topic id as a foreign key. A minimal model might look as follows. models.py class Topic(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Post(models.Model): name = models.CharField(max_length=30) topic = models.ForeignKey(Topic, on_delete=models.PROTECT) created_on = models.DateTimeField(blank=True, auto_now_add=True, editable=False) Now there are 2 possible approaches that I've considered: 1) Keep the views simple. views.py class PostList(ListCreateAPIView): queryset = Topic.objects.all() serializer_class = PostSerializer serializers.py class PostSerializer(serializers.ModelSerializer): topic_name = serializers.CharField() class Meta: model = Topic fields = ('name', 'topic_name', 'created_on') read_only_fields = ('created_on',) def validate_topic_name(self, value): """Verify that the topic exists.""" if not Topic.objects.filter(name=value).exists(): raise serializers.ValidationError("Specified Topic Name does not exist!") else: return value def create(self, validated_data): """Create a Post.""" topic_name = validated_data.pop('topic_name', None) topic = Topic.objects.get(name=topic_name) return Post.objects.create(topic=topic, **validated_data) 2) Keep the serializers simple. views.py class PostList(ListCreateAPIView): queryset = Post.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST) topic = get_object_or_404(Topic, name=serializer.data['topic_name']) post = Post.objects.create( name=serializer.data['name'], topic=topic) return Response({'name': serializer.data['name'], 'description': serializer.data['topic_name']}, status=status.HTTP_201_CREATED) serializers.py class PostSerializer(serializers.ModelSerializer): topic_name = serializers.CharField() class Meta: model = Topic fields = ('name', 'topic_name', 'created_on') read_only_fields = ('created_on',) My … -
related_name argument required
I've recieved the following error and I'm not sure how to handle this in my model. HINT: Add or change a related_name argument to the definition for 'UserCart.state_tax' or 'UserCart.fed_tax'. userorders.UserCart.state_tax: (fields.E304) Reverse accessor for 'UserCart.state_tax' clashes with reverse accessor for 'UserCart.other_tax'. models.py class UserCart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) state_tax = models.ForeignKey(Tax, on_delete=models.SET_NULL, null=True) fed_tax = models.ForeignKey(Tax, on_delete=models.SET_NULL, null=True) -
Looking for a good chat in Django
I'm looking for a good chat in Django. I would like to get the following features: old-skool smilies with images (I really don't like unicode emojis that look different on different devices) channels ... that's about it. -
Data not storing in database for choice field for UserRegsitrationForm django
I have extended the UserCreationForm of Django to add extra fields : Email and Choice field. Now when I am filling those details in the registration form and submitting it. Only the email is stored in the database and not the choice field(i.e status in the code). However when I am viewing the fields of my form in the console the choice field is showing. But when I am accessing the attribute using the django shell I am getting an error from django.contrib.auth.models import User users = User.objects.all() users[6].email Output : masterhimanshupoddar@gmail.com # success users[6].status Error: AttributeError Traceback (most recent call last) <ipython-input-7-c9d2701fa919> in <module>() ----> 1 users[6].status AttributeError: 'User' object has no attribute 'status' Here is my forms.py from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class SignUpForm(UserCreationForm): STATUS_CHOICES = ( (1, ("CEO")), (2, ("Dev Manager")), (3, ("Testing Manager")), (4, ("Developer")), (5, ("Test Engineer")) ) email = forms.EmailField(required=True, label='Email', error_messages={'exists': 'Oops'}) status = forms.ChoiceField(choices = STATUS_CHOICES, label="Designation", initial='Developer', widget=forms.Select(), required=True) class Meta: model = User fields = ("username", "email", "password1", "password2", "status") def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user = super(UserCreateForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.status = self.cleaned_data["status"] if commit: user.save() return user Why … -
Django check username at sign-up against a regex of allowed usernames
i would like to check the username upon signup against a regex (which is currently not a regex, see code below). I don't want a new user to use usernames like "admin, supporter, staff" etc. I just try'd to write myself a validator for this but sadly i didn't work with regex or a validation like this before as i'm quite new to coding, maybe smb. can help me out on this: models.py class User(AbstractBaseUser): ... user = models.CharField(verbose_name='Username', max_length=20, unique=True, validators=username_filter) ... validators.py from django.core.exceptions import ValidationError from django.core.validators import RegexValidator def username_filter(value): invalid_username_regex = RegexValidator( regex=("admin", "staff", "supporter", "support") ), if value in invalid_username_regex: raise ValidationError(u'Its not possible to signup with a username like this, please try a different one') but currently i get the following error: user = models.CharField(verbose_name='Username', max_length=15, unique=True, validators=username_filter) File "/venv/lib/python3.7/site-packages/django/db/models/fields/init.py", line 1039, in init app | super().init(*args, **kwargs) File "/venv/lib/python3.7/site-packages/django/db/models/fields/init.py", line 171, in init app | self._validators = list(validators) # Store for deconstruction later TypeError: 'function' object is not iterable thanks in advance