Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-puppeteer-pdf static files
I'm having django-puppeteer-pdf installed on my project. Page loads with css and PDF generation works great. But css files on STATIC_ROOT does not work on pdf. Any idea how to get this work? In html template I'm having static files loaded: {% load staticfiles %} ... <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title></title> <link href="{% static 'css/pdf-reports.min.css' %}" rel="stylesheet" /> </head> and settings.py file: STATIC_ROOT = os.path.join(BASE_DIR, "static_files") -
RecordView() missing 1 required positional argument: 'id'
I keep getting this error - RecordView() missing 1 required positional argument: 'id'. I am not able to figure out where I am missing 1 required positional argument. views.py def RecordView(request,id): print ("id :",id) all_investor = Investor.objects.all() total_investment=Investment.objects.filter(investor=id) print("all_investor :",all_investor) print("total_investment :",total_investment) investor_id = Investor.objects.get(id=id) print("investor_id :",investor_id) investor_name = investor_id.name print("investor_name :",investor_name) try: investor_id = request.GET.get('investor_id') investor_id = int(investor_id) investment = Investment.objects.filter(pk=investor_id) except: pass context = { 'all_investor':all_investor, 'total_investment':total_investment, 'investor_name':investor_name } return render(request, 'company/record.html', context) record.html {% if request.user.is_superuser %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Investment Record </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'total' %}">Total Investment</a> {% for investor in all_investor %} <a class="dropdown-item" href="{% url 'records' investor.id %}">{{ investor.name }} {{ investor.id }}</a> {% endfor %} </div> </li> {% endif %} -
Django vs Node(Express) vs Flask for RESTful API with high security and real-time
I have a few questions regarding some popular web frameworks. I can find pros and cons about all the frameworks, but which fits best regarding theese criteria: The website needs to be as secure as possible. It will need a lot of real-time feautures, an own mobile app (native or hybrid, with notifications) and the application will also run a lot of background processes. Django has some nice security features included, but suits bad for mobile development. The solution is then probably making a completely RESTful API tougheter with Angular and Ionic, but doesn't you loose most of Django's built in security solutions? Will it then be just as safe using a Node framework like Express, and manually escape user input, and manually prevent database injection? Will a good user authentication system then be equal as much work? In addition, will it be painful to mix synchronous and asynchronous programing using Django channels to implement websockets and real-time features. I don't have any experience using Django channels, but I really likes the simplicity of Socket IO together with Express. Even if it can be challenging to program asynchronous in a Node environment, will it be just as hard using Django … -
How should a django app handle a post request from a reactjs form
I wrote a views function in my django app for user registration, the code for which is as follows: def register(request): if request.method == 'POST': # data = request.POST.copy() print(request.POST) print(json.dumps(request.POST)) data1 = json.dumps(request.POST) data = json.loads(data1) # data = request.POST.copy() # full_name = data.get('userName') # # print(full_name) # print(data) # # print(request.POST) # #Get form values # full_name = request.POST.get("userName") # print(full_name) # username = request.POST['username'] full_name = data['userName'] company_name = data['agencyName'] phone = data['phoneNumber'] email_id = data['email'] password = data['password'] password2 = data['confirmpassword'] # full_name = request.POST.get('userName') # company_name = request.POST.get("agencyName") # print(company_name) # phone = request.POST.get("phoneNumber") # email_id = request.POST.get("email") # password = request.POST.get("password") # password2 = request.POST.get("confirmpassword") #Check if passwords match if password == password2: #Check username if MyUser.objects.filter(email=email_id).exists(): messages.error(request,'That email is being used') return redirect('register') else: #Looks good user = MyUser.objects.create_user(password=password, email=email_id, full_name=full_name,company_name=company_name,phone=phone) user.save() messages.success(request,'You are now registered') return HttpResponse(json.dumps({'success':'success'}), content_type='application/json') else: messages.error(request,'Passwords donot match') return HttpResponse(json.dumps({'error':'password donot match'}), content_type='application/json') return HttpResponse(json.dumps({'none':'none'}),content_type='application/json') The front-end of the website is made in reactjs and when I try to send a POST request from the react app for registration, it doesn't register's the user. Also when I send a post request from postman to it for user registration … -
how to solve attribute error when 'WSGIRequest' object has no attribute?
enter image description here please solve this problementer image description here -
How do make username and email field validations
I am trying to check if email already exists in the database during signup but with the below code I am not getting it forms.py from django.forms import ModelForm from django import forms from . models import registration_form class signup_form(ModelForm): Password = forms.CharField(widget=forms.PasswordInput()) Confirm_pwd = forms.CharField(widget=forms.PasswordInput()) class Meta: model = registration_form fields=['Firstname','Lastname','Username','Email','Password','Confirm_pwd'] def clean(self): cleaned_data = super(signup_form, self).clean() password = cleaned_data.get("Password") confirm_password = cleaned_data.get("Confirm_pwd") print(confirm_password) if password != confirm_password: print("yes") raise forms.ValidationError( "password and confirm_password does not match" ) def clean_Email(self): Email = self.cleaned_data.get('Email') try: match = registration_form.objects.get(Email=Email) print(match) except registration_form.DoesNotExist: # Unable to find a user, this is fine return Email raise forms.ValidationError('This email address is already in use.') It is throwing an error as MultipleObjectsReturned at /form/ get() returned more than one registration_form -- it returned 10! can anyone help me to achieve this -
How to post messages from Kafka consumer to Django views
I'm new to Django and Kafka. I have requirements to get msg in format below in Kafka Consumer and post its to a View in DRF. Below is my message format and my Post detail view I need to post Kafka msg to. My django View to post message : Msg format send from Kafka Producer from kafka import KafkaProducer import json from bson import json_util post = [] prod = KafkaProducer(bootstrap_servers='localhost:9092') while(True) : title = input("Title :") content = input("Content :") author = input ("Author :") post.append({ "title" : title, "content" : content, "author" : author }) prod.send('hung11898',json.dumps(post, indent=4, default=json_util.default).encode('utf-8')) prod.flush() cont = input("Add another Post ?(Y/N)") if cont == 'N' : break -
django-storages not uploading images, getting NoSuchKey (AWS s3)
I'm having an issue with django-storages. My image urls are being returning by fields, but when going to the url I get NoSuchKey. The odd thing is that when configuring this for static files (see last code block) and doing collectstatic, everything is uploaded fine. django-storages/boto doesn't return any errors. Here's my settings.py: AWS_ACCESS_KEY_ID = "" AWS_SECRET_ACCESS_KEY = "" AWS_STORAGE_BUCKET_NAME = "" AWS_BUCKET_ACL = "public-read" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_QUERYSTRING_AUTH = False AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) AWS_LOCATION = 'media' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) AWS_DEFAULT_ACL = "public-read" The view: @login_required def addface(request, personid): person = models.Person.objects.get(pk=personid) form = FaceForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): try: # this prints the url that returns the error print(form.instance.image.url) # some processing, ignore this faces = Person(person.name, person.personid, "1").detect( form.instance.image.url) # Should only be one face per image if len(faces) != 1: messages.add_message(request, messages.ERROR, "More than one face detected!") # Break out of loop, go straight to render raise SystemExit faces[0].add() form.save(commit=False) form.instance.person = person form.instance.faceid = faces[0].faceid form.save() except Exception as e: if e is not SystemExit: messages.add_message(request, messages.ERROR, ERR) raise e else: form = FaceForm() return render(request, "findapp/addface.html", {"form": … -
How to open file in django
I'm trying to open a file that is in the same directory as the app from views. -app --views.py --about.txt --... My code to open the file is.. def home(request): with open('about.txt','r') as f: about = f about = about.split('\n') about = '<br/>'.join(about) return render(request, 'business/home.html')# {'about':about}) But I keep getting an error of ` FileNotFoundError at / [Errno 2] No such file or directory: 'about.txt' After thinking about this, I thought of putting it in a static dir but it would still give the same error. I am still quite a beginner at django. Django 2.2.3 Python 3.7.3 -
Which server side framework should I prefer for scalability
I have worked previously on PHP and Django and right now doing JSP as part of my course. My instructor told me that JSP is preferred over other frameworks due to it's scalability, and even most of the banks, colleges and government institutes use JSP. But I have often seen their servers crashing, so I am a bit confused about it's scalability. I searched internet on comparison but none talked about scalability. Can you guys please help me remove my confusion about how scalable JSP is? -
sending mail with attachment but the attachment is not send only the body is sent
I'm sending a mail with pdf attached in my application but at the receiver end can receive only the body not the attachment This is the error I received while running the script but the mail is sent Traceback (most recent call last): File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 799, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 141, in run self.handle_error() File "C:\Result Creater\virtual\lib\site-packages\django\core\servers\basehttp.py", line 116, in handle_error super().handle_error() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 368, in handle_error self.finish_response() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 331, in send_headers if not self.origin_server or self.client_is_modern(): File "C:\Users\vineet\AppData\Local\Programs\Python\Python37\lib\wsgiref\handlers.py", line 344, in client_is_modern return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' TypeError: 'NoneType' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most … -
Django-autocomplete-light JS events and handlers
I'm trying to add handler on click by "No results found" in django autocomplete light. I'm trying to achieve that via $('.select2-results__message').click(function() { alert( "Handler for .click() called." ); }); However there is no element with class select2-results__message after page is ready, it initializes after filtering. How can i change message "No results found" and add handler on click by that item? -
Django-storage + S3, certain images retun erorr 403
I am having an issue with django-storages returning error 403. Only certain images trigger these though. From what I've tested, all photos taken on iPhone's (perhaps due to their large filesize? I've also transferred them to my pc and then uploaded- same thing) return a 403. Here is an example from an iPhone. Also, this is a random stock photo that errors out too. Anyway, this is my relevant settings.py (note: I only want to upload images): AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'media' MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') AWS_DEFAULT_ACL = "public-read" The model: class Face(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE) image = models.ImageField() faceid = models.TextField() The HTML form: <form enctype="multipart/form-data" action="" method="post"> {% csrf_token %} <input type="file" multiple name="image"> <button type="submit" class="px-4 py-4 rounded bg-gray-300 text-gray-600 hover:shadow">Add files </button> </form> @login_required def addface(request, personid): person = models.Person.objects.get(pk=personid) form = FaceForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): try: # some processing here .... # .... # This prints a URL print(form.instance.image.url) form.save(commit=False) form.instance.person = person // … -
Django multiple signals with one receiver
I'm trying to add a post_save and a post_delete signal to a receiver. However, I am getting an error that says: TypeError: change_followers() missing 1 required positional argument: 'created' @receiver([post_save, post_delete], sender=Following) def change_followers(instance, created, **kwargs): if created: instance.follower.following_count += 1 instance.target.follower_count +=1 instance.save() else: instance.follower.following_count -= 1 instance.target.follower_count -=1 instance.save() Why am I getting this error and how can I fix it? -
How to Group dictionary values in python
I have the following dictionary #BEFORE data={ 'cell_1':['13a'], 'jam_1': ['07-08'], 'model_1': ['SUPERSTAR'], output_1':['10'],'output_jam_1': [''], 'time_1': [''], 'output_ot_1': [''], 'time_ot_1': [''], 'cell_2':['13a'], 'jam_2': ['07-08'],'model_2':'SUPERSTAR'], 'output_2': ['20'], 'output_jam_2': [''], 'time_2': [''], 'output_ot_2': [''], 'time_ot_2': [''], 'cell_3':['13c'], 'jam_3': ['07-08'], 'model_3': ['SUPERSTAR'], 'output_3': ['40'], 'output_jam_3': [''], 'time_3': [''], 'output_ot_3': [''], 'time_ot_3': [''], 'cell_4':['13b'], 'jam_4': ['08-09'], 'model_4': ['SUPERSTAR'], 'output_4': ['30'],'output_jam_4': [''], 'time_4': [''], 'output_ot_4': [''], 'time_ot_4': [''], 'cell_5':['13d'], 'jam_5': ['16-17'], 'model_5': ['SUPERSTAR'], 'output_5': ['40'], 'output_jam_5': [''], 'time_5': [''], 'output_ot_5': [''], 'time_ot_5': [''], 'cell_6':['13d'], 'jam_6': ['16-17'], 'model_6': 'SUPERSTAR'], 'output_6': ['40'], 'output_jam_6': [''], 'time_6': [''], 'output_ot_6': [''], 'time_ot_6': [''], 'cell_7':['13d'], 'jam_7': ['17-18'], 'model_7': ['SUPERSTAR'], 'output_7': ['10'], 'output_jam_7': [''], 'time_7': [''], 'output_ot_7': [''], 'time_ot_7': [''], 'cell_8':['13d'], 'jam_8': ['18-19'], 'model_8': ['SUPERSTAR'], 'output_8': ['60'], 'output_jam_8': [''], 'time_8': [''], 'output_ot_8': [''], 'time_ot_8': [''], } #AFTER data={ 'cell_1':['13a'], 'jam_1': ['07-08'], 'model_1': ['SUPERSTAR'],'output_1': ['10'], 'output_jam_1': ['30'], 'time_1': ['0.33'], 'output_ot_1': [''], 'time_ot_1':[''], 'cell_2':['13a'], 'jam_2': ['07-08'], 'model_2': ['SUPERSTAR'], 'output_2': ['20'], 'output_jam_2': ['30'],'time_2': ['0.67'], 'output_ot_2': [''], 'time_ot_2':[''], 'cell_3':['13c'], 'jam_3': ['07-08'], 'model_3': ['SUPERSTAR'], 'output_3': ['40'], 'output_jam_3': ['40'], 'time_3': ['1'], 'output_ot_3': [''], 'time_ot_3':[''], 'cell_4':['13b'], 'jam_4': ['08-09'], 'model_4': ['SUPERSTAR'], 'output_4': ['30'], 'output_jam_4': ['30'], 'time_4': ['1'], 'output_ot_4': [''], 'time_ot_4':[''], 'cell_5':['13d'], 'jam_5': ['16-17'], 'model_5': ['SUPERSTAR'], 'output_5': ['40'], 'output_jam_5': [''], 'time_5': [''], 'output_ot_5': ['80'], 'time_ot_5':['0.5'], 'cell_6':['13d'], 'jam_6': ['16-17'], 'model_6': ['SUPERSTAR'], 'output_6': ['40'], … -
Django/Vue/Nuxt confusion: Why can't I register an account twice in the same "session"? (403 forbidden error)
Of course I can't, I'm not supposed to, but why/how is Django preventing me from doing that? I'm using Django with all-auth, rest-framework and rest-auth. The Django API lives at http://localhost:8000. My Vue/Nuxt.js app lives at http://localhost:8000. So I've coded up a registration form that passes username, password1, password2 and email to the registration endpoint at localhost:8000/api/accounts/auth/registration. What I haven't done is set any logic for logging-in or out, nor am I saving anything after that. The frontend app does nothing with the token returned by the Django API. So how come when I then try to register again, I keep getting a Forbidden error: HTTP POST /api/accounts/auth/registration/ 403 [0.01, 127.0.0.1:51661] But when I close the browser/open an incognito tab, and try the form again - the form works? I'm assuming it has something (or everything) to do with Django sessions, but how is that working behind the scenes? I mean all I'm getting is a string (the token) and I'm not doing anything with that. When that get cleared up I will hopefully know what my steps are, but just to be sure: would I want to disable Session authentication in my Django app? (it's strictly an API backend) -
How to upload image to db in django instead of static folder
I would like to deploy an image to my page using Django, still in a debig mode. I created a model for the image along some other fields, and all the information is migrated to the database except the image which is storaged in the directory folder for /media/. How can i upload this image to the db and deploy it from there? class Products(models.Model): title = models.CharField(max_length=30) image = models.ImageField(blank=True, null=True) def __str__(self): return self.title -
How to make multiple api calls with python requests
I am trying to make parallel calls to external apis from django using requests or any other library that allows me to do this. I have already tried using grequests to make this calls, sometimes it works but most times I get 'NoneType' object has no attribute 'json' error on the client side. Here are my codes views.py def get_fixtures(request, league_id): league_id = league_id urls = [ "https://api-football-v1.p.rapidapi.com/v2/fixtures/league/%d" % league_id, "https://api-football-v1.p.rapidapi.com/v2/leagues/league/%d" % league_id ] headers = {'X-RapidAPI-Host': "api-football-v1.p.rapidapi.com", 'X-RapidAPI-Key': X_RapidAPI_Key} resp = (grequests.get(u, headers=headers) for u in urls) responses = grequests.map(resp) a = responses[0].json() b = responses[1].json() fix_1 = a['api']['fixtures'] api_2 = b['api']['leagues'] context = { 'fix_1': fix_1, 'api_2': api_2, } return render(request, "pages/fixtures.html", context) On the server side i get this error: File "src\gevent\_greenlet_primitives.py", line 60, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src\gevent\_greenlet_primitives.py", line 64, in gevent.__greenlet_primitives.SwitchOutGreenletWithLoop.switch File "src\gevent\__greenlet_primitives.pxd", line 35, in gevent.__greenlet_primitives._greenlet_switch greenlet.error: cannot switch to a different thread. Can I use requests or any other library to perform the calls without getting these errors? if yes how do i implement it in my work? -
Gunicorn is not seeing new settings
I updated one environment variable inside settings.py and restarted gunicorn, but it is seeing the old settings. Here is the command I use to start it: nohup /opt/my_proj/.virtualenvs/my_proj/bin/python2 /opt/my_proj/.virtualenvs/my_proj/bin/gunicorn --bind=0.0.0.0:8008 --timeout=1800 --log-level=debug --error-logfile=/opt/my_proj/gunicorn_nik.log --enable-stdio-inheritance --capture-output --user=me --pythonpath=/opt/me/code/my_proj,/opt/me/code/my_proj/seqr_settings wsgi & I printed out paths to make sure that the scripts are running under my 'my_proj' directory and also looked up in 'gunicorn_nik.log' verifying that there I see it pointing to 'my_proj' folder. Then I removed settings.py to make sure still that it is the file gunicorn is picking up. The startup failed. I tried modifying settings.py printing out something from it but it is not working, logger.info is not printing from there. I have several Django projects on one cluster node running (not sure that it is important). Its as if Django is storing some cached file and using it, but how come gunicorn restart does not fix it? Seems weird to me. Any suggestions would be greatly appreciated. -
django-celery-beat break django unexpectedly
I am working with django-celery-beat with celery 4.2.1 and django2. At first it works perfect but after some time in gunicorn log appears the following error Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) File "/var/infra/app/smartwaypanel-backend/src/restfull_api/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/.local/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/ubuntu/.local/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/local/lib/python3.5/dist-packages/django_celery_beat/models.py", line 8, in <module> from celery.five import python_2_unicode_compatible ImportError: cannot import name 'python_2_unicode_compatible' It is a very strange behaviour and I cannont find more information about. -
How to handle HTTP responses in client side? [ReactJS & Django]
I have an endpoint to produce the token for authentication using JWT method. I send the request with Axios. Now assume I get back HTTP_BAD_REQUEST_400. If we look to console of browser in client side we get some message like this: POST http://127.0.0.1:8000/users/api/token/ 400 (Bad Request) How should I prevent of displaying the message? -
How to integrate sitemaps to django-oscar?
I want to integrate sitemaps for my oscar project and I used django-sitemaps package I followed the same, created an app called sitemaps-django, configured views.py, sitemaps-django/pages/sitemaps.py, URLconf in main urls.py file Views.py from sitemaps_django.pages.sitemaps import PagesSitemap def sitemap(request): sitemap = Sitemap( build_absolute_uri=request.build_absolute_uri, ) # URLs can be added one-by-one. The only required argument # is the URL. All other arguments are keyword-only arguments. for p in Page.objects.active(): url = p.get_absolute_url() sitemap.add( url, changefreq='weekly', priority=0.5, lastmod=p.modification_date, alternates={ code: urljoin(domain, url) for code, domain in PAGE_DOMAINS[p.language].items() }, ) # Adding conventional Django sitemaps is supported. The # request argument is necessary because Django's sitemaps # depend on django.contrib.sites, resp. RequestSite. sitemap.add_django_sitemap(PagesSitemap, request=request) # You could get the serialized XML... # ... = sitemap.serialize([pretty_print=False]) # ... or use the ``response`` helper to return a # ready-made ``HttpResponse``: return sitemap.response( # pretty_print is False by default pretty_print=settings.DEBUG, ) sitemaps-django/pages/sitemaps.py from django.urls import reverse_lazy from django.conf.urls import url urlpatterns = [ url(r'^robots\.txt$', robots_txt( timeout=86400, sitemaps=[ '/sitemap.xml', reverse_lazy('articles-sitemap'), ..., ], )), ] urls.py from django_sitemaps import robots_txt from sitemaps_django.views import sitemap urlpatterns = [ url(r'^sitemap\.xml$', sitemap), url(r'^robots\.txt$', robots_txt(timeout=86400)), ... ] I get this error url(r'^robots\.txt$', robots_txt( NameError: name 'robots_txt' is not defined -
Annotations in django with model managers
I have two models with an one to many relation. One model named repairorder, which can have one or more instances of work that is performed on that order. What I need is to annotate the Repairorder queryset to sum the cummulative Work duration. On the Work model I annotated the duration of a single Work instance based on the start and end date time stamps. Now I need to use this annotated field to sum the total cummulative Work that is performed for each order. I tried to extend the base model manager: from django.db import models class WorkManager(models.Manager): def get_queryset(self): return super(OrderholdManager, self).get_queryset().annotate(duration=ExpressionWrapper(Coalesce(F('enddate'), Now()) - F('startdate'), output_field=DurationField())) class Work(models.Model): #... order_idorder = models.ForeignKey('Repairorder', models.DO_NOTHING) startdate = models.DateTimeField() enddate = models.DateTimeField() objects = WorkManager() class RepairorderManager(models.Manager): def get_queryset(self): return super(RepairorderexternalManager, self).get_queryset().annotate(totalwork=Sum('work__duration'), output_field=DurationField()) class Repairorder(models.Model): #... idrepairorder = models.autofield(primary_key=True) objects = RepairorderManager() For each Repairorder I want to display the 'totalwork', however this error appears: QuerySet.annotate() received non-expression(s): . and if I remove the output_field=DurationField() from the RepairorderMananager, it says: Cannot resolve keyword 'duration' into field. -
Upload a file, display the data and store them in a database
How to upload a file, parse it, display the content, modify the data and store them in a database in Django? Let's assume a Django model with name, date of birth, address... I'm using a form to upload a CSV file with different data per line. Now my question is, what is the best (and a save) way to display the data for modification and completing before storing them into the database? -
Post LIST OF OBJECTS from HTML/axios with multipart/form-data to DRF multipart parser
This is my serializer: class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer(many=True) # reverse FK relation ParentSerializer also has an image field, so the request has to be multipart/form-data to support both image and data in a single request. The following code/test works fine: test_data = QueryDict('', mutable=True) dictionary = { 'name': ['test'], 'children[0]': [{'key1': 'val1', 'key2': 'val2'}] } test_data.update(MultiValueDict(dictionary)) test_serializer = self.get_serializer(data=test_data) test_serializer.is_valid(raise_exception=True) test_instance = test_serializer.save() ...because I'm manually creating the children list. The problem is I'm not able to do the same through axios/HTML form. The data being sent is converted to string. What are my options? I want to send list of child objects along with other data. DRF v3.9 & Django v2.2.