Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'utf-8' codec can't decode byte - Python
My Django application is working with both .txt and .doc filetypes. And this application open file, compares it with other files in db and prints out some report. Now the problem is that, when file type is .txt, I get 'utf-8' codec can't decode byte error (here I'm using encoding='utf-8'. When I switch encoding='utf-8' to encoding='ISO-8859-1' error changes to 'latin-1' codec can't decode byte. I want to find such encoding format that work with every type of file. This is my a little part of my function: views.py: @login_required(login_url='sign_in') def result(request): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w') # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) -
No path found on Django Channels
I created a simple consumer on my Django channels application, but when i try to connect to the websocket from my frontend, i keep getting the following error: ws_protocol: ERROR - [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'messages/127.0.0.1:8000/messages/'. Here is my routing: myapp>routing.py from .consumers import EchoConsumer websocket_urlpatterns = [ path("messages/", EchoConsumer), ] mysite>routing.py # mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import myapp.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( myapp.routing.websocket_urlpatterns ) ), }) And here is how i'm trying to connect to the websocket from my frontend: var wsStart = 'ws://' + window.location.host + window.location.pathname Can anyone help me find what i'm doing wrong, please? -
Passing parameters using action tag in HTML
I'm working with Tornado (python), and my handlers are in this format. class Application(tornado.web.Application): def __init__(self): handlers = [ url(r'/', MainHandler, name="main_handler"), url(r'/user', UserHandler, name="user_handler"), url(r'/users', UserListHandler, name="user_list_handler"), url(r'/profile/(?P<username>\w+)', UserProfileHandler, name="user_profile_handler"), ] settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirname(__file__),"static"), debug = True) self.db = client['user_db'] super().__init__(handlers, **settings) My HTML code on the landing page is <h1>INFO DB</h1> <p>Search via username...</p> <form method="get" action="{% url 'user_profile_handler' find_username %}"> <p>Enter Username<br> <input rows=1 cols=20 name="find_username"></p> <input type="submit"> </form> <br> Now my aim is when I click on the submit button, I'm redirected to the page '/profile/{username} Eg: if the username in the search bar is 'abcd', I should be redirected to /profile/abcd on pressing submit. What to put in the action attribute of the form tag in HTML? -
Django Rest Framework is serializing an object two different ways using the same serializer
When using a DRF ViewSet and an APIView, I get two different results for serialization of a DurationField. At the first endpoint host/app/items, which corresponds to the viewset Items and lists all of the created items, I get this response: [ { "id": 2, "duration": "604800.0", ... } ... ] The response from host/app/user_data includes the items corresponding to the item instances which have a relation to the profile: { ... "items": [ { "item": { "id": 2, "duration": "P7DT00H00M00S", ... } ... } ] } But the duration is in the ISO 8601 duration format. This was very perplexing, because the endpoints use the same serializer. I confirmed this by forcing the serializing with duration = serializers.DurationField() in ItemSerializer. I want the same format, in seconds. What can I do? These are issues I found while researching this issue: https://github.com/encode/django-rest-framework/issues/4430 https://github.com/encode/django-rest-framework/issues/4665 Urls: router = routers.DefaultRouter() router.register(r'items', views.Items) urlpatterns = [ path('', include(router.urls)), path('user_data', views.UserData.as_view(), name='user_data'), ... ] Views: class Items(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer def get_permissions(self): if self.action in ('list', 'retrieve'): permission_classes = [AllowAny] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] class UserData(APIView): """Get authenticated user's information: data related to models User and Profile""" … -
View Flow and Django Guardian
I am relatively new to django-guardian and django-viewflow , am still trying to wrap my head around things. Recently i have been attempting to implement a workflow system to get approvals on certain documents. As such i have chosen view flow workflow engine. The workflow that i have been tasked on developing is actually pretty simple and linear. However , at every check point , there must be a different person with a specialized role to verify the documents. There is 4 roles, 1 the preparer , 2 the verifier , 3 the treasury and 4 the Director. As i can't have someone verifying for the Director himself , there is a need for a role based user control. As such , i have adopted django guardian to do this job. Here is some of my code to demonstrate how i did it : Flows.py class Pipeline(Flow): process_class = PaymentVoucherProcess lock_impl = lock.select_for_update_lock #process starts here start = flow.Start( CreateProcessView, fields=["paymentVoucher"], task_title="Processing New Voucher" ).Permission("can_start_voucher", auto_create=True ).Next(this.documents) #preparer will upload supporting documents documents = flow.View( UploadView, task_title="Receiving Supporting Documents" ).Permission("preparer", auto_create=True ).Next(this.preparer) #i wont go in detail as it isn't relevant Models.py this is where i defined my permissions , … -
How to deal with large amounts of data from django based IOT projects
I'm working on a django IOT related dashboard style project. I have a question related to the scale of the project. Let's say that there are 30 or more raspberry pi's or ardunios and you want to get the location and some other data off of them and store it in a database. How would one go about designing a database for a system at such a large scale. -
Compare two tables in Django
I am displaying data from Table1 in my template as seen below, I recently created another model called Table2 which contains data which I would like to display in my table as well. I need to check if the code in Table1 exists in Table2, and if so, grab the var1 and var2 from Table2 and display it in my template. Does anyone know how to do this the best way? Pseudocode If `code` In Table1 Exists In Table2 Get var1, var2 From Table2 My template {% for data in info %} <tr> <td>{{ data.created }}</td> <td>{{ data.publisher }}</td> <td>{{ data.person }}</td> <td>{{ data.code }}</td> </tr> {% endfor %} My view def home(request): info = Table1.objects.all()[:20] return render(request, 'app/home.html', {'info':info}) My models.py class Table1(models.Model): created = models.DateTimeField(default=None) publisher = models.CharField(max_length=50, default=None) person = models.CharField(max_length=50, default=None) code = models.CharField(max_length=25, default=None) class Meta: db_table = 'Table1' unique_together = (("publisher", "person", "code"),) def __str__(self): return self.created class Table2(models.Model): code = models.CharField(max_length=30, default=None, null=True) url = models.CharField(max_length=100, default=None, null=True) var1 = models.CharField(max_length=50, default=None, null=True) var2 = models.CharField(max_length=50, default=None, null=True) def __str__(self): return self.code -
Cannot register more than two classes in the Django admin
I am trying to register three classes to the admin. If I pass two classes it works perfectly but when I add the third I get the following error. I tried to pass three of then separately and that didn't work too. This is the my Django admin.py file: from django.contrib import admin from .models import Sensor from leaflet.admin import LeafletGeoAdmin from import_export.admin import ImportExportModelAdmin class Sensor_admin(LeafletGeoAdmin): list_display = ('subsystem', 'datasheet') class Sensor_io_Admin(ImportExportModelAdmin): pass admin.site.register(Sensor, Sensor_io_Admin, Sensor_admin) This is the error I got: TypeError: register() takes from 2 to 3 positional arguments but 4 were given What can be the way around it? I am using Django 2.1 version. -
Why is my EC2 instance is returning 400 error
I have deployed a Django website on AWS Elastic Beanstalk - the environment is green and website available via the url provided. However, I have set an application load balancer with the EC2 instance of the ELB application as the target group, and this is returning Bad Request (400). When trying to access the instance via the public DNS I get the same Bad Request (400). I have checked the security groups and all required ports (80 for http, 443 for https and 22 for ssh) are open on the instances security group and the target groups security group. I am unsure what else could be causing this as the django app is available and the instance has status running and I can ssh into it. Have checked the AWS docs and other similar questions on SO but can't find any possible solutions. -
Using Camelot to work on an opened pdf file (io.BytesIO object)
I am trying to read tables from a pdf uploaded by a user in Django and I get the uploaded file by request.FILES. I use camelot.read_pdf but it only seems to take a path to the pdf. Can not camelot work with a '_up.BytesIO' object and read a file without specifying a path but only through an already open file?(Like PyPDF2) -
Django ERROR with tmeplate rendering. Reverse for 'login' not found. 'login' is not a valid view function or pattern name
Im new to Django (also to stackoverflow too) and im trying to make simple accounts system. When im "sign out" button to main page im getting this error Reverse for 'logout' not found. 'logout' is not a valid view function or pattern name. account/views.py def signout_view(request): if request.method == 'POST': logout(request) return redirect('/') account/urls.py app_name = 'account' urlpatterns = [ path('signup/', views.signup_view, name='signup'), path('signin/', views.signin_view, name='signin'), path('signout/', views.signout_view, name='signout'), ] home/templates/home/wrapper.html <form class="logout-link" action="{% url 'account:logout' %}" method="post"> {% csrf_token %} <button type="submit">Sign out</button> </form> anyone can help with fixing this problem? -
Django rest framework, difficulty understanding foreign Key field serialization
I'm trying to learn the relations in the Django rest framework and the serializer's job in then. I have the following model: from django.db import models class Point(models.Model): Latitude = models.FloatField(verbose_name="Latitude", blank=False) Longitude = models.FloatField(verbose_name="Longitude", blank=False) elevation = models.FloatField(verbose_name='Location Elevation', blank=False, default=1) class Location(models.Model): location_name = models.TextField(unique=True, blank=False, verbose_name="Location Name") location_coordinates = models.ForeignKey(Point, on_delete=models.CASCADE, verbose_name='Latitude & Longitude') class Meta: unique_together = ['location_name', 'location_coordinates'] get_latest_by = 'date_added' def __str__(self): return f'{self.location_name},{self.location_coordinates}' And, this serializer: from rest_framework import serializers from .models import Location class LocationSerializer(serializers.ModelSerializer): location_name = serializers.RelatedField(many=True, read_only=True) def to_representation(self, instance): representation = super().to_representation(instance) print(representation) return representation class Meta: model = Location fields = ['location_name'] Now, I'm trying to access the serialized data, so I can run my logic on it and return the response in the view. when trying to access serialized data in the shell, I get the following error: >>> from LocationModel.serializers import LocationSerializer >>> from LocationModel.models import Locations >>> from LocationModel.models import Location >>> queryset = Location.objects.all() >>> serialized_data = LocationSerializer(data,many=False) >>> print(serialized_data) LocationSerializer(<Location: yovel,Point object (1)>): >>> serailizer.to_representation(data) AttributeError: 'LocationSerializer' object has no attribute 'location_name' The framework's docs kind of jump into deep water in this topic (at least for me) So, I have two questions: … -
Forcing a user to upload an image during registration Django
I've extended my user model with profile, and have made it so that a profile object gets made when user does. Now, I am trying to add my own fields during registration, description and photo. However, I am having trouble doing that. Error: AttributeError at /register/ type object 'Profile' has no attribute 'USERNAME_FIELD' Request Method: GET Request URL: http://localhost:8000/register/ Django Version: 3.0.5 Exception Type: AttributeError Exception Value: type object 'Profile' has no attribute 'USERNAME_FIELD' Exception Location: /Users/papichulo/Documents/DatingApp/11_env/lib/python3.7/site-packages/django/contrib/auth/forms.py in __init__, line 109 Python Executable: /Users/papichulo/Documents/DatingApp/11_env/bin/python Python Version: 3.7.3 Python Path: ['/Users/papichulo/Documents/DatingApp', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/papichulo/Documents/DatingApp/11_env/lib/python3.7/site-packages'] views.py def register(request): form1 = UserForm(prefix="user") form2 = ProfileForm(prefix="profile") if request.method == "POST": form1 = UserForm(request.POST, prefix="user") form2 = ProfileForm(request.POST,request.FILES, prefix="profile") if form1.is_valid() and form2.is_valid(): # Save form1 with no commit user = form1.save(commit=False) user.username = form1.cleaned_data['username'] user.email = form1.cleaned_data['email'] # user.email = form1.cleaned_data['email'] user.save() user.profile.user = user user.profile.description = form2.cleaned_data['description'] user.profile.photo = form2.cleaned_data['photo'] user.profile.save() # Some return statement you choose return redirect('dating_app:home') # *** return render(request, 'dating_app/register.html', {"form1": form1, "form2": form2}) models.py from django.contrib.auth.models import User from django.db import models from dating_project import settings from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100) description … -
How to use filter_horizontal in non m2m fields?
I have a model which is a MultipleChoiceField it needs to be populated with the attributes from another model, however, I'd like to have that turned into a filter_horizontal-esk field. As you can tell it's not a M2M relation hence I can't use filter_horizontal there. Is there anyway I can override the change_form.html and serve custom HTML with this. I wouldn't mind a JS based solution as well. I am able to send the data (the attributes of other model) using render_change_form method. models.py class MyModel(models.Model): choice_field = models.CharField() forms.py class MyModelForm(forms.ModelForm): choices = (('adqt_homescreen_id', 'adqt_homescreen_id'), ('entity_name', 'entity_name'), ('display_name', 'display_name'), ('image', 'image'), ('category', 'category'), ('cat_order', 'cat_order'), ) choice_field = forms.MultipleChoiceField(choices=choices) admin.py class MyModelAdmin(admin.ModelAdmin): change_form_template = 'mychangeform.html' class Media: js = ('myjs.js', ) def render_change_form(self, request, context, *args, **kwargs): field_list = list() for i in AdqtHomescreen._meta.get_fields(): if hasattr(i, 'attname'): field_list.append(i.attname) elif hasattr(i, 'field_name'): field_list.append(i.field_name) extra_context = field_list context.update({'filterFields': field_list}) return super(DqRulesConfigAdmin, self).render_change_form(request, context, *args, **kwargs) mychangeform.html {% extends "admin/change_form.html" %} {% block after_field_sets %}{{ block.super }} <p id="filterFields">{{filterFields}}</p> {% endblock %} -
vue JS get too much responses from django channles
I'm writing backend using Django channels and my friend that does Frontend get a bug when I send him response using group_send every user receives as many answers as users are in the group. class RoomChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): try: async_to_sync(self.channel_layer.group_discard)(self.room_name+'chat', self.channel_name) except AttributeError: pass self.room.chat.users.remove(self.user) message = { "response": 'User has disconnected', 'username': self.user.username, 'timestamp': str(datetime.now().strftime("%d.%m.%y %H:%M")), } async_to_sync(self.channel_layer.group_send)( self.room_name+'chat', { 'type': 'send_users', 'data': message, } ) def receive(self, text_data): text_data_json = json.loads(text_data) if 'type' in text_data_json.keys() and text_data_json['type'] == 'authenticate': token = text_data_json['payload']['token'] self.user = Token.objects.filter(key=token).first().user self.room_name = self.scope['path'].split('/')[5] self.room = Room.objects.filter(name=self.room_name).first() async_to_sync(self.channel_layer.group_add)(self.room_name+'chat', self.channel_name) self.users_in_room = self.room.users.all() for msg in self.room.chat.last_messages( self.room.chat.messages_on_connect_count ): self.send(text_data=json.dumps({ 'response': 'new message', 'message': msg.content, 'username': msg.author.username, 'timestamp': msg.timestamp.strftime("%d.%m.%y %H:%M"), 'receivers': msg.get_receivers() })) self.room.chat.users.add(self.user) print(f'{self.user.username} connected') message = { "response": 'User is successfully connected', 'username': self.user.username, 'timestamp': str(datetime.now().strftime("%d.%m.%y %H:%M")), } async_to_sync(self.channel_layer.group_send)( self.room_name+'chat', { 'type': 'send_users', 'data': message, } ) elif text_data_json['request'] == 'new message': print('new message') recievers = [] usernames_in_room = [] for user in self.users_in_room: usernames_in_room.append(user.username) for part in text_data_json['message'].split(): if part[0] == '@': if part[1:] in usernames_in_room: user = self.users_in_room.filter(username=part[1:]).first() if user and user != self.user: recievers.append(user) message = Message.objects.create( author=self.user, content=text_data_json['message'], ) message.receivers.set(recievers) message.save() self.room.chat.messages.add(message) message = { … -
Is there any way to use Pagination with django-filter?
Whenever I press on a link to the next page (which is a get request), the filter is bypassed and I get the corresponding page for the entire list (without the filter). Example, if I am on page 1 for a filtered list and I click next, I land on page 2 for the entire unfiltered list. In models.py, class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=get_all_category_choices()) In filters.py, import django_filters from .models import Person class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] In views.py, def show_all_persons_page(request): context = {} filtered_person_list = PersonFilter( request.GET, queryset=Person.objects.all() ) context['filtered_person_list'] = filtered_person_list paginated_filtered_person_list = Paginator(filtered_person_list.qs, 3) page_number = request.GET.get('page') person_page_obj = paginated_filtered_person_list.get_page(page_number) context['person_page_obj'] = person_page_obj return render(request, 'app1/show_all_persons_page.html', context) In app1/show_all_persons_page.html, <form method="get"> {{ filtered_person_list.form.as_p }} <button type="submit">Search</button> </form> {% for person in person_page_obj %} <img src="{{ person.picture.url }}" width="240"> <h2> {{person.name}} <br> {{person.gender}} <br> {{person.category}} <br> </h2> <br> {% endfor %} <div class="pagination"> <span class="step-links"> {% if person_page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ person_page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ person_page_obj.number }} of {{ person_page_obj.paginator.num_pages }}. </span> {% if person_page_obj.has_next %} <a href="?page={{ person_page_obj.next_page_number }}">next</a> <a href="?page={{ … -
date field in a Django model is not found in the returning list
I have a function to return all Django model fields as follow: The model as follow: class Posts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=64) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return "%s %s %s %s %s %s %s" % (self.id, self.category, self.sub_category, self.title, self.content, self.date_created, self.date_updated, ) class Meta: verbose_name_plural = "Post" The function inside of view function as follow: def get_forums(): ret = [] forums = Posts.objects.all().order_by('-date_updated') print(forums) for forum in forums: value = model_to_dict(forum, fields=[field.name for field in forum._meta.get_fields()]) value['user'] = {'username': forum.user.username, 'id': forum.user.id} ret.append(value) print(ret) return ret The output of first print: [<Posts: 164 cars Toyota 49 First post title This is the content of the first post 2020-04-05 14:56:25.192988+00:00 2020-04-05 14:56:25.193046+00:00>, <ForumsPosts: 163 cars Toyota this is the second post title This is the content of second post 2020-04-05 14:32:10.217224+00:00 2020-04-05 14:32:10.217351+00:00>] The output of second print: [{'id': 164, 'user': {'username': 'saleh', 'id': 1}, 'category': 4, 'sub_category': 49, 'title': 'First post title', 'content': 'This is the content of the first post '}, {'id': 163, 'user': {'username': 'saleh', 'id': 1}, 'category': 4, 'sub_category': 49, 'title': 'this … -
Make IntegerField as uniqueue in Django
I have a Model(MyClass) and this Model has some existing data. Now i want to add a auto increment column. ***Id is already there in model and this is auto increment First Approach:- i have created two migrations. in first migration i have passed default value as zero and in second migration i have passed below function as default. class MyClass(models.Model): def get_next_store_code(): ''' Returns the next value for the `code` field''' last_value = Store.objects.all().order_by('code').last() if last_value is None or last_value.code is None: return 1123 return last_value.code + 1 code = models.IntegerField(default=get_next_store_code) Now my friend told me that get_next_store_code can generate two same values.I told him like sql handle race case also but he said that first django will perform read operation and then write operation so it is possible that in read operation it can read same value for two request. Now i am trying to store default value as NULL code = models.IntegerField(default=None) so i can make it as unique but i am getting following error. django.db.utils.IntegrityError: column "code" contains null values -
How to use Django formset to update tables with foreign key
I have : 1 - two models: client models and contact model (foreign key) 2 - two forms one for the client and the other for the contact What I trying to do here, update the client table with his contact on the same view, so I have to get the contact data from the client data (foreign key), after that display both and update them using the update method. The mains difficulties that I facing is how to get the child model data from the parent model and update them I have been told that Django Formset would do the thing if anyone knows how to implement it in this context I would be grateful, thanks models.py : class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def client_update(request,slug): client = get_object_or_404(Client_Data, slug=slug) if request.method == 'POST': form = ClientForm(request.POST, instance=client) else: form = ClientForm(instance=client) return save_client_form_update(request, form,'Client_Section/partial_client_update_update.html') def save_client_form(request, form,Contact_form, template_name): data = … -
Django-channels Error during WebSocket handshake: Unexpected response code: 404
I was able to use django-channels but when I wanted to move with Nginx, django-channels stopped working. I am getting this error: WebSocket connection to 'ws://localhost/ws/chat/room_name/' failed: Error during WebSocket handshake: Unexpected response code: 404 What I tried: I updated Nginx config for location / Here is my Nginx.conf upstream app { ip_hash; server app:8000; } server { client_max_body_size 100M; listen 80; server_name localhost; location / { proxy_pass http://app; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } location /static/admin { alias /app/static/admin/; } location /static/ { alias /app/static/; } } and here is my nginx in docker-compose.yml: nginx: container_name: "ngnix_master" image: nginx:latest ports: - 80:80 volumes: - ./app:/app - ./config/ngnix:/etc/nginx/conf.d - ./static:/static/ depends_on: - app -
axios.post to Django ConnectionResetError: [Errno 54] Connection reset by peer
I am going mad over a seemingly very easy task: performing a post request to a django server with a React app. post request (in React): static searchProducts(query) { console.log(queryString.stringify({'search_key':query})) const requestBody = { search_key: query } const config = { crossDomain: true, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*' } } return axios.post(API_ROUTE+'/search/', queryString.stringify(requestBody), config) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error); }); } function in Django backend: @csrf_exempt def search(request): if request.POST['search_key']: req=request.POST else: req=json.loads(request.body) if req['search_key']: if (req['search_key'][-1]) == " ": key=req['search_key'][:-1] else: key=req['search_key'] vector = SearchVector('name','brand','family','sub_family',config='italian') query = SearchQuery(key,config='italian') keys_array = key.split(" ") print(key) # rs = Product.objects.annotate(search=vector).filter(search=key) # rs = Product.objects.annotate(search=vector).filter(search__icontains__in=keys_array) q = Q() for word in keys_array: q |= Q(search__icontains = word) q |= Q(search=key) rs= Product.objects.annotate(search=vector).filter(q) rs=rs.annotate(rank=SearchRank(vector, query)).order_by('-rank').values() print(rs) return JsonResponse({'response':list(rs)}) Please note that the backend does print correctly rs, but then it trows the following error: ConnectionResetError: [Errno 54] Connection reset by peer On the FE, the error is: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/search/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. What am I doing wrong? I am going crazy over … -
NoReverseMatch / Django / WebBlog
I am trying to attach the ID from the database to the Realting post. I don't know what's wrong. Tested it several times, but for me it looks like all the necessary things are connected. Maybe you can check and scan the logical path. I always get this error. Reverse for 'post' with keyword arguments '{'post_id': 2}' not found. 1 pattern(s) tried: ['blog/post/<int:post_id$'] Code is linked below. Ideas whats wrong? Models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=250) created_at = models.DateTimeField(default=timezone.now) def get_url(self): return reverse('blog:post', kwargs={'post_id': self.id}) views.py def post_view(request, post_id): post = get_object_or_404(BlogPost, id=post_id) return render(request, 'blog/post.html', {'post': post}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.index, name='blog'), path('<str:username>/timeline/', views.timeline_view, name='timeline'), path('create/', views.create_post_view, name='create'), path('post/<int:post_id', views.post_view, name='post'), ] timeline.html {% extends 'blog/base.html' %} {% block blogContent %} {% if request.user.is_authenticated %} <form action="{% url 'blog:create' %}" method="post"> {% csrf_token %} {{ post_form }} <button type="submit">Senden</button> </form> {% endif %} {% for post in posts %} <p> {{ post.message }} - {{ post.created_at }} <a href="{{ post.get_url }}">#{{ post.id }}</a> </p> {% empty … -
django mezzanine customizing user
In django I expand the user model and mezzanine account profile model like this :AUTH_USER_MODEL=“App01.NewUser” ACCOUNTS_PROFILE_MODEL=“App02.MyProfile” But when I sign up a new account, the fields I add in User Model were blank.What should I do to deal with it? Thanks for answering my question! -
Where is the invalid syntax? Getting SyntaxError line 24
urlpatterns= [ url (r'^admin/', admin.site.urls) ** url (r'^about/$', views.about),** url (r'^$', views.homepage), ] ..urls.py",line 24 url (r'^about/$',views.about, SyntaxError: invalid syntax Followed tutorial and this is what the guy wrote, and keep getting error. -
Allowing Users to choose assignment View flow
I am currently working on a project with django and viewflow . I wish to allow the creator of a process to assign the task to other users , AKA allowing them to search and select from a drop down box. However there hasn't been much resources on how to go about that , would appreciate if anyone can point me in a direction , thank you!