Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
scroll down button changes url django
I am working on a django website which contains a button at the top of the page, which when clicked should scroll down. The button is enclosed in an anchor tag, with a specified href attribute. When I click the button the program alters the url, resulting in a 404 error. How do I code this to ensure that the url is not affected when the button is clicked? This is my code so far <a class="scroll_down_button" href='.second_part'>click</a> <div class="second_part"> This is a test </div> This is the error I am getting Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/.second_part -
Hotel Reservation system in Django: How to make a room unavailable to other users for a period of time
I am building a hotel reservation system for my a-level coursework and my problem is when a user books a room I want to make sure no other user can reserve that room for the duration of the time period that the room is occupied. I tried using iteration to loop over the dates and have a boolean value that is set to true when the room is reserved and false when it is not. Here is my models class Room(models.Model): name = models.CharField(max_length = 200) img = models.ImageField(upload_to='Pictures') desc = models.TextField() price = models.IntegerField() is_reserved = models.BooleanField(default=False) number_of_people = models.PositiveIntegerField() def __str__(self): return self.name class Meta: verbose_name = 'Room' verbose_name_plural = 'Rooms' class Reservation(models.Model): check_in = models.DateField(default=timezone.now) check_out = models.DateField() room = models.ForeignKey(Room, on_delete = models.CASCADE) guest = models.ForeignKey(User, on_delete= models.CASCADE) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' This is my function in views where it will loop over the checkin and check out dates inputted by the user and make sure that no other user can reserve that room for those dates def confirm(request, pk = None): if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) guest_id = request.user check_in = request.session['check_in'] check_out = request.session['check_out'] … -
What does 'group_list' object has no attribute 'object' mean?
I want to create listview and createview on the same screen, but I do not understand the meaning of the current error "'group_list' object has no attribute 'object'". I tried to create it on the basis of createview, but the list was confused. I also tried to create and inherit the createview and listview classes, but the same error occurred. #error 'group_list' object has no attribute 'object' #forms class GroupRequestForm(mixins.BaseModelForm): class Meta: model = belong fields = ('group',) #view class group_list(ListView,ModelFormMixin): model = group form_class = GroupRequestForm template_name = 'group/group_list.html' context_object_name = 'group_list' queryset = group.objects.all() def form_valid(self, form): group_pk = self.kwargs['pk'] comment = form.save(commit=False) comment.post = get_object_or_404(group, pk=group_pk) comment.save() return redirect('app:detail_and_create', pk=group_pk) def post(self, request, *args, **kwargs): self.object = self.get_object() # assign the object to the view form = self.get_form() if form.is_valid(): return self.form_valid(form) else: self.object = self.get_object() return self.form_invalid(form) # class group_list(CreateView,): # form_class = GroupRequestForm # template_name = 'group/group_list.html' # success_url = reverse_lazy('group:group_list') # # def get_context_data(self, *, object_list=None, **kwargs): # context_data = super(group_list, self).get_context_data(**kwargs) # context_data['group_list'] = group.objects.all() # return context_data # # def form_valid(self,form): # user = self.request.user # # POST.get('user_id') # form.instance.user = user # return super().form_valid(form) # class group_list(ListView): # model = group … -
ValueError: invalid literal for int with base 10: ' '
I am getting following error when I am trying to start the Django server. python manage.py runserver 0.0.0.0:8000 Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/core/management/init.py", line 363, in execute_from_command_line utility.execute() File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/core/management/init.py", line 307, in execute settings.INSTALLED_APPS File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 56, in getattr self._setup(name) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/django/conf/init.py", line 110, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/python-2.7/lib64/python2.7/importlib/init.py", line 37, in import_module import(name) File "/u/agrawalo/beatthestreet/beatthestreet/config/settings.py", line 96, in 'PORT': config('DB_PORT', cast=int), File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 197, in call return self.config(*args, **kwargs) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 85, in call return self.get(*args, **kwargs) File "/u/agrawalo/beatthestreet/lib/python2.7/site-packages/decouple.py", line 79, in get return cast(value) ValueError: invalid literal for int() with base 10: '' Content in .env SECRET_KEY=BeatTheStreet DEBUG=False ALLOWED_HOSTS=['*'] EVENT_STARTED=True EVENT_ENDED= # Production database details DB_NAME= DB_USER= DB_PASSWORD= DB_HOST= DB_PORT= -
How to fix form fields not appearing in html/django?
I'm very new to Django and was following a tutorial on creating a user registration page. However, when I run the server the form fields don't appear and only the submit button is there. I looked through many tutorials and tried to change the UserForm class thinking that that was the problem but I get the same issue. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] views.py ... class UserFormView(View): form_class = UserForm template_name = 'static/register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form":form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): #creates an object frm the form but doesnt save it into the database user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns object if credenials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('main:homepage') return render(request, self.template_name, {"form":form}) urls.py from django.urls import path from . import views from django.conf.urls import url, include app_name = "main" urlpatterns = [ path("", views.homepage, name="homepage"), path("register/", views.UserFormView.as_view(), name='register'), ] register.html {% extends 'static/header.html' %} {% block content %} <br> … -
Google Search using python
I get data from input. When I click to search button I need to open webbrowser page and see my input data in google. How can I do that? Many thanks. This is my code: views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): if request.method == 'GET': return render(request, 'index.html', context={}) # Handles the search once the submit button in the form is pressed # which sends a "POST" request if request.method == 'POST': # Get the input data from the POST request search_query = request.POST.get('search', None) # Validate input data if search_query and search_query != "": return HttpResponse(search_query) try: from googlesearch import search except ImportError: print("No module named 'google' found") for j in search(search_query, tld="co.in", num=10, stop=1, pause=2): print(j) else: return HttpResponse('Invalid input.') index.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> </head> <body> <form method="POST"> {% csrf_token %} <input type="text" name="search" placeholder="some text"><br> <button class="button" name="submit" type="submit">Search</button> </form> </body> </html> urls.py from django.urls import path from firstapp import views urlpatterns = [ path('', views.index, name='home') ] All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp index.html path is: C:\Users\user\Desktop\hello\firstapp\templates -
Django not saving form data
I've made a simple test django project that's a simple list of posts. And I'm trying to add functionality to update a post. Everything seems to be working, except the edits aren't saved to the database. I've checked the cleaned data to see if the updated data is coming through, and it is, but the save() function doesn't seem to actually do anything. models.py class Block(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=140, null=True, blank=True) content = models.TextField() def save(self, *args, **kwargs): if self.slug is None: self.slug = get_unique_slug(self, 'title', 'slug') super().save(*args, **kwargs) def get_absolute_url(self): return reverse("bulkapp:one_view", kwargs={"slug_id": self.slug}) def __str__(self): return self.title views.py def edit_block_view(request, slug_id): single_block_query = get_object_or_404(Block, slug=slug_id) update_form_query = BlockForm(request.POST or None, instance=single_block_query) if update_form_query.is_valid(): update_form_query.save() return redirect('bulkapp:one_view', slug_id=slug_id) return render(request, 'bulkapp/update.html', {'update_form': update_form_query}) <form class="form-container" method="POST"> {% csrf_token %} {{update_form.as_p}} <input type="submit" value="Edit"> </form> The redirect fires as expected, but no changes are saved, and no error messages are written to the console. Any help would be much appreciated. -
How to save Django QuerySet directly into redis?
I'd like to save results of Django QuerySets directly into redis instead of using built in cache.set and cache.get. The reason is that I'd like to use a separate redis db for certain queries to accelerate data retrieval. Here is my sample code: def cached_post(id): r = redis.StrictRedis(unix_socket_path='/var/run/redis/redis.sock', db=6) key = "tpcpots:" + id if not r.get(key): post = Post.objects.get(pk = id) r.set(key, post, AN_HOUR) return r.get(key) But I get this error: cannot concatenate 'str' and 'long' objects How can I fix this? -
How to set custom rates, for throttling in django rest framework?
I'm using DRF for throtlling, according to the document I can choose one of these options for my rate : second, minute, hour, or day. But the problem is, that I want a custom rate, for example, 3 requests per 10 minutes. Is it possible in DRF ? -
What is the standard or the best way to filters using boolean field and retrieve the resources accordingly?
I have a use case where I want to list the resources(posts) based on the filters applied which are all, active and inactive. There is a flag in the Django post model which has is_active status. I want to know what is the best way to design the API contract for this filter. The list post API is a POST API call. Context below: Filters in UI (Multiple Checkbox): All Active Inactive If all is selected, then select both Active and Inactive. Ideal Output: If all is select, then show the list the posts irrespective of the statuses. If None are selected, then show the list the posts irrespective of the statuses. If either Active or Inactive is selected, then list the posts with respect to that. class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title The approach is to have a flag as status in post API and values can be true, false, null. { ... "status": true, ... } Approaches are: if the status is true, then list only post with true status. if the … -
I Have a problem with django2.2 and django-tastypie
I have this problem: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
Hide empty values with prefetch-object
I want to hide all "delivery"-objects when there is no package in it. prefetch = Prefetch('packages',queryset=Package.objects.filter(status = "open",order__producttyp = request.POST['products'])) queryset = Delivery.objects.annotate(num_packages = Count('packages')).filter(num_packages__gt=0).prefetch_related(prefetch) I would like to get a queryset object which I can iterate over in my template without having a lot of "empty Deliveries". At the Moment the result looks like: DeliveryInstance 1.1. Package 1.2. Package DeliveryInstance DeliveryInstance DeliveryInstance 4.1. Package 4.2. Package -
How to update data in database table using conditional expression
I want to update my data in my database table only if conditional expression work. I have a dictionary called result_total which is continuously updated. Using for loop condition I want to update my data. For example: if result_total[news_item][2] is equal to any of my database table entries then result_total[news_item][2] will not be updated for news_item in result_total: if Haberler.objects.get(haber_link=result_total[news_item][2]): Haberler.objects.filter(sira_no=news_item).update( haber_id=result_total[news_item][0], haber_baslik=result_total[news_item][1], haber_link=result_total[news_item][2], haber_imagelink=result_total[news_item][3], haber_text=result_total[news_item][4] ) error messages shows following "Haberler matching query does not exist." -
Is it possible to query a database based on it's __str__?
Let's say theoretically I have these 3 models: class Cable(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.cableTypes, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) def __str__(self): return str(self.get_type_display()) + " Cable, " + str(self.length) + "m" class Adapter(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) adaptFrom = models.IntegerField(choices=choices.connectors, default=1) adaptTo = models.IntegerField(choices=choices.connectors, default=1) notes = models.TextField(blank=True) length = models.DecimalField(decimal_places=2, max_digits=6) def __str__(self): return str(self.get_adaptFrom_display()) + " to " + str(self.get_adaptTo_display()) class Fixture(models.Model): id = models.OneToOneField(Item, primary_key=True, on_delete=models.CASCADE) type = models.IntegerField(choices=choices.fixtureTypes, default=1) model = models.CharField(blank=False, max_length=128) manufacturer = models.CharField(blank=False, max_length=128) notes = models.TextField(blank=True) def __str__(self): return str(self.manufacturer) + " " + str(self.model) Is it possible to query these models based on the string they return? If not, how would I go about doing something similair to it? The reason I need to do this is because I have a parent model called item (which is where all of these models get their primary keys from) but I still need to implement a search function to my website. Here is my current way of doing it, which is a bit messy: results = [] form = SearchForm(request.POST) if form.is_valid(): for category in Type.objects.all(): for item in Item.objects.all(): if item.type == category: model … -
ModuleNotFoundError: No module named 'ckeditor_uploader' in django
I'm trying to integrate a ckeditor in my django blog application. I followed all the instructions in the github page of django-ckeditor precisely. i.e. installed, added to installed apps, added in urls, collected staticfiles, configured settings in settings.py and imported ckeditor.fields in models whenever necessary. When I try to make migration or run, I get this error as below: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/kush/projects/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/kush/projects/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/kush/projects/venv/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/home/kush/projects/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'ckeditor_uploader' I cant seem to figure out whats wrong here. Anyone here been … -
Django - Haystack Whoosh No Results
I'm using haystack and whoosh for searching. I followed the documentation step by step and already saw these answers: Django-Haystack-Whoosh is giving no results, Django + Haystack + Whoosh, no results in production, django haystack whoosh not showing any errors also no results, no result are found - haystack django whoosh but none could help me. I think it's an problem with my article_text.txt because everything else works. Here's my search index: class ArticleIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr="title") author = indexes.CharField(model_attr="authors") pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return Article def index_queryset(self, using=None): return self.get_model().objects.visible_for_user() my search_indexes\indexes\article\article_text.txt {{ object.text }} {{ object.title }} {{ object.pub_date }} # This comment isn't in the file but it's an information for you: I also added "neue" to the end of this file to debug but event that didn't work Whenever I say "neue" (I have an article that has "neue" in its title) -
How to refresh part of a Django page with AJAX?
I am deploying a website using Django. There is an application called 'forum', supporting a discussion forum on my website. The url of the discussion forum is 'XXX.com/forum/roomY'. I want to refresh a div id = ''chat'', which includes a message list, on this page when users click a refresh button. I want to use AJAX to do that. But I find that I could not call the function updatestatementlist(request) to retrieve the updated message list so it can be passed to the on this page. /forum/views.py def updatestatementlist(request): log.debug("call statementlist function") statements = Statement.objects.filter(discussion=discussion) return render(request, 'forum/statementlist.html', { 'statements': statements }) I cannot see the log info so I think by clicking the button I fail to call this function. The main html page of the discussion forum is /forum/discussion.html, which is under the template folder. I extract the html code within the div id = "chat" to a separate html /forum/statementlist.html as suggested here and several other SO posts. /forum/discussion.html <button id = "Refresh"> Refresh </button> <div id="chat"> {% include 'forum/statementlist.html' %} </div> /forum/statementlist.html {% recursetree statements %} {% endrecursetree %} forum.js //When users click the refresh button $("#Refresh").on("click", function(event){ alert("Refresh clicked") $.ajax({ url: '', type: "GET", success: … -
Django app not opening from different machine
I have a Django server running on 127.0.0.1:8000 When I try to access it from the same machine then I am able to open my application. But when I try to access this app from a different machine by using machinename:8000 then it says 'This site can't be reached' In my settings.py, I have ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) and ALLOWED_HOSTS= Is this related to above configuration? -
Vue-apexchart is not rendering in async method without any error
I am using vue-apexchart in my application. I am pushing my data from async method in array and looping apexchart in template. I am not getting any error and data is also available in template . When i use codesandbox the functionality get work. Here is the link - https://codesandbox.io/embed/vue-basic-example-1o0xm the same thing i want to achieve in my project but inside the async method where i am getting response from my service and same i am pushing in array which is forwarding in template as well. If anybody knows what's wrong here then please provide the solution. -
saving foreignkey instances in the createview in views.py
I've a models called job, application, attachments. when a job is already created an a user wants to apply for the job I get an integrity error that says null value in column "job_id" violates not-null constraint If I add job in the fields part of class Meta of ApplicationForm everything runs successful but when the user select the job he whats to apply he is forced to select again the job to fill in the job field, So I want is to automatically add the job field to be added in createview in views.py here is my code models.py class Application(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='applied_jobs', null=True, on_delete=models.SET_NULL) job = models.ForeignKey(Job, related_name='applications', on_delete=models.CASCADE) career_briefing = models.CharField(max_length=250, null=True) class Attachments(models.Model): application = models.ForeignKey(Application, related_name='attachments', on_delete=models.CASCADE) cv = models.CharField(max_length=150, null=True) form.py class ApplicationForm(forms.ModelForm): cvs = forms.CharField(max_length=6000, widget=forms.HiddenInput(), required=False) class Meta: model = Application fields = ('career_briefing',) views.py class ApplicationCreateView(LoginRequiredMixin, CreateView): model = Application form_class = ApplicationForm message = _("succesfuly applied") template_name = 'jobs/application_form.html' message = _("successful") def form_valid(self, form): cvs = form.cleaned_data['cvs'] form.instance.user = self.request.user form.instance.job = self.kwargs.get('pk') apply = form.save(commit=False) apply.job = self.kwargs.get('pk') apply.user = self.request.user apply.save() doc = Attachments(cv=cvs) doc.application = apply doc.save() return super(ApplicationCreateView, self).form_valid(form) def get_success_url(self): messages.success(self.request, self.message) … -
Getting error while installing mysqlclient
I AM FACING THIS ERROR WHILE INSTALLING MYSQLCLIENT ON WINDOWS BY PIP ERROR: Command errored out with exit status 1: command: 'c:\users\noob\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\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\NoOB\AppData\Local\Temp\pip-record-bknw0h8q\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\ Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb__init__.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb creating build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants__init__.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\noob\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\NoOB\AppData\Local\Temp\pip-install-fylu3lfn\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\NoOB\AppData\Local\Temp\pip-record-bknw0h8q\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output. -
Credentials aren't allowed error when using Outlook REST API Oauth2 in AWS server
I'm trying to implement Outlook Oauth2 in our Django backend server which is hosted on an AWS instance. I carefully followed the instructions in their python tutorial and it works 100% in my local machine. I am able to grab the authorization code which I then convert in my backend server to an access token. The problem lies in our demo server which is an AWS instance. We have a button that redirects the users to Outlook authentication. The URL has the following format: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=<client-ID-here>&redirect_uri=<demo-server-redirect-url>&response_type=code&scope=openid+profile+offline_access+Calendars.ReadWrite&prompt=consent I am receiving the following error whenever I convert the authorization code into an access token just after the consent screen: { 'error': 'access_denied', 'error_description': 'Your credentials aren't allowed' } The weird thing is that if I use POSTMAN using the demo server Outlook credentials, I am able to retrieve an access token from Outlook. Basically, it works for both in my local machine and using Postman. I really think that I'm just missing a very small piece of code/configuration here. Are there some extra settings that I need to do in order to make Outlook Oauth2 work in AWS? -
how to read Django request.FILES (which is an image) as binary
Sorry for my bad English. I want to get binary image from request which contains image file from ajax. Because when user upload image file, I want to do OCR to the image file using google VISION API. Currently I'm using django, ajax. So when user upload the image, using ajax the file is passed to django view. I tried to get binary file in the views.py. But When I use request.FILES.get('file').read(), there is no data. But request.FILES.get('file').name is 'bank.png'... I think it's weird. Here is some code views.py def receipt_ocr(request): if request.method == 'POST': print(type(request.FILES["file"])) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(type(request.FILES.get('file'))) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> print(request.FILES.get('file')) #bank.png imageFile = request.FILES.get('file') print(imageFile.size) #119227 print(request.FILES.get('file').name) #bank.png print(request.FILES.get('file').content_type) #image/png print(type(request.FILES.get('file').open())) #<class 'NoneType'> print(request.FILES.get('file').open()) #None print(type(request.FILES["file"].read())) #<class 'bytes'> for chunk in imageFile.chunks(): print(chunk) #this generates lot of binary and some rdf:Description rdf:about= ... things receipt_image = imageFile.read() print(type(receipt_image)) print(receipt_image) ajax part // receipt OCR process $.ajax({ url: "{% url 'place:receipt_ocr' %}", enctype: 'multipart/form-data', type: 'POST', processData: false, contentType: false, data: postData, complete: function(req){ alert('good'); }, error: function(req, err){ alert('message:' + err); } }); What I exactly want to do is using this kind of code (google VISION API example code, OCR) def detect_text(path): """Detects text in the file.""" … -
models with ManyToManyField
suppose that you want to simulate universities system, you have courses, teachers, students. we have some courses that present by some teachers and student choose some courses with some teachers. for example: courses: math, physics teachers: Jack(math), Jane(math, physics) students: st1(math with Jack), st2(math with Jane), st3(physics with Jane and cant choose Jack!!), every score by default=-1. with this code: teachers = models.ManyToManyField(teacher.objects.filter(t_courses=s_courses), verbose_name='Ostad') I got errors like: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet from django.db import models class profile(models.Model): n_id = models.IntegerField(primary_key=True, verbose_name='code melli') name = models.CharField(max_length=24, verbose_name='Full Name') class Meta: ordering = ('name',) class course(models.Model): name = models.CharField(max_length=24, verbose_name='Class Name') unit = models.SmallIntegerField() class Meta: ordering = ('name',) def __str__(self): return self.name class teacher(profile,models.Model): t_id = models.AutoField(primary_key=True) t_courses = models.ManyToManyField(course, verbose_name='Dars') def __str__(self): return self.name class student(profile,models.Model): s_id = models.AutoField(primary_key=True) s_courses = models.ManyToManyField(course, verbose_name='Dars') #teachers = ?????????????????????????? score = models.IntegerField(default=-1, verbose_name='Nomre') def __str__(self): return self.name I don't know about coding in the teachers part. Thanks alot -
How to run django test on google cloud platform
i'm deploying my app on Google Cloud platform. Every thing seems to be set up correctly but when i try to launch test, i get this error : ====================================================================== ERROR: purbeurre.core (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: purbeurre.core Traceback (most recent call last): File "/usr/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/usr/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'purbeurre.core' Is there a special setting to have all my test modules loaded ? i did check locally and it's working on my dev environnement