Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF cookie + ReactJS axios post request
HI I've been stuck on this axios post request for couple days. I'm trying to send a post request to the REST API so that it could create a new data entry in the backend. After I sent the post request using axios along with XSRF token and CSRF token, I always got "OPTIONS /endpointURL HTTP/1.1" 200 0" instead of the actual post request Here's my code for the axios post request import axios from '../helpers/axios'; axios({ method: "post", url: "http://endpointurl", withCredentials: true, headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': localStorage.getItem('xsrftoken'), 'csrftoken': localStorage.getItem('csrftoken') // 'XSRF-TOKEN': localStorage.getItem('userToken') }, data: { name: this.state.name, } }).then(res => { console.log(res); console.log(res.data); }) I also tried to send a wrong token along with the post request, I would still get "OPTIONS ..." if i remove withCredentials: true from the code, i would get Forbidden (CSRF cookie not set.) ../helpers/axios import axios from 'axios' /** * Config global for axios/django */ axios.defaults.xsrfHeaderName = "X-CSRFToken" axios.defaults.xsrfCookieName = 'csrftoken' export default axios And this is how I got the tokens // using jQuery function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) … -
Django NoReverseMatch error for Tutorial Part 3
Hi I've been trying to figure out why I keep getting the NoReverseMatch error in my program but can't seem to figure out why. I doubled checked that my question.id was correct and checked the urls.py to also make sure that there was nothing wrong but I keep getting the error when I add the {% url %}. I have also been through almost all of the other stackoverflow posts and have still not been able to figure out the issue. Any help is much appreciated! Index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question_id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} Polls/urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url('', views.index, name='index'), url('<int:question_id>', views.detail, name='detail'), url('<int:question_id>/results/', views.results, name='results'), url('<int:question_id>/vote/', views.vote, name='vote'), url('specifics/<int:question_id>/', views.detail, name='detail'), ] -
How to get the selected items in jstree and pass the result to my django view?
I have a django UpdateView to update a form that has a jstree and I had to create an api with django-rest-framework to use with jstree for a nested item but now I don't know how to get the values from jstree in my template to pass back to form_valid to save it. this is my django view before the jstree class ResearcherInfoUpdateView(LoginRequiredMixin, UpdateView): model = Researcher form_class = ResearcherInfoForm success_url = reverse_lazy('accounts:dashboard') def form_valid(self, form): researcher = Researcher.objects.get(email=form.cleaned_data['email']) items = [] if researcher.experience.all().count() >= 1: for new_item in form.cleaned_data['knowledge_areas']: area = CNPQ.objects.get(id=new_item.id) items.append(area.id) if not researcher.experience.filter(predominant_area_id=area.id): experience = ExperienceTime.objects.create(predominant_area=area) researcher.experience.add(experience) for item in researcher.experience.all(): if item.predominant_area_id not in items: researcher.experience.filter(predominant_area_id=item.predominant_area_id).delete() else: for new_item in form.cleaned_data['knowledge_areas']: area = CNPQ.objects.get(id=new_item.id) experience = ExperienceTime.objects.create(predominant_area=area) researcher.experience.add(experience) self.object = form.save() return super(ResearcherInfoUpdateView, self).form_valid(form) my serializer class ApplicationAreaSerializer(serializers.ModelSerializer): class Meta: model = models.ApplicationArea fields = ('id','parent', 'text') My template {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <div class="row"> <div class="card"> <div class="card-body"> <h2 class="text-center card-title">Informações Gerais</h2> <form method="post" enctype="multipart/form-data" novalidate> {% csrf_token %} {{form|crispy}} <input type="search" id="search_tree" class="form-control" value="" required="required" title=""> <div id="tree"></div> <input class="btn btn-primary btn-block" type="submit" value="Update" /> </form> </div> </div> </div> </div> <script> var application_area … -
Delete header in django rest framework response
I'm trying to delete Server header from django rest framework response, but I didn't find an easy way, so I create a middleware to delete it. This is my first try: middleware.py class RemoveHeaders(object): def process_response(self, request, response): response['Server'] = '' return response This middleware works ok, but the problem is that it fills server header with empty string and not delete it. so I tried the next: class RemoveHeaders(object): def process_response(self, request, response): del response['Server'] return response But It doesn't work. server header continues. How can I delete server header?, or do you know another alternative? thanks -
Storing additional information in django using absrtactuser
I have created custom Userclass in django(AbstarctUser). Everything works fine but my password is getting stored as plain text in database even after registering in admin.py. I do not have any forms.py explicitly defined. Also I am using nested serializers following "https://medium.freecodecamp.org/nested-relationships-in-serializers-for-onetoone-fields-in-django-rest-framework-bdb4720d81e6" tutorials My code is as below from django.contrib import admin from .models import BasicUserInfo from django.contrib.auth.admin import UserAdmin class BasicUserAdmin(UserAdmin): pass admin.site.register(BasicUserInfo, BasicUserAdmin) -
CurrentSiteManager via related model
Is it possible to use the CurrentSiteManager to check the site of a related object - not the site of the object itself? So, given the following models:- class A(models.Model): site = models.ForeignKey(Site) class B(models.Model): a = models.ForeignKey(A) I want to use the following manager on B:- on_site = CurrentSiteManager('a__site') Otherwise, I'll have to add site as a ForeignKey to both A and B and manage all the issues that come with that. But it looks like the CurrentSiteManager wants the 'site' field to be on the B class, not on A. Is my only solution to write my own CurrentSiteManager? -
Django Field defines a relation with model , which is either not installed, or is abstract
My code is as shown below: class X(models.Model): class Meta: db_table = 'X' ph_no = models.CharField(max_length =255,null=False) y = models.ForeignKey('y',on_delete=models.CASCADE) class M(models.Model): class Meta: db_table = 'M' comment = models.CharField(max_length=255,null= False) x = models.ForeignKey('X',on_delete=models.CASCADE) Now when , with this schema, I run the migrations, I get the following error appName.M.x: (fields.E300) Field defines a relation with model 'x', which is either not installed, or is abstract. appName.M.x: (fields.E307) The field appName.M.x was declared with a lazy reference to 'appName.x', but app 'appName' doesn't provide model 'x'. -
Run Celery in production with Supervisor
I am trying to launch Celery v3.1.25 in production. As I have found in docs there are 4 ways to run it, 1 of them is to use Supervisor. I have used it before - my Django project is running using it. I made following steps: 1. Created /etc/supervisor/conf.d/mycelery.conf on the basics of official git repo. [program:mycelery] command=celery worker -A cosmetics_crawler_project --loglevel=INFO directory=/home/chiefir/polo/Cosmo user=chiefir numprocs=1 stdout_logfile=/home/chiefir/logs/celery/celery.log stderr_logfile=/home/chiefir/logs/celery/celery.log autostart=true autorestart=true startsecs=10 stopasgroup=true priority=1000 2. Created /etc/supervisor/conf.d/mycelerybeat.conf: [program:mycelerybeat] command=celery beat -A cosmetics_crawler_project --schedule /var/lib/celery/beat.db --loglevel=INFO directory=/home/chiefir/polo/Cosmo user=chiefir numprocs=1 stdout_logfile=/home/chiefir/logs/celery/celerybeat.log stderr_logfile=/home/chiefir/logs/celery/celerybeat.log autostart=true autorestart=true startsecs=10 stopasgroup=true priority=999 3. And my /etc/supervisord.conf is set to: [unix_http_server] file=/var/run/supervisor.sock ; (the path to the socket file) chmod=0700 ; sockef file mode (default 0700) [supervisord] logfile=/var/log/supervisor/supervisord.log ; (main log file;default $CWD/supervisord.log) pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) childlogdir=/var/log/supervisor ; ('AUTO' child log dir, default $TEMP) [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket [include] files = /etc/supervisor/conf.d/*.conf I have found in this question that I have to run supervisord to fire the Celery, but it throws error: Traceback (most recent call last): File "/usr/bin/supervisord", line 9, in <module> load_entry_point('supervisor==3.2.0', 'console_scripts', 'supervisord')() File "/usr/lib/python2.7/dist-packages/supervisor/supervisord.py", line 367, in main go(options) File "/usr/lib/python2.7/dist-packages/supervisor/supervisord.py", line 377, … -
go back to previous page in django
I want to save the data in the form and go back to previous page when i click on 'Add' button. Its showing some errors. Can anyone suggest the correct way to do it ? template.html <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Add your own Category </h3> </div> <div class="panel-body"> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} </div> </div> </div> <input type="hidden" name="next" value="{{ request.path }}"> <button type="submit" class="save btn btn-default" >Add</button> </form> views.py class CustomCategory(LoginRequiredMixin,CreateView): model = Category form_class = CategoryForm def form_valid(self, form): obj = form.save(commit=False) def category(request): next = request.POST.get('next', '/') return render (request,HttpResponseRedirect(next)) -
python django how to send parameters to website in Post request
I am working on building a website with python Django. I want to do the following project. First, I get the input values from the website. Then I use the input values to produce a plot and save it in one place of the server. After that, I want to send the location of the plot back to the website. My codes are given below In views.py First define to Django form.Forms form_class = trip.forms.AdHocTripReportRequestForm graphurl_form=trip.forms.Graphurl Then define a "get" function def get(self, request): encoded_cabinets, id_dirserved = self._encoded_page_precache() ctx = { 'CABINETS': encoded_cabinets, 'ID_DIRSERVED': id_dirserved, 'form': self.form_class(), 'graph': self.graphurl_form(), } # add adhoc settings profile = get_profile(request.user) if profile: ctx.update(defaults=profile.get_settings('adhoctrip')) context = RequestContext(request, ctx) return render_to_response("adhoc-trip.html", context) after that, there is a post function def post(self, request): #1) read the input values form = self.form_class(request.POST) if form.is_valid(request.user): # update adhoc settings profile = get_profile(request.user) if profile: settings_form = DateRangeDowEmailForm(request.POST) if settings_form.is_valid(): profile.set_settings('adhoctrip', settings_form.cleaned_data) profile.save() # 2) some functions to get the link string graphurl=trip.tasks.TripReportTask().delay(trr, recipients, server, save_as, trr1) # 3) set this information to the html file graphurl_form_tmp=trip.forms.Graphurl(request.POST or None, initial={'name': graphurl}) CC return render(request, "adhoc-trip.html", {'graph' : graphurl_form_tmp,}) However, once I add the last line (return render ...) into … -
`The model Block is already registered` error when tried to refine the admin site
I registered a data model Block I had defined admin.site.register(Block) Additionally, I intend to make the admin site more readable: class BlockAdmin(admin.ModelAdmin): list_display = ('name', 'desc', 'admin') admin.site.register(Block, BlockAdmin) Unfortunately, encounters the error: raise AlreadyRegistered('The model %s is already registered' % model.__name__) django.contrib.admin.sites.AlreadyRegistered: The model Block is already registered How to revert the previous registration and implement the current? -
Python Django Connection and php
(venv) C:\inetpub\wwwroot\BugTracker>pip install mysqlclient Requirement already satisfied: mysqlclient in c:\program files\python36\lib\site-packages (1.3.12) Ive Installed: MySQL version 8.0, Django (2.0.5), python 3.6.5, mysql-connector-python (8.0.11), pip(10.0.1), protobuf (3.5.2.post1), pytz (2018.4), setuptools(39.0.1), six(1.11.0), xlwt(1.3.0)...... This is what comes when i try to install Mysql-server. (venv) C:\inetpub\wwwroot\BugTracker>pip install mysql-server Collecting mysql-server Could not find a version that satisfies the requirement mysql-server (from versions: ) No matching distribution found for mysql-server (venv) C:\inetpub\wwwroot\BugTracker> When i Installed MySQL 8, It came with the mysqlclient, mysqlserver and the workbench and a few other things. For some reason, i cant seem to connect django with mysql... Another thing that I cant get access to is my phpmyadmin at my localhost. When i entered my ID and password back when i had mysql 5.5, it worked fine but i couldnt install most of the things for my django because it said some sort of a version mismatch error (well, thats what i thought it was) but now that i've updated my MySQL, when i try to run my phpmyadmin, it loads but the password and ID is incorrect and it throws an error.. I've put up the phpmyadmin using IIS. Any idea whats up? I cant even seem to … -
python3 django psql storing bitcoin in db
Im creating a web app that uses api (json) to download bitcoin info and stores it in postgresql database. I know that there are some problems with calculations on floats. What type of data would you suggest for storing bitcoin values? Meaby converting it into satoshis? Or just storing floats and avoiding calculations on them? -
Uploading a file in django database in a specific root with diferrent folders everytime
I´m trying to upload file into database, but when i want put the function uoload to and i want to that function store the file in a root with the data the user submit in the for, for example year, course, section, I get that information and the file they uploaded I want to store in that subfolders, the code that I´m using only store the data in the Media_root, but not in the carpets how can I do in order to store the files in the subfolder I want. I'n my model document I store the information of the document, like the autor, the title,etc. class File(models.Model): titulo_file=models.ForeignKey(Document,on_delete=models.CASCADE,null=True,verbose_ name='Título de la Tesis') file = models.FileField(null=True,blank=True, upload_to=generate_path) Here the function I use to upload the file, Int only works to store the file into a folder with it´s same name. def generate_path(instance, filename): path =os.path.join(instance.file.name,filename) return path In my view, after the user submit the information, I use a os.path.join, that do the path with the information submited like this: year/course/section I want to send that path to my generate_path and store in that location the file, I tried with session but it doesn't work, what can I do? -
Implement Github API in Python
I'm working on a project using Python(3.6) in which I need to implement GitHub API. I have tried by using JSON apis as: from views.py: class GhNavigator(CreateView): def get(self, request, *args, **kwargs): term = request.GET.get('search_term') username = 'arycloud' token = 'API_TOKEN' login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token)) print(login) return render(request, 'navigator/template.html', {'login': login}) but it simply returns status 200, I want to get a list of repositories for term which is passed by the user. How can I achieve that? Help me, please! Thanks in advance! -
How to use Django __time lookup in a queryset
I have a model with 2 datetime fields which looks like this: class Booking(models.Model): start_date = models.DateTimeField() end_date = models.DateTimeField() ... As test data I have 2 bookings with start_date before 17:30 and 2 bookings after 17:45, all on the same day (8 May 2018). I am trying to filter the bookings with the __time lookup to find all the bookings before (and including) 17:30. My queryset is: bookings = Booking.objects.filter(date__time__lte=datetime.time()) Where datetime.time prints as datetime.time(17, 30) and where the date part of the datetime is the same as the bookings dates. The above query is returning an empty queryset but if I use the same query except filtering for times greater than datetime.time() i.e. bookings = Booking.objects.filter(date__time__gte=datetime.time()) The queryset returns all the bookings (where it should only return the 2 bookings with start_date after 17:30). Can someone please explain to me how the __time lookup is meant to be used? EDIT I updated the filter to bookings = Booking.objects.filter(start_date__time__lte=datetime.time()) and the result is the same. -
migrate.py: Cannot resolve 'django_db_logger.db_log_handler.DatabaseLogHandler'
so I am trying to migrate manage.py and I encounter this error: ValueError: Unable to configure handler 'db_log': Cannot resolve 'django_db_logger.db_log_handler.DatabaseLogHandler': No module named django_db_logger Here's the whole error log Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\venvi\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\venvi\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\venvi\lib\site-packages\django\__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\venvi\lib\site-packages\django\utils\log.py", line 75, in configure_logging logging_config_func(logging_settings) File "C:\Python27\Lib\logging\config.py", line 794, in dictConfig dictConfigClass(config).configure() File "C:\Python27\Lib\logging\config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'db_log': Cannot resolve 'django_db_logger.db_log_handler.DatabaseLogHandler': No module named django_db_logger Can anyone please tell me how to fix this? Thank you! -
geodjango wrong srid when it saves feature
I tried to read data from a shape file and save them into database. well here is my code lyr = ds[0] for feat in lyr: geom_t = feat.geom.transform(wgs84, clone=True) print(geom_t.wkt) print(feat.geom.wkt) name ='' Twoway='1' data = { 'name': name, 'Twoway': Twoway, 'geom': geom_t.wkb } form = Street_Form(data) if form.is_valid(): savedlocation = form.save() well it saves and works fine. I printed some of my geometries as wkt before saving to databse and here is the result print(geom_t.wkt): LINESTRING (50.9847540637495 35.8384680697353,50.9850968571006 35.8383655346687) print(feat.geom.wkt): LINESTRING (50.9847540637495 35.8384680697353,50.9850968571006 35.8383655346687) As you can see they are EPSG:4326 and nothing is wrong. Here is my model class str(models.Model): geom = models.LineStringField(srid=4326) but when I read data from database they are as following "LINESTRING(0.000457917485762628 0.000321907544087987,0.000457920236524686 0.000321915031075541)" the above result is from this query select st_astext(geom) from public."app_str" well the geometries are misplaced, where is the problem?why this happens? -
Django - Create unique ManyToManyField?
I have been working with Django for a little while now, and I've been reaching barriers in regards to storing data with the framework. I'd like to have a ManyToManyField in which its objects are user-specific. Example: User1 Grades A+ B+ User2 Grades: B B- With my current setup, both users will have: A+,B+,B,B-. I am not sure how to work around this without queries. Course_Grades = models.ManyToManyField(CourseGrade, default=1) Assignment_Grades = models.ManyToManyField(AssignmentGrade, default=1) -
Django Test Wants Access To Master Database MS SQL Server
I've got an application that is running Django 2 that connects to a Microsoft SQL Server backend. We're in a big environment where things are pretty tightly controlled - a user account has access to the database that houses all the tables for my django application. It does not have access to the master database on the SQL Server and any request for an account that does have that level of access would likely be denied. It can create tables in the existing database, but cannot create entirely new databases. When I run the tests for the application I get the error: Got an error creating the test database: ('42000', "[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]CREATE DATABASE permission denied in database 'master'. (262) (SQLExecDirectW)") So what is the best course of action for this? Is there a way to manually create the 'test database' and have Django use that for testing purposes so it isn't trying to create a new database when running tests? -
Proper way of streaming JSON with Django
i have a webservice which gets user requests and produces (multiple) solution(s) to this request. I want to return a solution as soon as possible, and send the remaining solutions when they are ready. In order to do this, I thought about using Django's Http stream response. Unfortunately, I am not sure if this is the most adequate way of doing so, because of the problem I will describe below. I have a Django view, which receives a query and answers with a stream response. This stream returns the data returned by a generator, which is always a python dictionary. The problem is that upon the second return action of the stream, the Json content breaks. If the python dictionary, which serves as a response, is something like {key: val}, after the second yield the returned response is {key: val} {key: val}, which is not valid Json. Any suggestions on how to return multiple Json objects at different moments in time? -
Search engine in javascript and django
Good day, I'm pretty new in django and python and newer still in javascript. And I'm mixing everyone! :( Step to tell you that I'm making a website where a Manager enters the movements performed during a work day, separated into a list that also that list is divided into sublists. On the website you are asked to enter the number of movements made in that workday (sublist), each of these movements correspond to different people who are discriminated against by an AUTOS AND JUDGE EJ: AUTOS: 251254 Court: PAZ 6. In javascript I managed to enter the number of movements you want to load and automatically generate the amount of input and select that I need. At that moment that the manager decided the number of movements that will be entered in that sublist, you must identify the client to whom the operation hosted in my database will be loaded, modeled in django. Then in all the input you must enter the AUTOS number and in a SELECT - OPTION select the COURT to which that car belongs and bring me the name of the client lodged in the data base and the doubt that I have is how … -
Operational Error : unable to open database file
Trying to deploy a Django app over Apache . Installed all dependencies, Apache is running fine , no errors, however when I launch the domain, It gives the error : Operational Error : unable to open database file This is where the database is stored : /home/wger/db/database.sqlite And in order to make sure I have the permissions, I did : chgrp www-data /home/wger/db/ chgrp www-data /home/wger/db/database.sqlite chmod g+w /home/wger/db/ chmod g+w /home/wger/db/database.sqlite chmod 664 /home/wger/db/database.sqlite chmod 664 /home/wger/db sudo chown :www-data /home/wger/db sudo chown :www-data /home/wger/db/database.sqlite sudo service apache2 restart However, the issue still persist. This is my domain, what is possibly causing this and how to effectively resolve this ? PS : I tried existing answers to identical questions, however I was not able to resolve the error! -
CSS file loading but not working in Django project
I am new to Django, I am working in python 3.5, I linked CSS using Jinja but I am not able to see the CSS style within my HTML file, even thought I am getting 200 status in my network and the CSS file is loaded but the style is not working. Can you help me. here is my html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" type="text/css" href="{%static 'posts/customstyle.css'%}"> </head> <body> <div class="container"> <h1>This is the HTML file</h1> </div> </body> and my CSS file is also within 'static' folder within my project folder. I have tried changing the name but nothing is happening. All I get in the console is: Resource interpreted as Stylesheet but transferred with MIME type application/x-CSS. While my network is pretty healthy and I am getting my files uploaded properly. Here is what I am getting in console: file uploads sucessfully style showing but not working -
Django - Showing items that are assigned to current user's email
I am working on a project and I am currently trying to make a dashboard which shows you which "range" you are assigned to based on your email. The email is the primary key for "Student". Basically, I want to request the user's email, and then check if the email matches "studentID" in the table "RangeStudents", and then pull out from the table "Range" where the range ID matches. This is what I have so far, and it returns an error of " 'Query' object has no attribute 'contains_aggregate'." At this point I am really lost, as I searched for a solution for hours. I apologise for the messy code. Any help to solve my problem would be very much appreciated. Models.py: class Student(AbstractBaseUser): Class = ( ('1A/22', 'DISM/FT/1A/22'), ('1A/23', 'DISM/FT/1A/23'), ('1A/01', 'DISM/FT/1A/01'), ) is_staff = False email = models.EmailField(db_column='email', primary_key = True) username = models.CharField(db_column='username', max_length=45, unique=True) password = models.CharField(db_column='password', max_length=100) studentname = models.CharField(db_column='studentName', max_length=100) datejoined = models.DateField(db_column='dateJoined', blank=True, null=True) # Field name made lowercase. lastmodifieddate = models.DateField(db_column='lastModifiedDate', blank=True, null=True) # Field name made lowercase. lastmodifedby = models.ForeignKey(Admin, models.DO_NOTHING, db_column='lastModifedBy', blank=True, null=True, related_name="LMB") # Field name made lowercase. acceptedby = models.ForeignKey(Admin, models.DO_NOTHING, db_column='acceptedBy', related_name="AB", null=True) # Field name made …