Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I reverse word when I put it to form. It must look like when I wrote Python it must looks like nohtyP
How can I reverse word when I put it to form. Example I wrote Python it must looks like nohtyP in DB it must be saved as reversed. Any help thanks **views.py** from django.shortcuts import render from django.views.generic import TemplateView, CreateView from django.http import HttpResponse from .models import Post class HomePageView(CreateView): model = Post template_name = 'home.html' fields = ['body', ] class AboutPageView(TemplateView): template_name = 'about.html' **models.py** from django.core import validators from django.db import models from django.urls import reverse from .validators import isalphavalidator class Post(models.Model): regex = r'^[A-z][\w ]{2,31}$' body = models.CharField(validators=[isalphavalidator], max_length=30, null=False, blank=False, unique=True) def str(self): return self.body def get_absolute_url(self): return reverse('about') -
Django prevent users from editing their own record in admin
In Django I have model called Loans. I want users to be able to edit a loan created by someone else, but not if they created it themselves. As a bonus, I would like staff members not to be able to edit loans that belong to other staff. How can I do this? I really have no idea. I tried creating custom validation, then I tried a manger like this: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from core.models import User class LoanManager(models.Manager): def create_loan(self, request, borrower, approved, start_date, term_in_months, principal, interest_rate_pa, **extra_fields): """Creates and saves a new loan""" print('USER========================================', request.user) if borrower != request.user: raise ValueError("Staff may not lend to themselves or other staff") return super(LoanManager, self).create(borrower=borrower, approved=approved, start_date=start_date, term_in_months=term_in_months, principal=principal, interest_rate_pa=interest_rate_pa,**extra_fields) class Loans(models.Model): borrower = models.ForeignKey(User, on_delete=models.CASCADE) approved = models.BooleanField(default=False) start_date = models.DateField(auto_now_add=True) term_in_months = models.IntegerField(validators=[ MaxValueValidator(360), MinValueValidator(24) ]) principal = models.IntegerField(validators=[ MaxValueValidator(1000000), MinValueValidator(2000) ]) interest_rate_pa = models.DecimalField(max_digits=5, decimal_places=2) objects = LoanManager() Nothing I do seems to prevent users creating loans for themselves and editing them! -
Is there any way of mentioning two login_redirect_urls in django?
In my application, if the user logs in for the first time, he is redirected to the profile page and from the second time, he is redirected to the homepage (VChome in my appliation). So I decided to write this in urls.py and views.py urls.py from django.urls import path from . import views urlpatterns = [ path('VC/',views.VChome, name='VChome'), path('profile/',views.update_profile,name='profile'), path('users/login/', views.login_user, name='login'), ] views.py def login_user(request): logout(request) username = password = '' if request.POST: username = request.POST['username'] password = request.POST['password'] userLL = CustomUser.objects.get(username=username) last_login = userLL.last_login user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if last_login==None: return HttpResponseRedirect(reverse("profile")) else: return HttpResponseRedirect(reverse("VChome")) return render(request, 'login.html') login.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> {% block content %} <form method="post"> <strong><p>Sign in</p></strong> <p>Username</p> {% csrf_token %} <input type="text" id="username" name="username" placeholder="Username"> <p>Password</p> {% csrf_token %} <input type="password" name="password" id="password" placeholder="Password"> <input type="submit" value="Login"> </form> {% endblock %} </body> </html> I have templates profile.html and VChome.html and I'm sure that they are rendered correctly in views.py The problem here is if I mention LOGIN_REDIRECT_URL = 'VChome', the login page is redirected to VChome. If I don't mention it, login page is redirected to /accounts/profile I want the login … -
Making a Django page visible only to confirmed emails
I'm trying to add a feature to my site where a certain part of the site can be used only by users who confirmed their email account. I found a solution, but it's not working. Here is what i did: I have been suggested to add a separate model for this: class account_emailconfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @property def has_verified_email(self): return self.user.emailaddress_set.filter(verified=True,primary=True).exists() And this is what the template looks like: {% extends "main/header.html" %} {% if user.profile.has_verified_email %} {% block content %} <style> </style> <body> <div> <p>Here goes a bunch of features</p> </div> </body> {% endblock %} {% else %} <p> Your email is ot confirmed </p> {% endif %} But it's not working, since i can see the page even without having to confirm my email. Here is what my db looks like: There is a table called account_emailconfirmation, then there is an index, verified, that will give 0 when the account is not verified, 1 when it is verified. Any advice is appreciated! -
I want to create multiple objects on saving the form
I want to create multiple objects of same field on saving the form. for example: i have a model name Pension and two other model Payrise and Bonus that are link to model Pension with foreign key. so when i save pension create form i also want to save multiple values to payrise and bonus model. def PensionCreateView(request): if request.method == 'POST': pension=Pension() pension.pension_provider= request.POST.get('pension_provider') pension.pension_scheme_id= request.POST.get('pension_scheme_id') pension.pension_scheme_name= request.POST.get('pension_scheme_name') pension.scheme= request.POST.get('scheme') pension.salary_sacrifies= request.POST.get('salary_sacrifies') pension.payrise_type= request.POST.get('payrise_type') pension.bonus_type= request.POST.get('bonus_type') pension.contribution_type= request.POST.get('contribution_type') contribution = pension.contribution_type pension.contribution_rates= request.POST.get('contribution_rates') pension.save() payrise = Payrise() payrise.payrise_month = request.POST.getlist('payrise_month[]') -
How to use pop up box properly in django url
Here i am trying to display pop up box after user clicks the delete link.and the below code does this pretty well and deletes the item also but the little problem is while i load the template this delete_pop_box.html page also loads first (for like 1 sec) then only the template appears.it might be because i done {% include %} at the top.if it is then how an i solve this issue delete_pop_up_box.html <title>delete</title> <!--Delete button will redirect to the href of the element with 'id = caller-id' property in this modal--> <div class="modal fade" id="confirmDeleteModal" tabindex="-1" caller-id="" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body confirm-delete"> Are You Sure You want to delete ? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmDeleteButtonModal">Delete</button> </div> </div> </div> </div> template {% load bootstrap4 %} {% include 'admin/delete_pop_up_box.html' %} <td>{{user.last_login}}</td> <td>{{user.date_joined}}</td> <td><a href="{% url 'admin:edit_user' user.id %}"> Edit</a></td> <td><a href="{% url 'admin:delete_user' user.id %}" class="confirm-delete" title="Delete" data-toggle="modal" data-target="#confirmDeleteModal" id="deleteButton{{user.id}}"> Delete</a></td> </tr> <script> $(document).on('click', '.confirm-delete', function () { $("#confirmDeleteModal").attr("caller-id", $(this).attr("id")); }); $(document).on('click', '#confirmDeleteButtonModal', function () { var caller = $("#confirmDeleteButtonModal").closest(".modal").attr("caller-id"); window.location = $("#".concat(caller)).attr("href"); }); </script> -
Django custom login form returns None
I am trying to authenticate a user by using a custom login form, but authenticate() returns None. I created a custom login form template, an index view which shows the login form to unauthenticated users and another template to authenticated ones, I "mapped" the appropriate URLs to the desired views functions and added some debug messages with print to know in which part of the code the flow stops. In views.py def index(request): if request.user.is_active and request.user.is_authenticated: print(request.user) if request.user.groups.filter(name='groupname').exists(): print('does have groups') else: print('doesnot have groups') return render(request, 'generic_pages\\index_and_login\\menu1.html', {}) else: return render(request, 'generic_pages\\index_and_login\\generic_login.html', {}) def login_user(request): print('We are in login_user') logout(request) username = password = '' if request.POST: print('We know we have a POST request') username = request.POST['login'][0] password = request.POST['login'][1] user = authenticate(username=username, password=password) print(user) #Prints the user object if user is not None and user.is_active: print('We know user is active') login(request, user) return HttpResponseRedirect('/') In urls.py urlpatterns = [ path('admin/', admin.site.urls), #path('accounts/', include('django.contrib.auth.urls')), re_path(r'^$', views.index, name='index'), path('', views.index, name='index'), re_path(r'^login', views.login_user, name='login_user'), re_path(r'^logout', views.logout_user, name='logout_user'), re_path(r'^.*/$', views.handler404, name='handler404'), ] In generic_login.html {% load static %} <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'generic_pages/index_and_login/css/generic_login.css' %}" > <div class="wrapper fadeInDown"> <div id="formContent"> … -
How to loop through django formset id in jquery?
My model: class Stock_total(models.Model): purchases = models.ForeignKey(Purchase,on_delete=models.CASCADE,null=True,blank=False,related_name='purchasetotal') stockitem = models.ForeignKey(Stockdata,on_delete=models.CASCADE,null=True,blank=True,related_name='purchasestock') quantity_p = models.PositiveIntegerField(default=0) rate_p = models.DecimalField(max_digits=10,decimal_places=2,default=0.00) disc_p = models.DecimalField(max_digits=10,decimal_places=2,default=0) total_p = models.DecimalField(max_digits=10,decimal_places=2,default=0.00,null=True,blank=True) This model performs a inline_formset with the Purchase model.. So as every one knows the id of the fields in an inline_form is not same for every field it increase in number as we go down or add a form. For example: The id for the form field quantity_p in the 1st line of form is id_purchasetotal-0-Quantity_p and in the second line of form is id_purchasetotal-1-Quantity_p (** Notice the number changes as we increase the line of a formset) My question is that how to loop over the id of a formset in jquery as because I have to perform some calculation in my form: I want to perform something like this but inside a for loop: <script type="text/javascript"> $(document).ready(function(result){ if($("#id_purchasetotal-0-Disc_p").val() != ''){ $('#id_purchasetotal-0-Quantity_p, #id_purchasetotal-0-rate_p, #id_purchasetotal-0-Disc_p').on('change', function() { $('#id_purchasetotal-0-Total_p').val($('#id_purchasetotal-0-Quantity_p').val() * $('#id_purchasetotal-0-rate_p').val() * (1 - ($("#id_purchasetotal-0-Disc_p").val()/100))); }); } else { $('#id_purchasetotal-0-Quantity_p, #id_purchasetotal-0-rate_p').on('change', function() { $('#id_purchasetotal-0-Total_p').val($('#id_purchasetotal-0-Quantity_p').val() * $('#id_purchasetotal-0-rate_p').val()); }); } }); </script> Any idea how to do this? Thank you -
which programing language i can use to develop both android and ios applications as frontend and django as backend?
which programing language i can to develop both android and ios applications as front-end and Django as back-end ? i am developing a back-end using Django which is the best language for both android and ios for application and ease of linking ? -
How to access data using reverse foreign key reference in django
I have a model named UserProfile and a model PersonalInformation. I would like to fetch all the data of PersonalInformation using UserProfile model when the user is logged into the webiste but i have a foreign key refernce in the PersonalInformation model with the UserProfile model so how do i fetch the personal information using UserProfile model? User Profile Model : class PersonalInformation(models.Model): """Represents a user's personal Infromation inside our system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) profile_picture = models.ImageField(upload_to='photos/%y/%m/%d/') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) highest_degree_earned = models.CharField(max_length=255, blank=False) college_name = models.CharField(max_length=255, blank=False) graduation_year = models.IntegerField(default=2020, blank=False) Personal Information Model : class PersonalInformation(models.Model): """Represents a user's personal Infromation inside our system""" user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) mobile = models.CharField(max_length=10 ,blank=True) bio = models.TextField(max_length=200, blank=True) college_university = models.CharField(max_length=100, blank=False) course = models.CharField(max_length=100, blank=False) -
How to sum django model fields
class Salary() : Basic = models. IntegerField () Allowance = models. IntegerField () Incentivies = models. IntegerField () gross = models. IntegerField () gratuity = models. IntegerField () Ctc = models. IntegerField () Here my problem is gross = basic+ allowance+ incentives ctc= gross+gratuity How should I sum for that, no need to enter the value of gross or ctc. It should sum -
django template styntex {% if p.category == "help" %} {% endif %} is not work
As a result of executing the code below {{p.category}} <!-- help --> {% if p.category == "help" %} <button type="button" class="btn btn btn-outline-danger btn-sm" style="color:blue;"> <a href="{% url "todo:todo_help" p.pk %}" >help 11</a> </button> {% else %} <button type="button" class="btn btn btn-outline-danger btn-sm"> <a href="{% url "todo:todo_help" p.pk %}" >help 22 </a> </button> {% endif %} I expected the help11 button to be output. The reason is that {{p.category} is 'help' But the output button was help22. I do not know why that's not work Is this comparison logic wrong? If you know the reason, please let me know. -
OperationalError at /admin/todo/todo/ in Django
I'm making a basic Todo app in django . While going to the admin page and clicking on the Todo optionThe Todo option i have created it gives me this error see the address bar Two times todo/todo occurs I have already done the migartions thing and i have added the todo.apps.TodoConfig in the INSTALLED_APPS Here is my code:- todo app urls.py `from django.urls import path from todo import views urlpatterns = [ path('', views.index), path('todo/', views.index,) ]` todo app views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello ") todo app models.py from django.db import models from datetime import datetime class Todo(models.Model): title = models.CharField(max_length = 200) text = models.TextField() created_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.title todo app admin.py from django.contrib import admin from .models import Todo admin.site.register(Todo) **The main project urls.py** from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('ToDoList/', include('ToDoList.urls')), path('Todo/', include('todo.urls')), ] -
How can I style table data differently according to the cell value?
I am new to django and I try to stylize a cell data according to it's value but not working. '''python class StatusPorumbei(models.Model): status = models.CharField(max_length=25, null=False, blank=False, unique=True) def __str__(self): return self.status class Meta: verbose_name = "Status" verbose_name_plural = "Statusuri" ordering = ['status'] class Porumbei(models.Model): id_porumbel = models.AutoField(primary_key=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True) anul = models.CharField(max_length=4, null=False, blank=False) culoare = models.ForeignKey(CuloriPorumbei, on_delete=models.CASCADE, null=False, blank=False) culoare_ochi = models.ForeignKey(CuloriOchi, on_delete=models.CASCADE, null=False, blank=False) sex = models.ForeignKey(Gender, on_delete=models.CASCADE) ecloziune = models.DateField(null=True, blank=True) rasa = models.CharField(max_length=50, null=True, blank=True) linie = models.CharField(max_length=50, null=True, blank=True) nume = models.CharField(max_length=50, null=True, blank=True) tata = models.CharField(max_length=25, null=True, blank=True) mama = models.CharField(max_length=25, null=True, blank=True) compartiment = models.ForeignKey(Compartimente, on_delete=models.CASCADE, null=False, blank=False) status = models.ForeignKey(StatusPorumbei, on_delete=models.CASCADE, null=False, blank=False) -
ModuleNotFoundError: No module named '__main__.models'
This is the project skeleton. Directory: users. testing.py and models.py are in users directory. For the following code, the mentioned error is generated: from .models import CustomUser username='Jason' userLL = CustomUser.objects.get(username=username) print(userLL) last_login = userLL.last_login print(last_login) Error is Traceback (most recent call last): File "C:/Users/lenovo/Desktop/vidyaConnect/users/testing.py", line 1, in <module> from .models import CustomUser ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package If i remove the dot (.) before models, I get the following error Traceback (most recent call last): File "C:/Users/lenovo/Desktop/vidyaConnect/users/testing.py", line 1, in <module> from models import CustomUser File "C:\Users\lenovo\Desktop\vidyaConnect\users\models.py", line 1, in <module> from django.contrib.auth.models import AbstractUser File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\lenovo\Desktop\projectVC\venv\lib\site-packages\django\conf\__init__.py", line 64, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
How to pass in a model in a redirect request in django
I'm creating a login View in which soon after a user is authenticated I'm logging that user in by redirecting to 'dashboard' page but I also want to sent additional data about the user to the 'dashboard' page so that I can display it dynamically on the template. For this, I'm trying to send a model as a parameter in redirect but django is not displaying anything on the template. if user is not None: # authenticate the user auth.login(request, user) # Fetch additional information about the user # fetching presonal-Information try: personal_info = PersonalInformation.objects.get(user_id=user.id) except ObjectDoesNotExist: personal_info = None return redirect('dashboard', personal_info) else: messages.error(request, 'Invalid credentials') return redirect('login') else: return render(request, 'pages/login.html') -
Django stops with "generator raised StopIteration" when html form allows for file upload
My setup is Windows 10, Python 3.7, Apache 2.4/mod_wsgi. When I add this enctype="multipart/form-data" in my form (just by adding this attribute, only -- no files are attached to the form) I get this error when submitting: Django Version: 1.8.5 Exception Type: RuntimeError Exception Value: generator raised StopIteration Exception Location: c:\users\holistic\envs\vitadmin\lib\site-packages\django\http\multipartparser.py in read, line 337 Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.7.3 Traceback here: http://dpaste.com/0K8MXCV Any ideas what is going wrong? PS: Same django application worked fine in Linux/Nginx/Gunicorn setup. So, I guess it must some misconfiguration between Django/Python/Apache. -
Select data from drop-down list and save it to database in Django
I am a newbie in Django. I want to show the food_status in drop-down list options, therefore the chef can select one of them, change it, and update it into database. It can be updated into database, but i am not sure how to display the drop-down list on template based on the food_status that I have in models.py. Anyone know how to do it? models.py class OrderItem(models.Model): Table_No = models.IntegerField(blank=False) FoodId = models.TextField() Item = models.TextField() Qty = models.DecimalField(max_digits=5, decimal_places=0) Price = models.DecimalField(max_digits=10, decimal_places=2) TotalPrice = models.TextField() Note = models.TextField(max_length=100, null=True) OrderId = models.TextField(max_length=5, null=True) FoodStatus = ( ('1', 'Has been ordered'), ('2', 'cooked'), ('3', 'ready to be served'), ('4', 'done'), ) food_status = models.CharField(max_length=50, choices=FoodStatus) views.py def kitchen_view(request): if request.method == "POST": order_ids = request.POST.getlist("OrderId") food_statuses = request.POST.getlist("food_status") for i in range(len(order_ids)): OrderItem.objects.filter(OrderId=order_ids[i]).update(food_status=food_statuses[i]) chef_view = OrderItem.objects.all() return render(request, 'restaurants/kitchen_page.html', {'chef_view': chef_view}) kitchen_page.html <form action="#" method="post"> <style> table, th, td { border: 1px solid black; table-layout: fixed ; height: "2000" ; width: "2000" ; } </style> {% csrf_token %} {% for order in chef_view %} <table> <tr> <th>Table Number</th> <th>Item</th> <th>Quantity</th> <th>Price</th> <th>Note</th> <th>Order Id</th> <th>Status</th> </tr> <tr> <td>{{ order.Table_No }}</td> <td>{{ order.Item }}</td> <td>{{ order.Qty }}</td> <td>{{ order.Price … -
Get user instance from profile model __str__ in django
I have this simple model: class Profile(models.Model): bio = models.CharField(max_length=300, blank=False) location = models.CharField(max_length=50, blank= edu = models.CharField(max_length=250, blank=True, null=False) profession = models.CharField(max_length=50, blank=True) profile_image = models.ImageField( upload_to=upload_image, blank=True, null=False) def __str__(self): try: return str(self.pk) except: return "" and a User model: class User(AbstractBaseUser, UserTimeStamp): first_name = models.CharField(max_length=50, blank=False, null=False) email = models.EmailField(unique=True, blank=False, null=False) profile = models.OneToOneField(Profile, on_delete=models.CASCADE) uuid = models.UUIDField( db_index=True, default=uuid_lib.uuid4, editable=False ) is_admin = models.BooleanField(default=False, blank=False, null=False) is_staff = models.BooleanField(default=False, blank=False, null=False) is_active = models.BooleanField(default=True, blank=False, null=False) objects = UserManager() USERNAME_FIELD = "email" def has_perm(self, perm, obj=None): return True def has_module_perms(self, perm_label): return True As you can see in User model I have a OneToOneField to Profile. but in Profile model I can't access user instance to just use its email in str method. something like this: def __str__(self): return self.user.email How can I do this? sometime these relations are confusing to me. -
Can't Upload .dcm file in django
I am creating an app for uploading .dcm files of patients and then do processing on these files. But the .dcm files are not uploaded whereas when I try to upload any other type it is shown in the media directory. I have used the code from Github to upload multiple files in Django as for processing I need at least 4 .dcm files of the patient. It works good for npy arrays and all but not for .dcm files. class Doc(models.Model): title = models.CharField(max_length=300, blank=True) file = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) I want the .dcm files uploaded to the documents folder -
How to make sum query with type casting and calculation in django views?
I'm calculating the sold items cost in django views and in django signals, and I want to calculate sold items cost on the fly. Price and quantity fields are integers. How can I convert one of them to the float and make sum query with some calculations like these sql queries below? SELECT sum((t.price::FLOAT * t.quantity) / 1000) as cost FROM public."sold" t; SELECT t.id, t.price, t.quantity, sum((price::FLOAT * quantity) / 1000) as cost FROM public."sold" t GROUP BY t.id; I expected the output of first query 5732594.000000002 and I expected the output of second query id price quantity cost 846 1100 5000 5500 790 1500 1000 1500 828 2600 1000 2600 938 1000 5000 5000 753 1500 2000 3000 652 5000 1520 7600 -
How to extract a photo from TinyMCE and use it as thumbnail in ListView?
Now I have a form which asks user to add the title, content and a photo. Then I use that photo as thumbnail in ListView like: Since user is using WYSIWYG editor in content field, he can add photos from tinymce editor. like this: I would like to add this photo uploaded from within tinymce as thumbanil at ListView like quora.com has already this feature. This is the code that shows thumbnail photo in template: <div class="col-4"> s<img src="{{ blog.image.url }}" class="image_in_list mt-5" alt=""> </div> How do I do this. If you know please help me do it, this would be a great help. Thank you -
Optimize gunicorn and nginx configuration when using 16GB of RAM, 6 vCPUs VPS
Should I change something in my Gunicorn and Nginx configuration when I use 16 GB of RAM, 6 vCPUs DigitalOcean VPS? gunicorn config: [Unit] Description=gunicorn daemon After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myproject ExecStart=/home/sammy/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/sammy/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target nginx config: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/sammy/myproject/myproject.sock; } } -
Can I arbitrarily replace and restore the db.sqlite3 file?
I know that the file db.sqlite3 in Django holds the entire database and the entire content within it. Is it safe to keep all the project files, the *.py files, the migrations files, but replace the db.sqlite3 file with a different one. If both these db.sqlite3 files work on the same database model, with the same tables, rows, columns, and everything, then if I swap out that file it should work seamlessly. I want to copy the original db.sqlite3 file into a different directory. Then I want to create a new db.sqlite3 file in my project. Then I want to work with the new database file, and give it other data to test how the project would work with it. Then I want to delete the new db.sqlite3 file, and I want to restore the old one, which I've saved into another directory. Would that work? And how can I create a new db.sqlite3 file, a clean state to put test data into? Also, what if I build my project on another sever, can I copy my old db.sqlite3 file there too, and have the database with all it's saved data restored? Basically, the main idea of my question is: … -
How can I solve this error "The current path, Logout, didn't match any of these."
Am creating a user login form and logout, when I run the code I get error which says "The current path, Logout, didn't match any of these." I have tried to go through the code again and again it looks Ok but still I get the same error, i don't know where the problem is. tried to look for different examples it looks fine but still i get the same error VIEWS CODE FOR LOGOUT def logout_request(request): logout(request) messages.info(request, "Logged out successfully") return redirect("main:homepage") VIEW CODE FOR LOGIN def login_request(request): form = AuthenticationForm() return render(request, "main/login.html", {"form":form} ) URL CODE urlpatterns = [ path( "", views.homepage, name="homepage"), path("register/", views.register, name="register"), path('logout/', views.logout_request, name='logout'), path("login/", views.login_request, name="login"), ]