Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
loop.run_until_complete(main(request)) NameError: name 'request' is not defined
i tried of integrating django with asyncio and aiohttp here is how my function looks like async def main(request): ws = web.WebSocketResponse() await ws.prepare(request) msg="this is awesome" ws.send_str(msg) return HttpResponse("ok") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(main(request)) loop.close() i want to send that message as websocket using aiohttp websockets but when ever i tried to run this peice of code and access the domain path i got this error in termianl loop.run_until_complete(main(request)) NameError: name 'request' is not defined but this is working perfectly fine when i tried to use web scraping in an asynchronous function using aiohttp&asyncio def djangoview(request): async def main(request): async with aiohttp.ClientSession() as client: async with client.get('http://localhost:3000/employees') as post: if post is not None: post=await post.json() page=post[0]['url'] token=post[0]['Authorization'] headers={'content-type':'application/json', 'Authorization':token} req=requests.get(page) soup = BeautifulSoup(req.content, 'html.parser') title=soup.find_all('h1')[0].get_text() body=soup.find_all('p')[0].get_text() print(title) await client.post('http://127.0.0.1:8000/api/list/',json={ "title":title,"content": body,"tags": []},headers=headers) else: print('none enctype') loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop = asyncio.get_event_loop() loop.run_until_complete(main(request)) loop.close() return HttpResponse("ok") i don't know what the issue could be and please let me know if you have better suggestions on using websockets in aiohttp with django -
Linking profile model to user
I created a separate profile form from what users enter when they sign up and I am trying to attach information inputted in this form to its relevant user. I have tried creating a foreign key in my profile model that refrences the user model however, I could not get that to work. models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) bio = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) level = models.CharField(max_length=255, choices=level_list, blank=True) preferred_language = models.CharField(max_length=255, choices=language_list, blank=True) time_zone = models.CharField(max_length=255, choices=time_list, blank=True) def create_profile(self, bio, instrument, email, level, preferred_language, time_zone): profile_obj = self.model(bio=bio, instrument=instrument, level=level, preferred_language=preferred_language, time_zone=time_zone) # add arguments full_name=full_name profile_obj.save(using=self._db) return profile_obj views.py def profile_page_edit(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): bio = request.POST.get('bio', '') instrument = request.POST.get('instrument', '') level = request.POST.get('level', '') preferred_language = request.POST.get('preferred_language', '') time_zone = request.POST.get('time_zone', '') #profile = request.user #form.save() profile_obj = Profile(bio = bio, instrument = instrument, level = level, preferred_language = preferred_language, time_zone = time_zone) profile_obj.save() return redirect('/student/profile-page') else: form = ProfileForm() form = ProfileForm() context = {'form': form } return render(request, 'student/profile_page_edit.html', context) def profile_page(request): form = ProfileForm profiles = request.user.profile.objects.all() args = {'form' : form, 'profiles' : profiles} return render(request, 'student/profile_page.html', args) I am trying … -
Zappa Django project "DisallowedHost at /" even though ALLOWED_HOSTS are correct
I am deploying my django app on AWS Lambda and RDS using zappa serverlessly I am using a Postgres database as my RDS instance. When I run my commands I am not getting any errors Your updated Zappa deployment is live!: https://56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com/production However when I click that link I get DisallowedHost at / Invalid HTTP_HOST header: '56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com'. You may need to add '56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com' to ALLOWED_HOSTS. Now I have added ALLOWED_HOSTS in my settings.py file ALLOWED_HOSTS = ["56ks43234234fhkshdfk48.execute-api.us-east-1.amazonaws.com/", ] Below are the steps I did $ pip install zappa $ zappa init $ zappa deploy production Below is my zappa_settings.json { "production": { "aws_region": "us-east-1", "django_settings": "Cool.settings", "profile_name": "default", "project_name": "cool", "runtime": "python3.6", "s3_bucket": "cool-723m6do75", "project_directory": "/tmp/code", "slim_handler": true, "vpc config": { "SubnetIds": [ "subnet-37werwer16b", "subnet-375werrwr19", "subnet-2cwerwr3c23", "subnet-5awerwrr93d", "subnet-1dwerwrre57", "subnet-fwerwerf9c7" ], "SecurityGroupIds": [ "sg-a9c865d7" ] } }, "production_ap_northeast_1": { "aws_region": "ap-northeast-1", "extends": "production" }, "production_ap_northeast_2": { "aws_region": "ap-northeast-2", "extends": "production" }, ... #All available zones " } Somehow this is not making any sense and I am not sure how to proceed. Can someone guide me in the correct direction. If there is any additional detail anyone needs. Please feel free to ask -
Is it possible to use/test a value of Django's BooleanField without a model?
I'm trying to make a workflow where the user enters data on one page, then has to check the data and tick a tickbox to accept the T&C's. So the code has to check that the checkbox is checked before going on, but doesn't care until the second step. It's not a bound field and I think that's the problem - I don't need a model just to handle a workflow, and I don't want to have to store, in a database, a simple ephemeral field in a form! I'm running Django 2.1.5. I've tried every possible combination of: test_form.fields['tickbox'].value - doesn't exist, which is ridiculous test_form.fields['tickbox'] == False - value doesn't change at all request.POST['tickbox'] seems to go missing? views.py from django.http import HttpResponse from django.template import loader from django.forms import Form, CharField, BooleanField class test_form(Form): name = CharField() tickbox = BooleanField(required=False, initial=False) def testview(request): if request.method == 'POST': testform = test_form(request.POST) if testform.fields['tickbox'] == True: do_things() else: dont_do_things() else: testform = test_form() template = loader.get_template('testform.html') context = { 'testform : userform, } return HttpResponse(template.render(context, request)) I should be able to test the value of the field and get a changing response depending on if the user has ticked … -
Insert custom field in Django response using middleware
I am looking for the right directions to add a custom field in the HTTP response using middleware and access the custom field in the JavaScript front-end. I am trying to implement this, but on receiving the response on the JavaScript side there is no field like "is_logged" in the body. class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.user.is_authenticated: response = self.get_response(request) response.body['is_logged'] = True else: response = self.get_response(request) response.body['is_logged'] = False return response -
Filter based on foreign key
So i was working on this problem for many days already and can't make it work. Basically I have three models class Year(models.Model): year = models.CharField() class Book(models.Model): name = models.CharField( verbose_name = "Library Name", max_length = 255 ) author = models.ForeignKey( Author, on_delete=models.CASCADE ) year = models.ForeignKey( Year, on_delete=models.CASCADE ) class Author(models.Model): name = models.CharField( verbose_name = "Author's Name", max_length = 255 ) num = models.CharField( max_length = 255, default=0 ) For example, If I pass 2018 i want retrieve all the Authors who published book in 2018. I tried different queries like Year.objects.filter(year=2018).filter() and don't know how to filter the rest -
Refresh data in django template without reloading page
Hi I'm trying to get new data added to DB without refresh the page. I'm using this library chartjs-plugin-streaming to live streaming data. I've tried with a ajax callback to my URL in wich my view is called My view gets to my template my model. view.py def live(request): queryset = Registro.objects.all() if request.GET.get('ensayo__exact') is not None: queryset = queryset.filter(ensayo__exact=request.GET.get('ensayo__exact')) if request.GET.get('presion') is not None: queryset = queryset.filter(presion=request.GET.get('presion')) if request.GET.get('etapa') is not None: queryset = queryset.filter(etapa=request.GET.get('etapa')) if request.GET.get('fecha__gte') is not None: queryset = queryset.filter(fecha__gte=request.GET.get('fecha__gte')) if request.GET.get('fecha__lte') is not None: queryset = queryset.filter(fecha__lte=request.GET.get('fecha__lte')) presion = [str(obj.presion) for obj in queryset] etapa = [str(obj.etapa) for obj in queryset] tempin = [str(obj.tempin) for obj in queryset] fecha = [str(obj.fecha) for obj in queryset] fecha__gte = [str(obj.fecha) for obj in queryset] fecha__lte = [str(obj.fecha) for obj in queryset] id = [int(obj.id) for obj in queryset] ensayo_id = [int(obj.ensayo_id) for obj in queryset] context = { 'presion': json.dumps(presion), 'etapa': json.dumps(etapa), 'tempin': json.dumps(tempin), 'fecha': json.dumps(fecha), 'fecha__get': json.dumps(fecha), 'fecha__lte': json.dumps(fecha), 'id': json.dumps(id), 'ensayo_id': json.dumps(ensayo_id) } return render(request, 'reporte/live_data.html', context) and this are the js functions I've tried in my tempalte and the canvas that render the li: template.html function update() { $.get('', '', function() { return presion … -
How do i Fix api data not displaying with vue and axios
I can't seem to load the data information on the html table from the api via using vue and axios I am adding vue as my frontend to my rest api and i have called the api correctly using axios the problem i am having is there is no data shown but the loop displays the number of lines cos i have 3 entries and the table shows 3 empty spaces but no meaningful data and there's no console error please what ami i doing wrong ? <div class="body"> <table class="table table-bordered table-striped table-hover dataTable "> <thead> <tr> <th>Article Id </th> <th>Title</th> <th>Body</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tfoot> <tr> <th>Article Id </th> <th>Title</th> <th>Body</th> <th>Edit</th> <th>Delete</th> </tr> </tfoot> <tbody> <tr v-for="article in articles" :key="article.article_id"> <td>{{ article.article_id }}</td> <td>{{ article.article_title }}</td> <td>{{ article.article_body }}</td> <td><button @click="geArticle(article.article_id)" class="btn btn-round btn-primary">Edit</button></td> <td><button @click="deleteArticle(article.article_id)" class="btn btn-round btn-danger">Delete</button></td> <td></td> </tr> <script> new Vue({ el: "#startapp", data: { articles: [], // loading: false, currentArticle: {}, message: null, currentArticle: {}, newArticle: {'article_title': null, 'article_body': null} }, mounted(){ this.getArticles(); }, methods: { getArticles: function() { axios({ method: 'get', url: '/api/article' }).then((response) => this.articles = response.data) } } }); </script> The data from the api is supposed to show … -
Rest Framework serializer to create parent and one of multiple child types
I have a serializer that creates a parent model, then creates a child model depending upon some information provided to the parent: class InitializeFormSerializer(serializers.Serializer): title = serializers.CharField() category = serializers.ChoiceField(choices=CATEGORY_TYPES) def create(self, validated_data, user): identifier = validated_data.get('title') obj, created = Parent.objects.update_or_create( user=user, ) if created: item_type = validated_data.get('item_type') if item_type == 'FIRST_TYPE': Child1.objects.create(identifier=obj) elif item_type == 'SECOND_TYPE': Child2.objects.create(identifier=obj) return obj This works, but the item_type check feels clumsy. Is there a paradigm within Django or Rest Framework I'm missing that might make this more elegant? -
Is there a way to pass an object + parameter using Django's list view?
I have a one question ~! Using Django's list view I want to pass the search keyword and the query set object post_list at the same time. I would like to pass the q in the function below, but I do not know how. If you know how, thank you if you let me know ex1 # pagination X search o class PostListView(ListView): model = Post template_name = 'blog/post_list.html' paginate_by = 2 q = '' def get_context_data(self, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) q= self.request.GET.get('q','') if q: print('q : ', q) context['post_list'] = Post.objects.filter(title__icontains=q) else: context['post_list'] = Post.objects.all() return context ex2 # pagination X search o class PostListView(ListView): model = Post template_name = 'blog/post_list.html' paginate_by = 2 q = '' def get_context_data(self, *args, **kwargs): context = super(PostListView, self).get_context_data(*args, **kwargs) q= self.request.GET.get('q','') if q: print('q : ', q) context['post_list'] = Post.objects.filter(title__icontains=q) else: context['post_list'] = Post.objects.all() return context -
Celery not making task
I'm new in async and celery, this is my first time. And i have a problem with a task. My task is just taking object with field, and make minus one from IntegerField. This method is worked when i used from python manage.py shell. But when i want to do this in celery task it's not worked. Also i dont know what happening its just say me a nothing.. Can someone told me how i can get why i have no output when i call celery worker -A project_name settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} CELERY_RESULT_BACKEND = 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0' celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') app = Celery('project_name') app.config_from_object('django.conf:settings') app.autodiscover_tasks() tasks.py from project_name.celery import app from .models import Post @app.task def check_post(): posts = Post.objects.filter(premium=True) if salons.count() > 0: for post in posts: salon.minus_premium_day() return True else: return False Output - i make this all on remote server.. ---- **** ----- --- * *** * -- Linux-4.9.132-0-beget-acl-x86_64-with-debian-wheezy-sid 2019-01-27 01:41:51 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: project_name:0x7f4e595081d0 … -
How to generate thumbnails in MEDIA_DIR from images stored in STATIC_DIR with Django?
I have a number of images stored in my static dir, set as per my django settings. These images are all different sizes and aspect ratios. They display fine in my django application at the moment. I want to generate thumbnails from these images using "smart crop" functionality (which looks for the parts of the image with the most entropy when reducing instead of just centering). I've tried this both with sorl-thumbnail and the easy_thumbnail packages that have the "smart crop" functionality I am after. In both cases, I get an error: SuspiciousFileOperation at /products The joined path (/static/images/products/test1.jpg) is located outside of the base path component (/home/jake/webapps/my_webapp/my_site/media) I understand that media and static dirs are meant to be distinct from each other, with media being for where users upload files and static being files that are part of the site. But, since thumbnail packages need to read images from my static dir and generate them in my media dir, how can I resolve this security conflict? Surely this should be a common configuration for people generating thumbnails, basin them on images in their static dir? Yet I can't find anything on this error coming up in this context before, … -
multiple field search in dajngo app wrong results
I would like to create a multiple field search for the my database in django app. my search work correct only if the user use all fields from html form. if the user don't use some field or if some field is empty or blank then my query return all results (like apps=movies.objects.all() ) and that is wrong because the user in not required to use all fields but anytime to use fields where need for search. any idea how to fix that ? here my code: models.py : class category(models.Model): title = models.CharField(max_length=100, blank=True, null=True) class movies(models.Model): code = models.CharField(max_length=100, blank=True, null=True) code_2 = models.CharField(max_length=100, blank=True, null=True) name = models.CharField(max_length=100, blank=True, null=True) year = models.CharField(max_length=100, blank=True, null=True) movies_title=models.ForeignKey('category', blank=True, null=True) link=models.CharField(max_length=100, blank=True, null=True) html form : <form method="POST" action="{%url 'search' %}">{% csrf_token %} <select name="link"> <option value=""></option> <option value="0">link 1</option> <option value="1">link 2</option> <option value="2">link 3</option> </select> <select name="category"> <option value=""></option> {% for data in cat%} <option value="{{ data.id }}">{{ data.title }}</option> {% endfor %} </select> <select name="year"> <option value=""></option> {% for data in apps%} <option value="{{ data.id }}">{{ data.year }}</option> {% endfor %} </select> code: <input type="text" name="code"><br> code_2: <input type="text" name="code_2"><br> name: <input type="text" name="lname"><br> <input type="submit" … -
Images database schema
I'm trying to store user profile pictures, uploaded images in statuses, etc. on my site. When the user uploads a profile picture, there should be 3 types of the same image (Original image, medium sized, small sized). This is stored in the filesystem. A user can upload a maximum of 2 pictures in their statuses and each of these images follow the same types (original, medium, and small). The reason why I'm making different thumbnails of the same image is to serve those images depending on which screen display the user is accessing the site. That being said, what is the best way to store these image's file paths in my database? What kind of schema makes the best sense, or if there is another better way I can serve these images, what is the best approach? For the profile image table, I was thinking something like this: id user_id size img 1 2 S /img/s/avatars/ex.jpg 2 2 M /img/m/avatars/ex.jpg 3 2 L /img/l/avatars/ex.jpg Does this look like a good approach? -
Trouble with redirecting to an absolute_uri
I'm attempting to redirect to a full url currenturl = request.GET.get('currenturl') #lets say this resolves to google.com return redirect(currenturl) This sends me to an 404 error page as it's trying to resolve the following url http://localhost:8000/accounts/profile/calendar/delete/15/'google.com' -
How to designate a template tag element in custom template filter? (Django 2.1)
I am trying to build a custom template filter that highlights the keyword put into my search engine in the search results. Search engine code in view.py: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') context = {'articles': articles, 'search_term': search_term} return render(request, 'query_search.html', context) HTML template for search results: <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article }}</a></li> <p> {{ article.Content|highlight: search_term }} </p> {% endfor %} </ul> Custom filter: @register.filter def highlight(text, search_term): text = article.Content return mark_safe(text.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) I get the error message "highlight requires 2 arguments, 1 provided". I assume this is because I am not designating the template tag element article.Content right. How can I do it properly? -
How to send value from stars input to database with AJAX
I am trying to get the value from a stars rating input I have and send it to a form input to be submitted into the database. I have tried creating a form input that is hidden and takes the value of the stars, but I could not get it to work. HTML <div class="form-group"> <x-star-rating value="5" number="5" id="stars"></x-star-rating> </div> <div class="bottom"> <button type="submit" name="submit" class="btn blue_button" onclick="getRating()">Save</button> </div> Javascript function getRating() { var stars = document.getElementById('stars').value; $.ajax({ method: 'POST', url: '/student/rating/', dataType: 'json', contentType: 'application/json', async: true, data: { stars: $('#stars').val(), }, success: function(data){ results = $(data).find('#stars').html(); }, error: function(){ alert("Error"); }, }); }; forms.py class RatingForm(forms.ModelForm): review = forms.CharField(widget=forms.Textarea(attrs={'class' : 'form-control', 'rows' : 5, 'required' : 'true'})) stars = forms.IntegerField(widget=forms.TextInput(attrs={'required' : 'true'})) class Meta: model = Rating fields = ('review', 'stars') views.py @csrf_exempt def rating(request): if request.method == 'POST': form = RatingForm(request.POST) if form.is_valid(): stars = response_data['stars'] review = request.POST.get('review', '') stars = request.POST.get('stars', '') rating_obj = Rating(review = review, stars = stars) rating_obj.save() return HttpResponse(json.dumps({'stars': stars}), content_type="application/json") return redirect('/student/leave-feedback') form = RatingForm() context = {'form': form } return render(request, 'student/rating.html', context) I want to grab the value from the javascript created stars, and send it to a … -
Group private messages in Django by users
I have built a private messaging system for registered users in Django, and I have a small issue. I cannot think of a way to group the messages by users. The image below shows the messages between two users. This is the conversation as seen by the user karolann. You can see that it does not group the messages correctly. The sentences "Hello Susan" and "Those two modules are quite challenging" should come after the last sentence - "Text me when you online.". Right now, the messages are grouped by the sender. If I group them by the receiver, it still does not work properly. It would need something that is common for both like a conversation id or something. So my question is: How do I create conversations? I want all the messages between two users to be in the same place. My models.py is as follows: My views.py is as follows: And lastly, my template: -
Suspicious Operation trying to upload local image to S3 in Django
I'm developing a Django project where my Users have a profile picture saved as an ImageField, which I currently store in S3. class MyUser(models.Model): user = models.OneToOneField(User, unique=True) picture = models.ImageField(max_length=255, upload_to=get_user_pic_path) def get_user_pic_path(instance, filename): return os.path.join('user_pics', instance.user.username, filename) with the relevant settings.py: # Amazon S3 stuff AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' # URL prefix for static files. STATIC_ROOT = '/%s/' % AWS_LOCATION STATIC_URL = '//%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media urls MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION MEDIA_URL = '//%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The project works in production, which allows users to create accounts by taking a webcam photo and saving that to S3, but I get a SuspiciousOperation when trying to set up a local user for testing purposes. I have a command that is invoked by python manage.py create_test_user, which does: def handle(self, *args, **options): pic_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'test_img.jpg') user_list, pic_list = [], [] for i in range(5): # create user objects associated with each MyUser u = User.objects.create_user( username='bickeree_'+str(i), email=str(i)+'@gmail.com', password='1234' ) u.first_name = 'Test User' u.last_name = … -
Django Form Doesn't Save to Table
Here is the issue - when the user presses the 'Save' button, the settings they entered SHOULD be saved to the table. However, this doesn't happen. After you are redirected, you can check the 'Settings' page again or the admin site and the changes will not appear. I even put in several print statements which ALL run, but I can't figure out why this is happening. Here is the code (I only included what is necessary) views.py class SettingsView(LoginRequiredMixin, FormView): template_name = 'example/settings.html' form_class = ExampleSettingsForm success_url = reverse_lazy('example:index') def get_context_data(self, **kwargs): context = super(SettingsView, self).get_context_data(**kwargs) context['page'] = 'settings' return context def get_initial(self): initial = super(SettingsView, self).get_initial() initial['example1'] = self.request.user.example.example1 initial['example2'] = self.request.user.example.example2 initial['example3'] = self.request.user.example.example3 initial['example4'] = self.request.user.example.example4 initial['example5'] = self.request.user.example.example5 initial['example6'] = self.request.user.example.example6 initial['example7'] = self.request.user.example.example7 return initial def form_valid(self, form): form.save_to_example(self.request.user) print("Form valid.") return super(SettingsView, self).form_valid(form) @method_decorator(shelter_login_required) def dispatch(self, *args, **kwargs): return super(SettingsView, self).dispatch(*args, **kwargs) forms.py class ExampleSettingsForm(forms.Form): example1 = forms.CharField() example2 = forms.TimeField() example3 = forms.TimeField() example4 = AddressField() example5 = forms.IntegerField() example6 = forms.RegexField(regex=r'^\+?1?\d{9,15}$') example7 = forms.BooleanField() def save_to_example(self, user): user.example.example1 = self.cleaned_data['example1'] user.example.example2 = self.cleaned_data['example2'] user.example.example3 = self.cleaned_data['example3'] user.example.example4 = self.cleaned_data['example4'] user.example.example5 = self.cleaned_data['example5'] user.example.example6 = self.cleaned_data['example6'] user.example.example7 = self.cleaned_data['example7'] user.save() print(user.example.example1) -
Django REST API not returning response to angular 7 http.post call
I have been trying to call API, I created in Django it works fine in Postman application gives the right results, but when I call it in my Angular 7 app it returns status code 200 ok! but I don't get any response !! ** ANGULAR 6 ** return this.http.post(`http://localhost:8000/scheduler/FCFS/`, body, { headers: headers }).pipe( map((response) => { return response; }) ) Django (view file) @api_view(['GET', 'POST']) def FCFS(request): return Response({'foo':'boo'}) Here are some screenshots Angular response -
How can I build a Django template filter that displays text surrounding a certain word? (Django 2.1)
I am building a search engine and want my search results to contain a short text blob that shows the keyword highlighted in its context, just like Google. For example, if the keyword is "Linux", I want my text blob to be something like "Get a Linux computer: no need to remove (and pay for) all the software you can't trust! The following vendors sell machines preinstalled with ..." So far, I've only found a filter mechanism to limit the amount of characters shown in the text blob, but I don't know how to restrict these characters to the characters surrounding the keyword. Any idea? My template: <div id="results-list" class="container"> <ul> {% for article in articles %} <li><a href="{% url 'search:article_detail' article.ArticleID %}">{{ article }}</a></li> <p> {{ article.Content|slice:":255" }} </p> {% endfor %} </ul> </div> My code for the search engine: def query_search(request): articles = cross_currents.objects.all() search_term = '' if 'keyword' in request.GET: search_term = request.GET['keyword'] articles = articles.annotate(similarity=Greatest(TrigramSimilarity('Title', search_term), TrigramSimilarity('Content', search_term))).filter(similarity__gte=0.03).order_by('-similarity') -
Server Error 500 in deploy Django to Heroku
So, I have a problem with a Django project I deployed to Heroku. I have finally been through the whole process of deploying the project resolving loads of errors. Now that the site is correctly deployed i have difficulties with my login app (that works perfectly fine on local host). Whenever I try to Register or login a user (or login in the admin page), i get a Server 500 error (You can try yourself at the link Universalvvfamily.herokuapp.com), but i can't understand why... What should I show you about my code so that you can help me? Thank you very much in advance -
Django send_mail giving NoneType Error with RequestFactory, But Not When Running Code Outside of Views (Test Code Included)
So I am having issues with my website in production and figured it was something with Nginx while in production. But I have boiled it down to another issue, that I am not quite sure how to define. The issue at hand is when using the send_mail function in Django (1.10.x). I can send emails perfectly when I run my function code from the terminal, just by typing it out while in a python shell. But when I try to run it using RequestFactory and running the given function with the request, I get an odd error. This error on my terminal screen is much more clear than the blank 500 server error I receive on my website. I have tried different email setups, even changing the email backend to console in the settings, and nothing is working. Code that works, after opening up my shell ./manage.py shell_plus >>> from django.core.mail import send_mail >>> name = 'Test User' >>> contact_email = 'testing@test.com' >>> contact_phone = '123-456-7890' >>> subject = 'Message from: %s, %s' % (name, contact_phone) >>> message = 'This is a test being sent from the backend console.' >>> to = 'user@test.com' # changed for anonymity >>> send_mail(subject, message, … -
Django: access from different network
I made a django server, which I ran by the command: python3 manage.py runserver 0.0.0.0:8000 When I try to connect to the server from the same computer using the localhost:8000 everything works fine :) However, when I try to connect to the server using server_ip:8000 from another computer, I get the response: ERR_CONNECTION_TIME_OUT. ( The server ip is configured in ALLOWED_HOSTS ) Any ideas how to solve this problem or what might be causing it? :)