Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{Django} How does the .env file stay hidden/secret?
How does the .env file stay hidden/secret when in the same dir as settings.py, urls.py, and wsgi.py? Should I do something additional to keep my env variables hidden? I will be deploying AWS elastic beanstalk and have the (environment variables ) set like: .env DEBUG=on SECRET_KEY=blah123456 MAILCHIMP_API_KEY=blah123456 Settings.py import os import environ env = environ.Env( #set casting DEBUG=(bool, False) ) # read .env file environ.Env.read_env() MAILCHIMP_API_KEY = env('MAILCHIMP_API_KEY') SECRET_KEY = env('SECRET_KEY') -
django-dynamic-formset add another / delete buttons failing
[enter image description here][1] [1]: https://i.stack.imgurstrong text.com/2D4l2.png Hi, I'm a beginner Django developer writing my first question in stackoverflow. I'm trying to use the django-dynamic-formset plugin to enable the user of my web application to add or delete forms dynamically, by clicking a button, however, instead of getting a "remove" button for every row, I'm getting one for every field in my form as you can see in the picture. Also, when I'm trying to customize the text in the "add another" or "delete" button, this is not working (you can see the script at the end of my html template). I would appreciate if you can tell me what I might be doing wrong. I'm attaching the code of my html template as well. `{% load crispy_forms_tags %} {% load staticfiles %} <table class="formset-test"> {{formset.management_form|crispy}} {% for form in formset.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_row-{{formset.prefix}}"> {% for field in form.visible_fields %} <td> {% if forloop.first %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field|as_crispy_field }} </td> {% endfor %} </tr> {% endfor %} </table> <!-- <p class='btn btn-warning' id='agregar'>Agregar Posición</p> --> <br> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% … -
Django Error: NameError name 'db_table' is not defined
so I am getting this error in cmd when I try to make migrations. Here is my code: from django.db import models from shop.models import Product class Cart(models.Model): cart_id = models.CharField(max_length=250, blank = True) date_added = models.DateField(auto_now_add = True) class Meta: db_table - 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete = models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product This is my models.py file. Thanks for any help you can give. -
pylint doesn't work correctly when pylint_django loaded
When pylint-django is installed error messages like Class 'MyModel' has no 'objects' member disappear. But with them being disappeared some real errors are skipped too. For example, the line MyModel.objectss.all() will not throw an error (note two s in the word objects). Actually, I find it quite interesting, how pylint is marking errors: MyModel.objects.all() (everything is correct) - gives no error. MyModel.objectss.all() (two s in objects) - gives no error. MyModel.objectss.alll() (two s in objects and three l in all) - gives Class 'MyModel' has no 'objectss' member. MyModel.objects.alll() (three l in all) - gives no error. It's like at least two errors must occur in order for pylint to throw an error. I am working withVisual Studio Code 1.39.1, pylint==2.4.2, pylint-django==2.0.11 My Visual Studio's settings.json file looks like this: { "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ] } So, is this a bug or is there something wrong with my config? -
Bootstrap Navbar won't get colored when using with Django
I'm using Django to create an E-Commerce Website. Used Bootstrap navbar in it, but the css I copied from here doesn't work when I use it within the {%block css %} tag. I'm uploading the html here. Any help is largely appreciated. Also, if anybody needs the entire project to get an idea of what might be causing an issue, here's the project. basic.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link rel="stylesheet" href="styles.css"> <title>{% block title %} {% endblock %}</title> <style> {% block css %} .navbar { background-color: #e74c3c; } .navbar .navbar-brand { color: #ecf0f1; } .navbar .navbar-brand:hover, .navbar .navbar-brand:focus { color: #ffbbbc; } .navbar .navbar-text { color: #ecf0f1; } .navbar .navbar-text a { color: #ffbbbc; } .navbar .navbar-text a:hover, .navbar .navbar-text a:focus { color: #ffbbbc; } .navbar .navbar-nav .nav-link { color: #ecf0f1; border-radius: .25rem; margin: 0 0.25em; } .navbar .navbar-nav .nav-link:not(.disabled):hover, .navbar .navbar-nav .nav-link:not(.disabled):focus { color: #ffbbbc; } .navbar .navbar-nav .nav-item.active .nav-link, .navbar .navbar-nav .nav-item.active .nav-link:hover, .navbar .navbar-nav .nav-item.active .nav-link:focus, .navbar .navbar-nav .nav-item.show .nav-link, .navbar .navbar-nav .nav-item.show .nav-link:hover, .navbar .navbar-nav .nav-item.show .nav-link:focus { color: #ffbbbc; background-color: #c0392b; } .navbar … -
(index):84 Uncaught ReferenceError: $ is not defined at (index):84
I try to work with jquery which is native to HTML5. But not success but failed. Because it says (index):84 Uncaught ReferenceError: $ is not defined at (index):84. Triyed many tecknics including copying google apis and microsoft apis. All the answers are related to php or depreciated. Here is my base.html: <script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script language="JavaScript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> Here is the simple code I am using for ajax, you know not the page refresh every time like facebook commenting: <a class="btn btn-secondary btn-sm mt-1 mb-1" id="{{post.pk}}" href="{% url "post-update" post.id %}">{{post.pk}}</a> <script> $(document).ready(function(){ $("button").click(function(){ $("#{{post.pk}}").hide(); }); }); </script> <button>Click me</button> I want the end result as look we recognized $ sign and you can hide all buttons or related id = {{ comment.id }} without page refreshing but that was not the case. -
Why this save() function in django not working properly
`def save(self): super().save() img = Image.open(self.image.path) output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)` I am currently practicing for a Django Project about Post uploading with some basic feature like login ,Register, Update/Profile , In profile section there is a feature to update profile picture of user selected png or jpg of any size and convert into 300x300 to fit in a page. But I don't know why this save feature is not working, Actually the image is saving in my local folder but the size is not updating. Thanks -
How to solve python Issue __import__(name) ImportError: No module named preferences
Stuck with issue as my project require Django==1.7.7 but couldn't proceed with this error. Library I have: Django==1.7.7 django-browserid==2.0.2 django-dynamic-preferences==1.7.1 django-preferences==1.0.0 -
django catch request error when deploy nameserver to ip
when i deploy nameserer to ip host,the django will catch error request from nameservr,may be nameserver sent hearbeat to ip host.How can skip this error from django? Exception happened during processing of request from ('127.0.0.1', 51975) Traceback (most recent call last): File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/data/home/anaconda3/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/data/home/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 169, in handle self.handle_one_request() File "/data/home/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/data/home/anaconda3/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer -
DjangoFilterBackend date search format
I have the following class with DjangoFilterBackend which work for query parameters like: localhost/ett/?date=2019-10-13 class EttListView(generics.ListCreateAPIView): queryset = models.Ett.objects.all() serializer_class = serializers.EttSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['date'] But I need to have call a different date format like below: localhost/ett/?date=Thu Oct 13 2019 Is it possible to achieve this in DjangoFilterBackend ? -
IIS with Hamachi
I am trying to share a Django webapp with IIS and Hamachi, all is fine in debug mode and if I bind the site to my real LAN IP Address. If i create an hamachi lan and put the hamachi IP address to binding the website I cannot reach the site anymore. I have already open the port TCP 90 (the one that i'm using now) on the firewall but nothing happen. In the site log I have no errors. What I am doing wrong? Thanks -
Am I writing my template tag urls correctly?
using Django 2 I am trying to add a shopping cart app to my django project. I am getting this error message: Reverse for 'add_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P[0-9]+)/$'] From my understanding and doing some research I think my problem is that I am not inputting the correct urls in the template tags to link to my views. But I am only 4 weeks in to Django and am a bit lost. I have tried changing the "{% url 'cart_remove' cart_item.product.id %}" and "{% url 'cart_add' cart_item.product.id %}" tags. I have tried adjusting the app and project level urls.py. I have tried to change the base.html, cart.html I have tried changing the views and have read through every file a number of times trying to spot an error or typo. I have been changing things around for about 5 hours now but nothing seems to work. as I said I think it is a problem with my template tags. I reckon I am confused and am trying to link the wrong thing. cart.html {% for cart_item in cart_items %} <tr> <td>{{cart_item.product.name}}</td> <td>{{cart_item.product.brand}}</td> <td>{{cart_item.product.description}}</td> <td>€{{cart_item.product.price}}</td> <td>{{cart_item.sub_total}}</td> <td>{{cart_item.quantity}}</td> <td><a href="{% url 'cart_remove' cart_item.product.id%}"> <span class="glyphicon glyphicon-minus-sign"></span></a></td> <td><a … -
For loop into js object in template
I want to iterate over an object I return from django view to create dynamically columns in a table (each column is a field in a model and I want to be able to switch the model without changing the template) In the html body part of the template the same exact code worked fine, in the script section it's not. Working example non in the script section {% block content %} <div class="d-flex pt-5 pb-2"> <!-- Need to be set to colums initials names using django --> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Show </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton" id="swichable_column"> <!--reate fileds name and Showable names --> {% for name in columns_name %} <div class="checkbox"> <label> <input type="checkbox" checked="checked" class="chackable_name" value="{{ name.1 }}">{{ name.0 }}</label> </div> {% endfor %} </div> </div> </div> <div id="example-table"></div> {% endblock content %} Script section in my tamplet - not working even do it's the same code <script> //define some sample data var tabledata = [ {id:1, first_name:"Oli Bob", age:"12", col:"red", dob:""}, {id:2, name:"Mary May", age:"1", col:"blue", dob:"14/05/1982"}, {id:3, name:"Christine Lobowski the gratest and latest", age:"42", col:"green", dob:"22/05/1982"}, {id:4, name:"Brendon Philips", age:"125", col:"orange", dob:"01/08/1980"}, {id:5, name:"Margret Marmajuke", age:"16", col:"yellow", dob:"31/01/1999"}, … -
django wont store authUser referenced as foreign key in my model
I created my model that have authUser referenced as foreign key, then using django Form API i am trying to store data into my DB but my user field remains null. I have used build-in FORM API to receive an uploaded file and before storing my file, i also store filename. I tried to do the same for userField but django throw ValueError. Models.py class sample(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True ,default=1) submit_time = models.DateTimeField(auto_now=True) file_name = models.CharField(max_length=1024) score = models.FloatField(default=0.0) is_pending = models.BooleanField(default=True) is_complete = models.BooleanField(default=False) json_URL = models.FilePathField() sample = models.FileField(upload_to='samples/') Views.py @login_required def upload(request): if request.method == 'POST': file = request.FILES['sample'] form = SampleForm(request.POST, request.FILES) if form.is_valid(): new_sample = form.save(commit=False) new_sample.file_name = file.name new_sample.user = User.id #throws ValueError Cannot assign "sample.user" must be a "User" instance. form.save() return redirect('reports') else: print("form is invalid") else: form = SampleForm() if request.method == 'GET': return render(request, 'upload2.html', {'form': form}) forms.py class SampleForm(forms.ModelForm): class Meta: model =sample fields=('sample',) my goal is to save the user id in my db so i know who uploaded the file. -
How to use multithread with celery?
I'm trying to improve my application with celery, I would like to run several tasks in parallel. To achieve it, i'm using the group function of celery. When i'm trying i'm facing two issues : celery-beat_1 | app = self.tasks[0].app celery-beat_1 | AttributeError: 'NoneType' object has no attribute 'app' The second issue, when I add ".s" (group(scrapp.s(url_objects) for url_objects in listUrl) : celery_1 | kombu.exceptions.EncodeError: Object of type Url_lbc is not JSON serializable tasks.py from __future__ import absolute_import, unicode_literals import json import random import time from datetime import datetime from celery import group import requests from django.core import mail from django.db.models.aggregates import Count from django.template.loader import render_to_string from django.utils.html import strip_tags from scrapper.models import Proxy, Scrapper, Url_lbc from celery import shared_task from scrapper.proxy_broker import crawl_proxy @shared_task def scrapp(url_objects): try: url_api = "*********" proxy = get_proxy() print('proxy.id') print(proxy.id) proxyDict = { "http": proxy.address, "https": proxy.address, } print(proxyDict) ua = user_agent_func() user = url_objects.user email_user = user.email token = Url_lbc.objects.get(token=url_objects.token) start = time.time() response = requests.post(url_api, headers=headers, data=json.dumps( payload), proxies=proxyDict, timeout=10) roundtrip = time.time() - start print(response.status_code) print(roundtrip) if response.status_code == 200: array = [] for ad in ads: list_ad = {} **** some treatment**** try: a = Scrapper.objects.get(id_lbc=ids, user=user) except Scrapper.DoesNotExist: … -
Define class variables with respect to 'self'
So I am trying to set up a django form and I want to use Django Choicefield. Now for choicefield you have to supply it choices which is essentially a list of tuples. I am trying to use a self.locales_allowed declared in init() in place of the class variable locales_allowed. class XXX(forms.Form): def init(self): self.locales allowed = XX locale = forms.ChoiceField( label=label["locale"], choices=locales_allowed, required=True) #How to use self.locales_allowed here? I keep getting NameError: name 'self' is not defined if I try to do that. I am looking for a way to get this done. -
Django REST framework API occurs ConnectionDoesNotExist
I am learning the decoupled Django with Django-rest-framework and React for web development. The database is PostgreSQL. I have configured API, and when I run http://127.0.0.1:8000/api, it looks fine: enter image description here But if I click the link in this API(http://127.0.0.1:8000/api/todos/), it fails: enter image description here I can't figure out what is going on. my backend/urls.py is: from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from todos import views router = routers.DefaultRouter() router.register(r'todos', views.TodoView,'todo') urlpatterns = [ # url(r'^', include('todos.urls')), url(r'^api/', include(router.urls)), url(r'^admin/', include(admin.site.urls)), ] my backend/settings.py is: # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'igphn#&4b(67(*=!u)lr1wr=jtfhvgwc03nl&5+t7m18%-#ttm' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'todos', 'corsheaders', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', ) ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
get() takes from 2 to 3 positional arguments but 4 were given. Why is this error occuring? What is the solution for this?
I was working on a comment of a blog project. When I typed the code to handle the POST request in the views.py but was getting a error. This was the error 'get() takes from 2 to 3 positional arguments but 4 were given'. models.py class commenttable(models.Model): comment_id = models.AutoField(primary_key=True, default=0) blog = models.TextField() comment_name = models.CharField(max_length=200) comment_email = models.EmailField() comment_Text = models.TextField() comment_date = models.DateField() def __str__(self): return self.comment_Text views.py from .models import commenttable ... def post_comment(request, blog_id): if request.method == 'POST': data = request.POST.get("name", "email", "comment") # blog = get_object_or_404(Blog_tables, pk=blog_id) p = commenttable(blog= data.name, comment_name=data.email, comment_email= data.email, comment_Text= data.comment, comment_data = timezone.now()) p.save() return HttpResponseRedirect('/thanks/') else: return render(request, '/blogs/' + blog_id + '/comment', {'error_message': 'Error'}) This is the form : <form action="/blogs/{{blog_id}}/comment" method ="post"> {% csrf_token %} <input type="text" name="name" id="name" placeholder="Enter Your Name"/> <input type="text" name="email" id="email" placeholder="Enter Your Email"/> <input type="text" name="comments" id="comments" placeholder="Comments here"/> <input type="submit" value="Post"/> </form> I want to get the data from POST request and save it to the database. But writing this code gives me error 'get() takes from 2 to 3 positional arguments but 4 were given'. -
I m confused about the ready function used inside app.py
i m doing some project using django frame work i am a beginner and just used django signals but i m confused that why do we need to imporrt signals file in app.py inside the ready function code below makes question more clear i m stuck in this so require help signal.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def save_profile(sender,instance,**kwargs): instance.profile.save() app.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals #i have no idea what this function does what is the need of ready function here and why is it importing signals here??? -
How to rollback to a transaction made by django default, in MySQL?
so I have a django app using MySQL database, the client asked for some database records deletions, and one of our developers did the deletions manually from the MySQL console, now I'm trying to recover it to the previous state, I don't have any backups, I read that django does transactions automatically by default,so I want to know how can I rollback to one of these transactions. I already seen this and this, none of them helped me. -
How to correctly write url for #hashtag in Django
I want to insert data with modal form and show it on current page. Page already show data on table and modal form, now i need to add modal form to urls.py. path('viewpost/#add_data_Modal', views.createpost, name='createpost'), -
Error log PythonAnywhereDjango Python PythonAnywhere
Why does hosting on pythonanywhere not work? The syntax seems to me to be correct? Everything works fine on my computer. http://fixitcemes.pythonanywhere.com/ https://www.pythonanywhere.com/user/fixitcemes/files/var/log/fixitcemes.pythonanywhere.com.error.log models.py class Device(models.Model): """Model representing a device.""" type_name = models.ManyToManyField(DeviceType, help_text='Select a device type') device_id = models.DecimalField(max_digits=4, decimal_places=0) short_name_device_own = ForeignKey(DeviceType, related_name='device_type_device', on_delete=models.SET_NULL, null=True) prod_year = models.DateTimeField(auto_now=False, auto_now_add=False) worked_science = models.DateField(auto_now=False) def __str__(self): """String for representing the Model object.""" return f'{self.short_name_device_own} - {self.device_id}' error log: 2019-10-13 10:05:37,509: Error running WSGI application 2019-10-13 10:05:37,510: File "/home/fixitcemes/fixitcemes.pythonanywhere.com/mysite/dokumenty/models.py", line 38 2019-10-13 10:05:37,510: 2019-10-13 10:05:37,511: return f'{self.short_name_device_own} - {self.device_id}' 2019-10-13 10:05:37,511: 2019-10-13 10:05:37,511: ^ 2019-10-13 10:05:37,511: 2019-10-13 10:05:37,511: SyntaxError: invalid syntax 2019-10-13 10:05:37,511: File "/var/www/fixitcemes_pythonanywhere_com_wsgi.py", line 15, in <module> 2019-10-13 10:05:37,512: application = get_wsgi_application() 2019-10-13 10:05:37,512: 2019-10-13 10:05:37,512: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-10-13 10:05:37,512: django.setup(set_prefix=False) 2019-10-13 10:05:37,512: 2019-10-13 10:05:37,512: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/__init__.py", line 24, in setup 2019-10-13 10:05:37,513: apps.populate(settings.INSTALLED_APPS) 2019-10-13 10:05:37,513: 2019-10-13 10:05:37,513: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate 2019-10-13 10:05:37,513: app_config.import_models() 2019-10-13 10:05:37,514: 2019-10-13 10:05:37,514: File "/home/fixitcemes/.virtualenvs/fixitcemes.pythonanywhere.com/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models 2019-10-13 10:05:37,514: self.models_module = import_module(models_module_name) 2019-10-13 10:05:37,514: *************************************************** 2019-10-13 10:05:37,514: If you're seeing an import error and don't know why, 2019-10-13 10:05:37,515: we have a dedicated help page to help you debug: 2019-10-13 10:05:37,515: https://help.pythonanywhere.com/pages/DebuggingImportError/ -
Django unit tests ask to delete MariaDB DB: (1007, "Can't create database 'test_x_django'; database exists")
I have django unit tests creating a MariaDB database for tests. I am accessing the database with a user and password in the settings file and keep getting this error: Type 'yes' if you would like to try deleting the test database 'test_x_django', or 'no' to cancel: Got an error creating the test database: (1007, "Can't create database 'test_x_django'; database exists") Which makes me type 'yes' every time that I run unit tests - specifically after stopping tests in the middle (not allowing django to delete the database?). I have tried a lot of solutions, including: trying to use the root user, giving django_user all permissions to 'test_x_django' db, giving django_user permissions to createdb. I have not found a solution online for MariaDB, in this case. The configuration in my settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'x_django', 'USER': 'django_user', 'PASSWORD': 'xxxx', 'HOST': 127.0.0.1, 'PORT': '3306' } } Is there a solution to make django stop asking the question, and delete the Database automatically? -
DRF: "GET Not Allowed", on a generic view set with ListModel mixin
I have 2 viewsets on the same url, one for Create and List the other one for retrieve update and destroy. The Viewset Code is follows class UserViewSet(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): """ retrieves user accounts """ queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) class UserCreateViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """ Creates user accounts """ queryset = User.objects.all() serializer_class = CreateUserSerializer permission_classes = (AllowAny,) def list(self, request, *args, **kwargs): email = self.request.query_params.get('email', None) phone_no = self.request.query_params.get('phone_no', None) if email is not None: queryset = User.objects.filter(email=email) elif phone_no is not None: queryset = User.objects.filter(phone_no=phone_no) else: queryset = User.objects.all() return super(UserCreateViewSet, self).list(request, *args, **kwargs) This is my url configuration: router = DefaultRouter() router.register(r'users', UserCreateViewSet) router.register(r'users', UserViewSet) router.register(r'advertisement', AdvertisementCreateViewSet) router.register(r'advertisement', AdvertisementViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api-token-auth/', CustomAuthToken.as_view()), path('api-token-auth/verify-otp', VerifyTokenView.as_view()), path('api-token-auth/verify-email', VerifyEmailView.as_view()), path('api/v1/admin/login', LoginAdminUser.as_view()), path('api/v1/user/reset-password/', ResetPasswordView.as_view()), url('api/v1/user/(?P<id>.+)/changePassword', ChangePasswordView.as_view()) path('api/v1/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), re_path(r'^$', RedirectView.as_view(url=reverse_lazy('api-root'), permanent=False)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The advertisement ViewSet does the exact same thing on a different model and it works seemlessly. But in the UserViewSet it doesn't..I tried comparing the code of both viewsets and they are exactly the same.... -
django user authentication and authorization
I need suggestion on the following issue, actually I start developing a small erp in django. I’m quite confuse about how to handle user authentication and authorization. My project architecture is ERP (Main Project) o HR (App) o Finance (App) o Payroll (App) o Sale (App) How to implement login system in above architecture? Thanks