Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid hard coding URL when submitting form in Django
I have a Django project with a form on the homepage. When the form is submitted, it hard codes a URL which triggers a view function. I am trying to submit that form and trigger the function without hard coding the URL. I have done some research into reverse and reverse_lazy but the actual implementation still makes no sense to me so I am here for help. index.html: <form action= '/add_trans_form' method="POST" id='formALL'> urls.py app_name ='pages' urlpatterns = [ path('', views.index_view, name='index'), path('add_trans_form', views.add_trans_form, name='trans_form') ] views.py def add_trans_form(request): ~do some top secret stuff to my database~ return HttpResponseRedirect(reverse('pages:index')) please note the project name is AIS and the Django app is 'pages' PLEASE help me understand what I am doing wrong... I would like to process the form without changing the url. -
Adding django channels to existing wsgi server causes 400
There is this open source project called okuna-api that I am trying to modify and add chat to for learning purpose. The original okuna runs on wsgi and works fine. Now for chat, I added channels and added asgi to settings, created the asgi.py and routing.py according to channels docs. After doing this and reinstalling the api, the companion app(flutter) starts showing error 400 for all requests, even though the admin panel accessed via browser is working fine. When checking the server logs, it seems to be asgi server only. Asgi should be backward compatible I believe. I don't know what kind of mistake I am making. Is it not possible to run code for wsgi in asgi ? Is there any further modification needed in asgi.py, routing.py and settings ? Or is it possible to run wsgi and asgi simultaneously ? Or is it just a problem with the flutter requests ? I am a newcomer to django, so what is the best approach to the problem ? -
Django Admin - Include field of a model A when adding a record of model B
I'm working on legacy code which is in Django (1.11) I have a model A, with attributes: Model_A: Name (NOT NULL) City (NOT NULL) FieldX (Nullable) - CharField And a model B, with attributes: Model_B: Name (NOT NULL) City (NOT NULL) RelatedField (ForeignKey to an instance of Model_A) Now, When I add a record for Model_A then I may NOT need to fill FieldX. However, When I add a record for Model_B then I'll have to select an instance of Model_A and then if FieldX of that instance is NULL then I have to fill that as well (make it mandatory). The form for Model_A is pretty straight forward. But for Model_B I need a form where: The first instance of Model_A is selected (Dropdown) The input box for FieldX of instance selected in 1 is shown. The rest of the fields are shown (Name, City, FieldY). Can this be done using the admin page? Or will I have to create proper forms and user flow for this? -
Django not loading static files on subpath
Introduction I am using an implementation of Django REST Framework and API with React (create-react-app) and everything works fine if accessed through the React interface via buttons. Also, some links work fine when accessed from the search bar, like the home page (/) and any immediate paths without a trailing slash (E.g. /a or /archive) as you can see here: The Problem Whenever I try to access immediate paths with trailing slashes or any subpath with or without trailing slashes through the browser it provides this error: The Settings Here are some photos of my Django settings: Django Static Files Settings Django Main URLs Django API App URLs Final Comments Thank you for reading this. I hope the photos are helpful and please let me know if you need any other information and I will provide it. Thank you. -
Search bar with Python-Django
i'm trying to build my first Django blog that someone can make an account, search & update posts and now i want to add a search bar so someone can find others by profile name. But i don't know how to make it exactly, i try to find something on google but nothing help me. i try this: ( on the base.html ) <form type="get" action="/other/path/" style="margin: 0"> <input id="search_box" type="text" name="search_box" placeholder="Search..." > <button id="search_submit" type="submit" >Submit</button> ( on the views.py ) @login_required def search_bar(request): if request.method == 'GET': search_query = request.GET.get('search_box', None) ( on the urls.py ) path('', UserPostListView.as_view() , name='search'), -
Django: is it possible to use data/context from a django rest framework APIview inside HTML?
I have this class view to display some chart.js on my homepage: class chartData(APIView): authentication_classes = [] permission_classes = [] renderer_classes = [TemplateHTMLRenderer] template_name = 'index.html' def get(self, request, format=None): ... data = { "data1": data1, "data2": data2, ... } return Response(data) My function view for the homepage is this: def index(request): return render(request, 'index.html') My question is: Is it possible to use the data from the class chartData(APIView) and display it inside HTML like this --> {{data1}} -
Is there a simple way to design document with Reportlab?
I`ve got an invoice html document designed and looking like I want. I would like to use reportlab to generate a pdf. Each time, I am making some changes to the canvas in my view to match my html document, I need to reload the app and it seems to takes a while to develop this pdf. Is there a quicker to test or create the canvas? Many thanks, -
How to scale Django RQ workers that can read from source directory & be able to write to database?
How to "Scale" RQ workers? I have architecture like this uwsgi/django (machine 1) <=> RQ server (machine 1) <=> RQ worker 1...n (machine 1) Problem is.. RQ workers are eating up all the CPU so the Django/uwsgi is almost unresponsive during high load So I want to do something liket his uwsgi/django (machine 1) <=> RQ server (machine 1) -> RQ worker 1 (machine 2) -> RQ worker 2 (machine 3) -> ... -> RQ worker n (machine n-1) Problem is, I'm using Django RQ (django wrapper for RQ).. and the RQ workers are spawned from a specific directory and need to be able to write to database If I split up the RQ workers into other machines, i need the workers to be able to read from django source directory be able to write to Django App database #2 can be solved with microservice.. however I'm a bit stuck I can do something like SSHFS but i am not 100% certain if this is a "good" design in terms of scalability, security, and of course, complexity ( i dont' want to keep adding more monitors / software stack). Of course, I can just have a script that pulls down … -
I keep getting an error when I deploy my app on heroku
I followed a tutorial on how to deploy apps on heroku After deploying I opened the page and saw application error, I checked my logs 2020-07-29T19:40:59.398818+00:00 heroku[run.1760]: State changed from starting to up 2020-07-29T19:40:59.543326+00:00 heroku[run.1760]: Awaiting client 2020-07-29T19:40:59.573857+00:00 heroku[run.1760]: Starting process with command python manage.py migrate 2020-07-29T19:41:06.780115+00:00 heroku[run.1760]: Process exited with status 0 2020-07-29T19:41:06.825218+00:00 heroku[run.1760]: State changed from up to complete 2020-07-29T19:41:59.632795+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=fruit- wurld.herokuapp.com request_id=59cd7c94-4b9d-4d31-b0bb-e6f03f235c7a fwd="129.205.124.156" dyno= connect= service= status=503 bytes = protocol=https 2020-07-29T19:42:00.036677+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=fruit-wurld.herokuapp.com request_id=44d555d7-ce8a-4aa8-8933-35b72db38d61 fwd="129.205.124.156" dyno= connect= service= statu s=503 bytes= protocol=https -
Posting multiple images and data to database via django
I would like to post multiple pics from my vue.js form (frontend) into my database via django (backend). I'm using this solution for my vue script, but I additionally post picture id, which is foreign key to another table. I've already tried with File Storage API, REST APIView unsuccessfully. Here is my model: class gallery(models.Model): idpic = models.ForeignKey(News, on_delete=models.CASCADE) photo = models.ImageField(upload_to='img', null=True) and my vue script: if(this.disabled2==true){ const id = this.info[0].id + 1; for( var i = 0; i < this.file2.length; i++ ){ let img = this.file2[i]; console.log(obraz); formData2.append('idpic[' + i + ']', id); formData3.append('photo[' + i + ']', img, id + '_' + i + '.jpg'); } } axios.post(link2, formData2, { headers: { 'Content-Type': 'multipart/form-data'} }) .then(res => { console.log(res.data);}) .catch(err => console.log(err)) Below are my 'views.py attempts' #this one doesn't work from the beginning, because body unicode tries to decode file def Gallery(request): if request.method == 'POST': body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) idpic_front = body_data['idpic'] pics = request.FILES['photo'] fs = FileSystemStorage(location="path") for p in pics: insert_gallery = gallery.objects.create(idpic=idpic_front, photo='img'+pics.name) fs.save(pics.name, pics) result = list(insert_gallery) return JsonResponse(fs, rezultat) #this one uploads only the last selected picture class GalleryView(APIView): parser_classes = (MultiPartParser, FormParser) def get(self, request, *args, **kwargs): … -
AttributeError at /stories/6/segnala-commento/14/ 'NoneType' object has no attribute 'storia' Django
How i fix this error??? views.py @login_required def segnalaCommento(request, id, pk): commento = get_object_or_404(Commento, id=commento.storia.id, pk=pk) commento.segnala += 1 commento.save() return HttpResponseRedirect(commento.storia.get_absolute_url()) HTML Page <a href="{% url 'segnala-commento' id=commento.storia.id pk=commento.pk %}"><p class="badge badge-danger mb-0">Segnala</p></a> urls.py path('<int:id>/segnala-commento/<int:pk>/', segnalaCommento, name="segnala-commento"), Thank you -
Problem running celery: No module named 'transport'
I'm using Celery in Django project but when I try to run celery worker -A my_app -l info or celery beat -A my_app -l info, the following error is triggered: celery worker -A my_app -l info return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'transport' celery beat -A my_app -l info [2020-07-29 14:14:07,506: WARNING/MainProcess] ModuleNotFoundError [2020-07-29 14:14:07,506: WARNING/MainProcess] : [2020-07-29 14:14:07,506: WARNING/MainProcess] No module named 'transport' I don't know where this mistake came from. Celery configuration CELERY_TIMEZONE = TIME_ZONE CELERY_BROKER_URL = redis://localhost:6379 CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_TIME_LIMIT = 5 * 60 CELERY_TASK_SOFT_TIME_LIMIT = 60 Celery set up from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") app = Celery("my_app_name") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() current task from celery import shared_task @shared_task def send_message_with_attachments(message) -> None: """Send mails or Whatsapps with attachments.""" send_mail( subject=message.subject, message=message.content, recipient_list=message.recipient_mails, ) Task execution I execute the task in admin @admin.register(Message) class MessageAdmin(admin.ModelAdmin): def save_related(self, request: Any, form: Any, formsets: Any, change: bool) -> None: super().save_related(request, form, formsets, change) send_message_with_attachments.delay(form) Environment … -
What is the difference between DTL and jinja2 in Django?
I read many Articles but the answer was not satisfying. Well I have been using DTL and I'm good satisfied with it. Jinja is similar library which is cool too. But being Django user when we can use jinja2 -
Pandas df column values = NaN, Django (django-pandas)
I'm using django pandas(https://github.com/chrisdev/django-pandas/), to grab data from a django model into a pandas dataframe. I first create a df with the indexes, and then try to add columns to it. My function: def market_value(self, ticker_list): date_yesterday = date.today() - timedelta(days=1) date_today = date.today() market_value_list = [] first_ticker = ticker_list[0] first_data = Ticker_historic_prices.objects.filter(ticker=first_ticker) first_df = read_frame(first_data, fieldnames=['close']) df_date = read_frame(first_data, fieldnames=['date']) df = pd.DataFrame(index=df_date['date']) for ticker in ticker_list: modelToDf = Ticker_historic_prices.objects.filter(ticker=ticker) df[ticker] = read_frame(modelToDf, fieldnames=['close']) print(df) But my output looks like this: YAR.OL NHY.OL TSLA MSFT STB.OL DNB.OL SBO.OL date 2004-03-24 NaN NaN NaN NaN NaN NaN NaN 2004-03-25 NaN NaN NaN NaN NaN NaN NaN 2004-03-26 NaN NaN NaN NaN NaN NaN NaN 2004-03-29 NaN NaN NaN NaN NaN NaN NaN 2004-03-30 NaN NaN NaN NaN NaN NaN NaN ... ... ... ... ... ... ... ... 2020-07-15 NaN NaN NaN NaN NaN NaN NaN 2020-07-16 NaN NaN NaN NaN NaN NaN NaN 2020-07-17 NaN NaN NaN NaN NaN NaN NaN 2020-07-21 NaN NaN NaN NaN NaN NaN NaN 2020-07-22 NaN NaN NaN NaN NaN NaN NaN The date part is correct, but why do I get NaN values? I have tested, by running the first_df I do get … -
Django QuerySet aggregate based on field value
My model is as follows: class AssetIdentifications(models.Model): id = models.BigIntegerField(primary_key=True, db_index=True, editable=False, null=False) entity = models.ForeignKey( "Entity", db_constraint=False, null=False, ) asset = models.ForeignKey( "Asset", db_constraint=False, null=False ) type = models.CharField( max_length=32, null=False, ) vendor = models.CharField( max_length=64, null=False ) software = models.CharField( max_length=64, null=False ) version = models.CharField( max_length=64, null=False ) I want to get a queryset that is grouped based on unique values of vendor. The result should look something like this: {"vendor1": [\<list of AssetIdentifications\>], "vendor2": [\<list of AssetIdentifications\>] ...} Is this possible with a group_by or aggregate function (I haven't found something like this in the docs)? Or would I have to iterate through the queryset I obtain just through filtering like AssetIdentifications.objects.filter(entity=e) -
Django: Updating through a post() method a CBV object with FormMixin and ListView
I'm trying to update an specific value of the objects shown trough the ListView. I found a possible solution using FormMixin, but when the input is done using the <select> tag, instead of updating the object value trough the form, a new object is created. models.py: class Quote(models.Model): STATUS = ( ('E', 'Entregada'), ('R', 'Revaluada'), ('C', 'Confirmada'), ('A', 'Anulada'), ) client_name = models.CharField(max_length=40) client_last_name = models.CharField(max_length=40) status = models.CharField(max_length=1, default='', choices=STATUS, blank=True, null=True) forms.py: class QuoteChangeStatusForm(forms.ModelForm): class Meta: model = Quote fields = ['status'] widgets = { 'status': forms.Select( attrs = { 'class': 'form-control-sm', 'onChange':'this.form.submit();' } ) } views.py: class QuoteListView(FormMixin, ListView): model = Quote template_name = 'quoter/quote_list.html' form_class = QuoteChangeStatusForm success_url = reverse_lazy('quoter:quote-list') context_object_name = 'quotes' queryset = Quote.objects.all() def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): form.save(commit=True) return self.form_valid(form, **kwargs) else: return self.form_invalid(form, **kwargs) quote_list.html: <form method="POST"> {% csrf_token %} <h5>Status: <br>{{ form.status }}</h5> </form> Thanks in advance! -
In the Django Admin, the ManyToMany second box doesn't appear for some of my models. How can I display it back?
I'm making an app with Django 3.0.8 and I'm customizing the Django admin panel in order to make it more user-friendly for the administrators. But the problem is that some (almost all) of my ManyToMany fields in my models are not displaying correctly. Usually, you should have to boxes. On on the left (or above if your screen isn't large enough) where you can select the related objects, and one on the right (or bellow) of the first one, containing the objects already selected. You can use the arrows between to boxes to add or remove one or more objects from one box to the other. The problem is that in my case, the right/bottom box and the arrows disappeared. i cannot see which objects are related to my current object and therefore I cannot remove some of them from the relationship, which is problematic. I post this because I already had this with a couples of Django apps. -
Is there any way to get reversed nested serializers in django rest framework?
Suppose i have two models: class Region(models.Model): region_name = models.CharField( max_length=50, null=False, blank=False, unique=True, verbose_name="Region Name" ) def __str__(self): return self.region_name class Meta: verbose_name_plural = "Regions" class Country(models.Model): region_id = models.ForeignKey( Region, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Region id", ) country_name = models.CharField( max_length=50, unique=True, null=False, blank=False, verbose_name="Country Name" ) def __str__(self): return self.country_name class Meta: verbose_name_plural = "Countries" Now, when i access the country model through Djnago REST Framework, as /api/countries I get country_name and region_id for example [ { "id": 1, "country_name":"Taiwan", "region_id": 1 }, ... ... ] Is there any way to get the result like: [ { "id": 1, "country_name":"Taiwan", "region_id": { id: 1, region_name: "Asia", } }, ... ... ] I have tried nested serializer example as on the DRF website, but it returns a list of countries if we get the regions api. like: [ { "id": 1, "region_name":"Asia", "countries": [ "Taiwan", "Japan", "Vietnam", ... ] }, ... ... ] I need to know the region name of the country in one api get request. Right now i am using 2 requests. One to get country, and then get region name from region id. -
mysql client not installed
i want install "mysql client" package but i have error. the error is : Defaulting to user installation because normal site-packages is not writeable Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\program files (x86)\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\HaMiD\\AppData\\Local\\Temp\\pip-install-c4vd2bfk\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\HaMiD\\AppData\\Local\\Temp\\pip-install-c4vd2bfk\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\HaMiD\AppData\Local\Temp\pip-record-3c2b32j1\install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:\Users\HaMiD\AppData\Roaming\Python\Python38\Include\mysqlclient' cwd: C:\Users\HaMiD\AppData\Local\Temp\pip-install-c4vd2bfk\mysqlclient\ Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.23.28105\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(2,0,1,'final',0) -D__version__=2.0.1 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Ic:\program files (x86)\python38-32\include" "-Ic:\program files (x86)\python38-32\include" "-IC:\Program … -
ImportError at / Module "cart.context" does not define a "cart_context" attribute/class
Im trying to create a django cart page. im having an issue adding products/plans to a cart and im also having an issue on showing a quantity of items in the cart. Ive made a context.py to try add to the cart but im not too sure what im doing wrong. im getting an error message ImportError at / Module "cart.context" does not define a "cart_context" attribute/class Heres my context.py file from django.shortcuts import get_object_or_404 from plans.models import Plans def cart_contents(request): """ Enables the cart contents to be shown when rendering any page on the site. """ cart = request.session.get('cart', {}) cart_items = [] total = 0 product_count = 0 for (id, quantity) in cart.items(): product = get_object_or_404(Product, pk=id) total += quantity * product.price product_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'product': product}) return {'cart_items': cart_items, 'total': total, 'product_count': product_count} Heres my cart views from django.shortcuts import render, redirect, reverse # Create your views here. def view_cart(request): """ A view that renders the cart page """ return render(request, 'cart/cart.html') def add_to_cart(request, item_id): """ Add plan to shopping cart """ cart = request.session.get('cart', {}) cart[item_id] = cart.get(item_id, 1) request.session['cart'] = cart return redirect(reverse('plans')) Add here is my navbar cart link, where … -
how to pass instance post image in email template in django?
i need to send post update through email to the users with the instance post image, but i dont know how to pass the instance post image to the email template. signals.py def sendUpdateMail(sender,created,instance,**kwargs): if created: if instance.status == 'Published': subject=instance.postTitle message=Truncator(instance.postContent).words(30) from_email=settings.EMAIL_HOST_USER email=list(NewsletterUser.objects.values('email')) d={'postContent':instance.postContent,'title':subject} recepients=[] html_templatey=get_template("blog/postUpdateMail.html").render(d) #recepients=[p.email for p in NewsletterUser.objects.all()] for p in NewsletterUser.objects.all(): recepients.append(p.email) email=EmailMultiAlternatives(subject,'',from_email,recepients) email.attach_alternative(html_templatey,'text/html') email.send() -
How can i accept and run user's code securely on my web app?
I am working on a django based web app that takes python file as input which contains some function, then in backend i have some lists that are passed as parameters through the user's function,which will generate a single value output.The result generated will be used for some further computation. Here is how the function inside the user's file look like : def somefunctionname(list): ''' some computation performed on list'''' return float value At present the approach that i am using is taking user's file as normal file input. Then in my views.py i am executing the file as module and passing the parameters with eval function. Snippet is given below. Here modulename is the python file name that i had taken from user and importing as module exec("import "+modulename) result = eval(f"{modulename}.{somefunctionname}(arguments)") Which is working absolutely fine. But i know this is not the secured approach. My question , Is there any other way through which i can run users file securely as the method that i am using is not secure ? I know the proposed solutions can't be full proof but what are the other ways in which i can run this (like if it can be … -
post save user is inactive based on assigned user_group - Django Allauth
I have two different user groups group_a and group_b. On register a user can choose the group he/she belongs to. I am using Django Allauth to handle all the user stuff so I've made a custom account adapter to handle the extra logic: custom_adapter.py class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False) user.voornaam = form.cleaned_data.get('first_name') user.achternaam = form.cleaned_data.get('last_name') user.user_group = form.cleaned_data.get('user_group') user.save() user.groups.add(user.user_group) user.save() if user.groups == 'group_b': user.is_active = False else: user.is_active = True user.save() return user On register the user gets assigned to the group it selects as intended. Afterwards I want to assign user.is_active = False to the people who select group_b. In the above example I am using 3 save methods (I think this is way to much under DRY principle) but I tried every possible combination. When I am printing out the user.groups it is set to None after every save method in the above example. But it still gets assigned the right way when i look in the admin panel. What is the best method to tackle this? -
Database config for Django testing
I am building an app with Django and Postgres. I managed to do migrations and I want to test it. When I test with sqlite everything works fine, but when I run tests with postgres I'm getting this error: Creating test database for alias 'default'... Got an error creating the test database: permission denied to create database I've checked user's permissions and I'm sure that this user have permission to create database. My database config looks like this: # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } # } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': '****', 'PORT': '****', } } My postgres db is on a server. My questions are: What is the right way to config my db and run tests? Should I be using sqlite for testing? If so how my code should look like, so I don't have to comment configs? -
403 CSRF verification failed. Request aborted
I had practice many instructions in this case, but find no improvement. when I want to submit the value inside the input tag, page pops up with 403 CSRF verification failed. Request aborted.. would you please tell me whats wrong here is my part of my code: views.py class ODMS2FixEndView(TemplateView): template_name = 'ODMS2FixEnd.html' def get(self, request): form = HomeForm() return render(request, self.template_name, {'form': form}) @csrf_exempt def post(self,request): if request.method == 'post': form = HomeForm() if form.is_valid(): print("YESSSS") form.update(csrf(request)) text = request.form['post'] print(text) print(form) args = {'form': form, 'text': text} return HttpResponseRedirect('/success/') else: print("NOOOO") return render (request, self.template_name, context=form) ODMS2FixEnd.html <!DOCTYPE html> {% extends 'base.html' %} <meta name="csrf_token" content="{{ csrf_token }}"> .... <div id="forID" class="container"> <form method="post" id="form1ID" action="">{% csrf_token %} <input type="text" id="OUtPUTCal"> <button type="submit"> Calculate</button> </form> <h2>{{ text }}</h2> </div> <script> ..... document.getElementById("OUtPUTCal").value=TEXT4; } ...... </script> urls.py urlpatterns = [ .... url(r'^myprojects/ODMS2FixEnd', TemplateView.as_view(template_name = 'ODMS2FixEnd.html'), name='ODMS2FixEnd'), .... form.py from django import forms class HomeForm(forms.Form): post = forms.CharField()