Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: Could not read from 'src\pip\_vendor\requests\cookies.py': Bad file descriptor
I was trying to create a new django project using pycharm but it keeps saying bad file descriptor. I completely uninstalled python and pycharm and reinstalled several times but still it did not work. I also noticed that the python scripts file is empty where there should be a easy_install and pip after reinstallation. running install running bdist_egg running egg_info writing src\pip.egg-info\PKG-INFO writing dependency_links to src\pip.egg-info\dependency_links.txt writing entry points to src\pip.egg-info\entry_points.txt writing top-level names to src\pip.egg-info\top_level.txt reading manifest file 'src\pip.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' writing manifest file 'src\pip.egg-info\SOURCES.txt' installing library code to build\bdist.win-amd64\egg running install_lib running build_py creating build creating build\lib creating build\lib\pip copying src\pip\__init__.py -> build\lib\pip copying src\pip\__main__.py -> build\lib\pip creating build\lib\pip\_internal copying src\pip\_internal\build_env.py -> build\lib\pip\_internal copying src\pip\_internal\cache.py -> build\lib\pip\_internal copying src\pip\_internal\configuration.py -> build\lib\pip\_internal copying src\pip\_internal\download.py -> build\lib\pip\_internal copying src\pip\_internal\exceptions.py -> build\lib\pip\_internal copying src\pip\_internal\index.py -> build\lib\pip\_internal copying src\pip\_internal\locations.py -> build\lib\pip\_internal copying src\pip\_internal\pep425tags.py -> build\lib\pip\_internal copying src\pip\_internal\pyproject.py -> build\lib\pip\_internal copying src\pip\_internal\resolve.py -> build\lib\pip\_internal copying src\pip\_internal\wheel.py -> build\lib\pip\_internal copying src\pip\_internal\__init__.py -> build\lib\pip\_internal creating build\lib\pip\_vendor copying src\pip\_vendor\appdirs.py -> build\lib\pip\_vendor copying src\pip\_vendor\distro.py -> build\lib\pip\_vendor copying src\pip\_vendor\ipaddress.py -> build\lib\pip\_vendor copying src\pip\_vendor\pyparsing.py -> build\lib\pip\_vendor copying src\pip\_vendor\retrying.py -> build\lib\pip\_vendor copying src\pip\_vendor\six.py -> build\lib\pip\_vendor copying src\pip\_vendor\__init__.py -> build\lib\pip\_vendor creating build\lib\pip\_internal\cli copying src\pip\_internal\cli\autocompletion.py -> build\lib\pip\_internal\cli copying src\pip\_internal\cli\base_command.py -> … -
makemigrations take duplicate entries django
I have created 2 models in Django Rest Framework Python. 1 model is joined to other model using foreign Key. The problem I am facing is even if I don't make any changes, makemigrations would still consider the model fields as changed. **This is model 1 ** class ProfessionalStepServiceData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,blank=True, null=True) profession = models.ForeignKey(Profession, on_delete=models.CASCADE,blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) is_deleted = models.BooleanField(default = False, help_text="activate/deactivate skills") service_description = models.TextField(max_length=500,blank=True,null=True) def __str__(self): return "{}-{}".format(self.profession, self.user) class Meta: verbose_name_plural = "Step Service Data" db_table = 'professional_StepData' This is model 2 class Profession(models.Model): professionName = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return "{}".format(self.professionName) class Meta: verbose_name_plural = 'Static Profession' db_table = 'StaticProfession' now even if I don't make any changes to ProfessionalStepServiceData, It would still get added on makemigrations stating that profession Field in ProfessionalStepServiceData has been altered. Is this a bug or I am messing with something? -
Not Displaying error message in Django Admin?
Whenever i try to add project of same name it leads to IntegrityError at /admin instead there should be an Error message on Django admin that "This project already exists". Also i have two users. So same user cannot have project of same name and different users can have project of same name. Please let me know how to fix this. class Project(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, default=None) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = (("name", "added_by"),) -
while creating user for my postgreSQL database. I get error su : The term 'su' is not recognized
I run the following command in my windows powerShell su postgres su : The term 'su' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 su postgres ~~ CategoryInfo : ObjectNotFound: (su:String) [], CommandNotFoundException FullyQualifiedErrorId : CommandNotFoundException -
display two objects by for loop django
my template has a timeline structure.. so 1 object is left aligned and other is right aligned .. i want to display them alternatively within a for loop.. content from same model but alignments of divs are Diffrent.. <ul class="timeline"> <li class="timeline-right"> <div class="timeline-badge"> <i class="fa fa-calendar"></i> <p class="date-inverted wow slideInLeft">{{Experience.first.FromDate}} -{{Experience.first.ToDate}}</p> </div><!-- end timeline-badge --> <div class="timeline-panel wow slideInRight"> <div class="experience-content"> <h4>{{Experience.first.Designation}}</h4> <h5>{{Experience.first.Department}}</h5> <p>{{Experience.first.ShortNote}}</p> </div> </div><!--end timeline-panel --> </li><!-- end timeline-right --> <li class="timeline-left"> <div class="timeline-badge"> <i class="fa fa-calendar"></i> <p class="date wow slideInRight">Oct 2015 - Nov 2016</p> </div><!-- end timeline-badge --> <div class="timeline-panel wow slideInLeft"> <div class="experience-content"> <h4>MGS PVT. LTD.</h4> <h5>Senior Designer </h5> <p>The Big Oxmox advised her not to do so, because there were thousands of bad Commas, wild Question Marks.</p> </div> </div><!-- end timeline-panel --> </li><!-- end timeline-left --> models. py class Experience(models.Model): Designation = models.CharField(max_length=150) Department = models.CharField(max_length=150,default='my dept') Organisation =models.CharField(max_length=150) ShortNote = models.CharField(max_length=200) FromDate = models.DateField( default=datetime.date.today) ToDate = models.DateField(default=datetime.date.today) def __str__(self): return self.Designation -
Save incoming data from a webhook
{'event_type': 'shipment.label.created', 'resource_type': 'shipment', 'resource_id': 'ESTEST00000', 'label':{'easyship_shipment_id': 'ESTEST00000', 'platform_order_number': '#100001', 'status': 'success', 'label_url'}} I'm trying to link easyship webhook with my django project , I'm successfully recieivng the above data from easyship, However I would like to save status into my shipment models easyhip_satatus field , where the shipment_id of an object is equal to easyship_shipment_id. My def post function is not working. models.py Shipment(models.Model): shipment_id = models.CharField(max_length =100, null=True, blank=True) easypost_status = models.CharField(max_length =100, null=True, blank=True) def post(self,request): print(request.data) order = get_or_404(Order, shipment_id=request.data['label']['easyship_shipment_id']) order.objects.filter(shipment_id=order).update(easypost_status = ['event_type']['status'] return Response(request.data) -
Django connect mysql issue
I am connecting my mysql database to django.While migrating or running django app it shows following error: mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES) My database is accessible configuration is also correct in my config file.As when i type wrong database name it shows no database found. [client] database = vs4 user = newuserq password = tooq default-character-set = utf8 How to fix this error and why in this error it is asking for 'root' user, i have written 'newuser' user in my django config. -
Is django-seeder also use when model have foreign key?
I'm trying to use django-seeder in language model when create profile, models: class Profile(models.Model): name = models.CharField(max_length = 255) email = models.EmailField(unique=True) phone_no = models.CharField(max_length=10) def __str__(self): return self.name class Language(models.Model): user = models.ForeignKey(Profile, on_delete = models.CASCADE) language = models.CharField(max_length=255) proficiency = models.CharField(max_length=32,choices=PROFICIENCY) def __str__(self): return self.language when I create Profile, I need to create Language objects. -
What is the best Workflow for Updating a Web App
I'm pretty new at this but I recently deployed my first web application using Django, Postgres, Nginx, and Gunicorn on Digital Ocean. I went to make some updates and ran sudo service gunicorn restart to see the changes. I wiped my entire Database. I obviously need to work on setting up a better workflow for deploying to production. Does anyone have any suggestions? What are some best practises when re-deploying a Django App with a Postgres DB? I've read some articles about backing up my DB (which I'm definitely going to be doing in future), but what else can be done to ensure a seem-less transition? -
.dockerignore: some files are ignored, some are not
The Problem Hi I'm new to Docker. I want to ignore some files and directories using .dockerignore in my Django project. In the beginning, no files were ignored , then I searched in stackoverflow and found that its because of the volumes in docker-compose.yml, so I commented it out. But now some of the files and directories are getting ignored but some are not. I went through a lot of questions but couldn't find any solution. Project structure -src --coreapp ---migrations ---__init__.py ---__pycache__ ---admin.py ---apps.py ---models.py ---tests.py ---views.py ---tests.py --UserApp ---migrations ---__init__.py ---__pycache__ ---admin.py ---apps.py ---models.py ---tests.py ---views.py ---tests.py --admin.json --db.sqlite3 --manage.py -.dockerignore -.gitignore -docker-compose.yml -Dockerfile -Procfile -README.md -requirements.txt -runtime.txt Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /code/requirements.txt RUN pip install -r /code/requirements.txt COPY . /code/ WORKDIR /code/ EXPOSE 8000 docker-compose.yml version: '3' services: db: image: postgres web: build: . command: bash -c "python src/manage.py runserver 0.0.0.0:8000" # volumes: # - .:/code ports: - "8000:8000" depends_on: - db .dockerignore # Byte-compiled / optimized / DLL files __pycache__/ **/migrations src/media src/db.sqlite3 Procfile .git Commands # build image sudo docker-compose up --build # to enter container sudo docker exec -it [container id] bash # to check ignored files inside the container … -
How to implement Trello-like kanban board using socket or push notifications
I am trying to implement a Trello-like board page that updates any changes to cards and lists on a board real-time (ex-card order, list order, newly added cards or deleted cards, etc) using Django Rest Framework. I was initially thinking of using Django channels and WebSocket to receive any change from frontend and return JSON containing updated information that other subscribers in the group should know. But I am now wondering if there is a way to implement this feature without using socket: For example, using Django signals to detect changes and sending some sort of notification to the frontend to reload certain sections of the page (after which the users will see the updated changes). Can this be made possible? I guess it does not have to be Django signals -- any recommendation of useful libraries or features will be appreciated, as well as any advice on approaching this task. Thank you! -
how to apply my custom content in template django-allauth
I use common template both for login purposes and other "guest visit" tasks. I dont need to special separate template for login form. But i need to apply huge content. Is it possible to apply my own content to render my own template by allauth view - accounts/login for example or i should apply another library? if i use advice: from allauth.account.views import SignupView, LoginView class MySignupView(SignupView): template_name = 'my_signup.html' class MyLoginView(LoginView): template_name = 'my_login.html' i have error, because my 'my_login.html' includes many variables for rendering and i can`t apply my content - i dont now, how i can do it. another advice: <div class="fieldWrapper"> {{ form.email.errors }} <label for="{{ form.email.id_for_label }}">Your email address:</label> {{ form.email }} </div> <div class="fieldWrapper"> {{ form.username.errors }} <label for="{{ form.username.id_for_label }}">Your Username:</label> {{ form.username }} </div> <div class="fieldWrapper"> {{ form.password1.errors }} <label for="{{ form.password1.id_for_label }}">Password:</label> {{ form.password1 }} </div> <div class="fieldWrapper"> {{ form.password2.errors }} <label for="{{ form.password2.id_for_label }}">Password(again):</label> {{ form.password2 }} </div> is to use form fields in my custom template and render it by myself def guestVisit(request): return render( request, "index.html.j2", { 'LoginForm': LoginForm(), 'GuestMesForm': GuestMesClearForm, 'user': request.user, 'loginEnb': request.META['REMOTE_ADDR'] in AVALABALE_IP } ) is a good idea, but if i have error … -
Issues with select drop down filtering django
i have issues getting the output of my experience_level and country select fields despite my best efforts,please kindly help,below are snippets of my code for better understanding //a choice.py file to store all my selections salary_choices = { '100000': '$100,000', '200000': '$200,000', '300000': '$300,000', '400000': '$400,000', '500000': '$500,000', '600000': '$600,000', '700000': '$700,000', '800000': '$800,000', '900000': '$900,000', '1000000': '$1M+', } Country_choices = { 'US': 'United States', 'AF': 'Afghanistan', 'AL': 'Albania', 'DZ': 'Algeria', 'AS': 'American Samoa', 'AD': 'Andorra', 'AO': 'Angola', 'AI': 'Anguilla', 'AQ': 'Antarctica', 'AG': 'Antigua And Barbuda', 'AR': 'Argentina', 'AM': 'Armenia', 'AW': 'Aruba', 'AU': 'Australia', 'AT': 'Austria', 'AZ': 'Azerbaijan', 'BS': 'Bahamas', 'BH': 'Bahrain', 'BD': 'Bangladesh', 'BB': 'Barbados', 'BY': 'Belarus', 'BE': 'Belgium', 'BZ': 'Belize', 'BJ': 'Benin', 'BM': 'Bermuda', 'BT': 'Bhutan', 'BO': 'Bolivia', 'BA': 'Bosnia And Herzegowina', 'BW': 'Botswana', 'BV': 'Bouvet Island', 'BR': 'Brazil', 'BN': 'Brunei Darussalam', 'BG': 'Bulgaria', 'BF': 'Burkina Faso', 'BI': 'Burundi', 'KH': 'Cambodia', 'CM': 'Cameroon', 'CA': 'Canada', 'CV': 'Cape Verde', 'KY': 'Cayman Islands', 'CF': 'Central African Rep', 'TD': 'Chad', 'CL': 'Chile', 'CN': 'China', 'CX': 'Christmas Island', 'CC': 'Cocos Islands', 'CO': 'Colombia', 'KM': 'Comoros', 'CG': 'Congo', 'CK': 'Cook Islands', 'CR': 'Costa Rica', 'CI': 'Cote D`ivoire', 'HR': 'Croatia', 'CU': 'Cuba', 'CY': 'Cyprus', 'CZ': 'Czech Republic', 'DK': 'Denmark', 'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': … -
TypeError at /edit : edit() missing 1 required positional argument: 'entry'
I am very new at Django and I am working on a web app project. this particular page is supposed to edit an entry and save the entry. but I keep getting the missing 1 required argument Views.py # editPage forms class editform(forms.Form): content = forms.CharField(widget=forms.Textarea(), label='') def edit(request, entry): if request.method == 'GET': page = util.get_entry(entry) return render(request,"encyclopedia/edit.html",{ "form":SearchEntry(), "edit":editform(initial={'content': page}), "entry":entry }) #If this is a POST request else: form = editform(request.POST) if form.is_valid(): content = form.cleaned_data["content"] util.save_entry(entry,content) page = util.get_entry(entry) page = mark.convert(page) return render(request,"encyclopedia/entry.html",{ "form":SearchEntry(), "page":page, "entry": title }) urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:entry>", views.entry, name="entry"), path("search", views.search, name="search"), path("newEntry", views.newEntry, name="newEntry"), path("edit", views.edit, name="edit"), edit HTML {% extends "encyclopedia/layout.html" %} {% block title %} Edit {{name}} {% endblock %} {% block body %} <h1>{{title}}</h1> <form action= "{% url 'edit' %}" method="POST"> {% csrf_token %} {{ edit }} <br> <input class="save btn btn-info" type="submit" value="save"/> </form> <p> Click the "save" button to save your entry to the encyclopedia.</p> <br> <a href = "{% url 'index' %}"> Return Home</a> {% endblock %} entry HTML {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} … -
find out why my web server becomes unavailable
I have a python web server (django) It talks to other services such as elasticsearch I notice when elasticsearch goes down, the web server soon (after a few minutes) stops responding to client requests. I use https://github.com/elastic/elasticsearch-py and it implements timeout and don't think it's blocking. My hunch is that requests piles up during the timeout period and server becomes unavailable but it's a just guess. What's the reason for the server not being able to handle requests in such a scenario and how do I fix it? I have nginx - uwsgi - django on unix (amazon ecs) setup if that makes difference -
Django create a new column in an already existing table
I'm using Django 3.0.5 and I am trying to create a new column in a table. The table looks like this: class VacationModel(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) emp_id = models.IntegerField() email = models.EmailField() from_date = models.DateField() to_date = models.DateField() reason = models.TextField() time_sent = models.DateTimeField("date sent") req_approved = models.BooleanField(default=False, null=True) req_denied = models.BooleanField(default=False, null=True) # daysoff_given = models.IntegerField() def __str__(self): return self.emp_id The new column would be daysoff_given. I tried adding this column and after running python manage.py makemigrations I got an error saying django.db.utils.OperationalError: no such column I tried following some other answers and I deleted the migrations made inside the mirgations folder, without deleting the __init__.py file. After running makemigrations again the same error occured and then I deleted the whole model and made a new model. I think my database is broken, but is there an actual way to avoid this, since it has already happened 2 times. Whenever I try to add a new column, it always throws that error and I cannot continue. How can I fix this? -
Django and Vue.js with Axios: 500 internal server error with post request
I am currently making a TODO app with Vue.js and Django (Vanilla Django not the Django REST framework) and I am using AXIOS to perform the request post/get, the get request works perfectly fine and I am able to fetch data, but when I create a new task and submit it to the Django I get this error on the front end: xhr.js:185 POST http://127.0.0.1:8000/tasks/ 500 (Internal Server Error) createError.js:17 Uncaught (in promise) Error: Request failed with status code 500 at createError (createError.js:17) at settle (settle.js:18) at XMLHttpRequest.handleLoad (xhr.js:69) Here is my code in the front end HTML and javascript: function sendRequest(url, methode, data) { const r = axios({ url: url, method: methode, data: data, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-Requested-With': 'XMLHttpRequest' //to allow django recognizing this request as ajax request } }); return r; } const app = new Vue({ el: '#app', data: { task: '', tasks: [], }, //use hooks to call the function at the event of page loaded created() { const vue_instance_ref = this; const r = sendRequest('', 'get') .then(function (response) { vue_instance_ref.tasks = response.data.tasks; }); }, methods: { createNewTask() { const vue_instance_ref = this; const formData = new FormData(); formData.append('title', this.task); sendRequest('', 'post', formData) … -
Can not seem to get Django to display the correct content in web-pages
I am creating a web-app using Django. I want the app to have 4 sections, the homepage, Culture, Entertainment, and Technology. The home page would display all the articles while the other pages would display articles that relate to that category. I created a class for all the articles. Some of the class objects are: category, title, by, summary. In views.py, for the homepage, I created a function to display all the articles in random order. I then created 3 more functions that display the articles by category. The problem is, the home page is the only one that works properly. I made links to all 4 pages in my navbar, all four links go back to my homepage instead of the category pages i made. The function I made for the homepage or all_blogs is the only one that works. When I modify it so it only displays articles in a certain category it works, but when I try to make a new function and new page, it only displays the homepage. views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def all_blogs(request): blogs = Blog.objects.order_by('?') return render(request, 'blog/all_blogs.html', {'blogs': blogs}) def Entertainment(request): blogs = Blog.objects.exclude(category='Technology, Culture') return … -
How can i imperilment multiple step form in django, for example Application Form that has 3 steps like first of personal information
model.py i create my Application model with many fields class Application(models.Model): family_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) other_name = models.CharField(max_length=100) district = models.CharField(max_length=100) pobox = models.CharField(max_length=100) email = models.EmailField() phone = models.CharField(max_length=30) date_of_birth = models.DateField(null=True) place_of_birth = models.DateField(null=True) gender = models.CharField(max_length=6, choices=GENDER) status = models.CharField(max_length=50, choices=M_STATUS) spouse = models.CharField(max_length=100) nationality = models.CharField(max_length=100) father_name = models.CharField(max_length=150) mather_name = models.CharField(max_length=150) mother_language = models.CharField(max_length=150) other_language = models.CharField(max_length=150) religion = models.CharField(max_length=250) employee_address = models.CharField(max_length=250) hearth_status = models.CharField(max_length=50, choices=HEARTH) there are other fields that i didn't include here form.py i have my 3 forms from above Model class Form1(forms.ModelForm): class Meta: model = Application fields=('family_name','first_name','other_name','district','pobox','email','phone','date_of_birth','place_of_birth','gender','status','spouse','nationality','father_name', 'mather_name','mother_language','other_language','religion','employee_address','hearth_status','comment') class Form2(forms.ModelForm): class Meta: model = Application fields = ('school_fees_sponsor','sponsor_address','sponsor_letter','program','course', 'training_site','name_of_secondary_school','year_began','year_of_completion') class Form3(forms.ModelForm): class Meta: model = Application fields=('name_of_institution','started_year','end_year','re_name','re_phone','re_name_two','re_phone_two','note', 'all_documents') my views.py class UndergraduateApplicationFormView(SessionWizardView): instance = None template_name = 'application/ugraduate.html' form_list=[Form1,Form2,Form3] file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'applicarion_files')) def done(self, form_list, **kwargs): return render(self.request, 'application/ugraduate.html', { 'form_data': [form.cleaned_data for form in form_list] }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) my html template this is a html file tha i creeated my own {{ wizard.management_form }} {% if wizard.form.forms %} {% for form in wizard.form.forms %} {{ wizard.form.management_form }} {{ form }} {% endfor %} … -
Django : get value from different table and calculate fields
I would like to get 'weight' from 'Product' and calculate 'total_weight=weight*quantity' as shown on html class Product(models.Model): code = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64) weight = models.DecimalField(max_digits=20, decimal_places=2) class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey(Client,on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) def total(self): return round(self.price * self.quantity, 2) And the html : {% for product in object.invoiceitem_set.all %} <tr> <td>{{product.product}}</td> <td>{{product.price}}</td> <td>{{product.quantity}}</td> <td>{{product.total}}</td> <td>{{product.weight}}</td> <td>{{product.total_weight}}</td> </tr> -
Adding custom views to django admin interface to add more functionality
So I'm trying to extend Django's admin interface. I want to add more functionality to it without overriding it completely. I have a view in my app which returns a list of users who have registered in a particular time frame (last 24 hours e.t.c.) and also a toggle button which can deactivate or activate the users at will. The thing is, I initially created it with it's own template and everything, but now I don't want to reinvent the wheel and just want to add it to django's own admin interface. I've checked multiple solutions online, however they all involve using models, whereas I'm not trying to use any particular model. I just want to be able to pass context from my views to the template. So I'm trying to have something like in the image above, but in the django admin interface. Like just in a div below the other fields. Below are the views that display the data and the toggle buttons @staff_member_required def custom_admin(request): if request.user.is_staff: users_in_past_24_hours = CustomUser.objects.filter(created_at__gt=time_threshold(24)) users_in_past_week = CustomUser.objects.filter(created_at__gt=time_threshold(168)) users_in_past_month = CustomUser.objects.filter(created_at__gt=time_threshold(730)) context = {"users_in_past_24_hours": users_in_past_24_hours, "users_in_past_week": users_in_past_week, "users_in_past_month": users_in_past_month} else: return redirect('unauthorized') return render(request, 'admin_dashboard.html', context) @require_POST @staff_member_required def toggle_user_status_true(request, user_id): user … -
Django Custom UserAdmin wrong change user password URL
I'm doing some refactors on an application written in Django and I've noticed that the URL to change the password for the desired user is wrong in the link. Instead of /admin/myapp/user/<:id>/password/ the url on the link is /admin/myapp/user/<:id>/change/password/. If I go to /admin/myapp/user/<:id>/password/ I can see the password reset screen for django admin but the link to click is wrong. This is my class: @admin.register(User) class UserAdmin(UserAdmin): inlines = [CarInline, ] search_fields = ['id', 'email'] fieldsets = ( (None, {'fields': ('email', 'password')}), ( 'Personal info', { 'fields': ( 'full_name', 'date_of_birth', 'gender', ) }, ), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ) add_fieldsets = ((None, {'classes': ('wide',), 'fields': ('email', 'password1', 'password2')}),) form = UserUpdateForm add_form = UserCreateForm list_display = ('id', 'email') list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups') ordering = ('email',) -
when error are thrown by these validators they are shown in cmd but i want them to be shown beside the form fields itself
from django.db import models from django.core.validators import DecimalValidator,MinValueValidator,MaxValueValidator from django.contrib.auth import get_user_model as user_model import datetime User = user_model() # Create your models here. class BasicInfo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="basicinfo", null=True) date = models.DateField(default=datetime.date.today) temp = models.DecimalField( max_digits = 4 ,decimal_places=1,validators=[DecimalValidator(max_digits = 4 ,decimal_places=1)]) headache = models.BooleanField() running_nose = models.BooleanField() sore_throat = models.BooleanField() loss_smell_taste = models.BooleanField() difficulty_breathing = models.BooleanField() oxygen_level = models.IntegerField(validators=[MaxValueValidator(0,"To low value"),MaxValueValidator(1000,"Might be incorrect")]) travel = models.IntegerField() objects = models.Manager() def __str__(self): return str(self.pk) if any error is given by these validators error is shown in the cmd but I want it to show beside the input field how to I pass these error there -
I'm making a user login and Registration app in Django and need help in message module of django
I am making an application using Django auth. when the user gets register or activated I want to show success and error messages. Views.py from django.shortcuts import render, redirect from django.views.generic import View from validate_email import validate_email from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError # from django.contrib.auth.tokens import PasswordResetTokenGenerator from .utils import generate_token from django.core.mail import EmailMessage from django.conf import settings from django.contrib.auth import authenticate, login, logout # Create your views here. from django.contrib import messages class RegistrationView(View): def get(self, request): return render(request, 'login/register.html') def post(self, request): data = request.POST global messages context = { 'data': data, 'has_error':False} username=request.POST.get('username') email=request.POST.get('email') password1=request.POST.get('password1') password2=request.POST.get('password2') if not validate_email(email): messages.add_message(self.request, messages.INFO, 'Pls, Enter valid email.') context['has_error']=True # if len(password1) < 8: # messages.add_message(request,messages.ERROR, 'Password should b 8 inch long, bro') # context['has_error']=True if password1 != password2: messages.add_message(self.request, messages.ERROR, 'Password dont match.') context['has_error']=True try: if User.objects.get(email=email): messages.add_message(self.request, messages.ERROR, 'Email is alredy registered') context['has_error'] = True except Exception as identifier: pass try: if User.objects.get(username=username): messages.add_message(self.request, messages.ERROR, 'Username is taken') context['has_error'] = True except Exception as identifier: pass if context['has_error']: return render(request, 'login/register.html', context) else: user = User.objects.create_user(username=username, email=email) user.set_password(password1) user.is_active … -
Django 2.2 with 2 domains
I have a Django web app and 2 domains. I want to use these domains for the different Django apps. For example: firstdomain.com -> stuff app seconddomain.com -> customer app Is it possible? How should urls.py looks like?