Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework ModelSetView POST not allowed
I am trying to learn how to use Django REST framework. I want to make a very simple API using ModelViewSet. I've followed the docs but it's not exactly clear to me if ModelViewSet provides an automatic mapping from its create to POST when doing router.register(r"polls", QuestionViewSet, basename="polls") I keep trying my endpoint: curl --location --request POST 'http://localhost:8005/polls/' \ --header 'Content-Type: application/json' \ --data-raw '{ "question_text": "how it do", "pub_date": "01-01-2021" }' But it returns: {"detail":"Method \"POST\" not allowed."} Models: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) Serailizer and ModelViewSet: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ["id", "question_text", "pub_date"] class QuestionViewSet(viewsets.ModelViewSet): queryset = Question.objects.all() serializer_class = QuestionSerializer() Routers: from django.conf.urls import re_path, url, include from django.urls import path from rest_framework import routers from .question import QuestionViewSet router = routers.DefaultRouter() router.register(r"polls", QuestionViewSet, basename="polls") urlpatterns = router.urls -
name 'InMemoryUploadedFile' is not defined in django model?
So basically I have a django model which has a filefield. I'd like to resize images that get submitted and I have this code here to do that def save(self, *args, **kwargs): img = Image.open(self.media) output = BytesIO() original_width, original_height = img.size aspect_ratio = round(original_width / original_height) desired_height = 100 desired_width = desired_height * aspect_ratio img = img.resize((desired_width, desired_height)) img.save(output, format='JPEG', quality=90) output.seek(0) self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) super(Post, self).save(*args, **kwargs) The error im getting is "name 'InMemoryUploadedFile' is not defined". How do I fix this? Also a side question. The model also takes in videos. How would I resize a video? This is just a side question the InMemoryUploaded is the main question. Thank you! -
How can I make my graphene-python API respond faster?
I've built a python/daphne/django/graphene server, and did everything I could to optimize my queries -- cached db queries in Redis so that they are basically free, and eventually came to find that even with a very small graph schema I still see a >200ms overhead inside of graphql-core, evidently parsing my query. I come from a REST-api-centric worldview, and in this case the stack decisions were out of my hands. I'm just trying to make it work. Queries that a normal django view should return in ~20ms still take ~250ms. Given that I'm consistently sending the same few queries, it would be fantastic to skip the repetitive parsing of the same query over and over again. So, I'm curious what the Python graphql people do, to make their service perform, and to begin with, I'd like to know: Should I just expect to live with that query overhead? Can I improve by doing something like switching from Daphne to Uvicorn, or even mod_wsgi (am not doing any async stuff) Is there any way to circumvent repeated parsing of the same query? thanks for your time and assistance. -
Cannot saving form in django
So i'm using the auth.models.user to create user model and by default it's passing ('first_name', 'last_name', 'username', 'email', 'password1', 'password2'). and the forms.py: class UserSignUpForm(UserCreationForm): class Meta: fields = ('first_name','last_name','username', 'email', 'password1', 'password2') model = user def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = "Email Address" i try to allowing user to edit their personal information from all avaliable fields in UserSignUpForm, except the password fields. so i created this views.py (function based view): def edit_account(request): user = request.user form = UserSignUpForm(instance=user) if request.method == 'POST': form = UserSignUpForm(request.POST, instance=user,) if form.is_valid(): form = UserSignUpForm(instance=user) form.save() messages.success(request, 'Your account has been updated.') return redirect('/dashboard/profile/') context = {'editform':form} return render(request, 'accounts/updateaccounts.html', context) tried submit the specific field form like{{editform.first_name}} after passsing it in the html page (because i dont want to user be able edit their password) but it still not update/saving the new user data. is there any method so it can be save? thanks -
Pandas & Jango - How to create a DataFrame filter from multiple user inputs without using string executable
I am building a website where users can graph data in a dataframe and apply filters to this data to only plot information they are interested in, as shown below Right now I am having trouble figuring out a way to take the filters a user inputs in the fields above and using those inputs to filter the dataframe. Since the user can create an unbounded number of filters, I decided to use a for loop to build an executable string that contains all of the filters in one variable that is shown below column = (value selected in "Select Parameter", which corresponds to a column in the dataframe) boolean = (value selected in "Select Condition" e.g., >, <, >= ect.... user_input = (value user inputs into field e.g., 2019 and Diabetes) executable = 'df = df[df[' + column1 + '] ' + boolean1 + user_input1 + ' and ' + 'df[' + column2 + '] ' + boolean2 + user_input2 + ' and '..... exec(executable) While this method works, it leaves my code very vulnerable to injection. Is there a better way of doing this? -
Error in importing a module in rest_framework, while creating rest API using Django framework
I created a web application using Djanjo framework, and then when I am trying to create a REST API, after configuring all the relevant files such as models.py, admin.py, serializers.py, views.py, and settings.py. It shows an error while importinng the model from rest_framework. The traceback is as follows: *Traceback (most recent call last): File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\site-packages\django\urls\resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\dmandal\AppData\Local\Continuum\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen … -
django - How to get parameters from "def save" function
Is there a way to get parameters from the "save" function? Even if I shoot debug, models.py def save(self, *args, **kwargs): super().save(*args, **kwargs) in postman url http://127.0.0.1:8000/photo?file_h=200&file_w=800 I have to save using "file_h=200&file_w=800". Adding "request" gives me an error. -
decoding to str: need a bytes-like object, HttpResponse found when using Render function in Django
I'm trying to return a error page if a file is not found, by using the render shortcut after the FileNotFoundError and it doesn't work. In view.py I have: return render(request, "encyclopedia/entry.html", { "entry":util.get_entry(request, title) }) In util.py I have: def get_entry(request, title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns error page. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: context = {} context['title_name']="Title name" return render(request,'encyclopedia/error.html',context,content_type='text/html') #return "The page '"+str(title)+"'"+" was not found." I want to return a html page but it gives me this error Type error: decoding to str: need a bytes-like object, HttpResponse found I'm a beginner and I'm really stuck on this code and I don't know how to change the type to a 'byte-like object' -
In DjangoRestFramework, is it expected that a MultipleChoiceField default attribute is ignored? [duplicate]
I have the following request serializer using a MultipleChoiceField class CompletedOrderStatusDefault: requires_context = False def __call__(self, serializer_field): # -----> this code is never hit?! return [OrderStatus.COMPLETED] class OrderListRequestSerializer(serializers.Serializer): ... order_statuses = serializers.MultipleChoiceField( required=False, default=CompletedOrderStatusDefault, choices=AllowedOrderStatus.ALLOWED, ) the code in the call is never hit during a request and the value for the field is instead an empty set. Is this a bug I should raise or am I wrong to expect that the default is used for this MultipleChoiceField? if so, how should the default be set when the parameter is unspecified in an incoming request? -
python sorted(regex expr with for loop if statement)
I'm having tough time understanding def list_entries function . what does _, mean? and inside sorted() there is a regex expr which means replace .md with empty string and then it runs a for loop? it's possible to run a for loop in sorted after regex expression? and lastly if statement checking if it file ends with .md? I just want to know how this is all put together into sorted() Thank you for your help. import re from django.core.files.base import ContentFile from django.core.files.storage import default_storage def list_entries(): _, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename)for filename in filenames if filename.endswith(".md"))) -
Adding a button to export to a csv/xlsx file on Wagtail Dashboard
I am attempting the solution mentioned in this stack overflow post (Adding a button to Wagtail Dashboard) however the solution might be outdated, or at least it doesn't work for me and I'm unsure why. Goal: Be able to export a object's data to csv First, the button HTML code had to be slightly adjusted to be formatted correctly like so: {% extends "modeladmin/index.html" %} {% block header_extra %} <div class="right"> <div class="addbutton" style="margin-left: 2em;"> {% include "modeladmin/includes/button.html" with button=view.button_helper.export_button %} <a href="#" class="button bicolor icon icon-download">My button</a> </div> </div> {{ block.super }}{% comment %}Display the original buttons {% endcomment %} {% endblock %} and then I copied and pasted the views and helper functions: from django.contrib.auth.decorators import login_required from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.translation import ugettext as _ from wagtail.contrib.modeladmin.helpers import AdminURLHelper, ButtonHelper from wagtail.contrib.modeladmin.views import IndexView class ExportButtonHelper(ButtonHelper): """ This helper constructs all the necessary attributes to create a button. There is a lot of boilerplate just for the classnames to be right :( """ export_button_classnames = ['icon', 'icon-download'] def export_button(self, classnames_add=None, classnames_exclude=None): if classnames_add is None: classnames_add = [] if classnames_exclude is None: classnames_exclude = [] classnames = self.export_button_classnames … -
Django issue running manage.py on Mac
I am trying to run a project in atom using a virtual environment and I keep getting an error in regards to the manage.py file. File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I've searched for solutions all over and most people seem to resolve it by using python3 manage.py runserver in the virtual environment instead of python manage.py runserver but that did not work for me. Any suggestions on this? -
Render html tags in Django send email
I found a tutorial on how to send email with Django. This works as intended. However, when I apply html tags, it is being read as a string. Probably because of render_to_string function, but any ideas how to proceed on this? This is my view to send email: current_site = get_current_site(request) mail_message = render_to_string('send/email_template.html', { 'name' : name, 'domain':current_site.domain, }) And this is my email template: {% autoescape off %} <html> Hi {{ name }}, <div class="form-control">......</div> </html> {% endautoescape %} As for the result, it is this: <html> Hi Name, <div class="form-control">......</div> </html> -
How to use Django's APIRequestFactory with an array of objects?
I have the following test def test_bulk_post(my_faker,factory): snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}] assert factory.post('/snippets/',snippets) == True I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request. Right now this gives me: /venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart() *** AttributeError: 'list' object has no attribute 'items' so its not expecting a list.. But I want to give it one. How do I do that? -
Foreign Key with db_constraint= False and postresql: foreign key appears to refer to wrong parent field
I am preparing tables for use in an analytics tool (Microsof Power BI). It would be helpful to show relationships between the tables to assist in report building. However, I don't want to use foreign keys with constraints because the method of data updating and integrity checking doesn't need constraints, and it will actually get in the way. Some of the alternate backends this code supports are for cloud databases that don't offer real foreign keys. I mention that because it means I am trying to define a foreignkey field like this: order_guid = models.ForeignKey("Dear_sales_header",to_field="order_guid",db_constraint=False,on_delete=models.DO_NOTHING) The migration file has this: operations = [ migrations.AlterField( model_name='sales_fact', name='order_guid', field=models.ForeignKey(db_constraint=False, on_delete=django.db.models.deletion.DO_NOTHING, to='dear_zoho_analytics.Dear_sales_header', to_field='order_guid'), ), ] This table is routed to a different database python manage.py migrate --database=dear_analytics does indicate that the migration file was applied (it is 0026) Applying dear_zoho_analytics.0026_auto_20210217_2245... OK But when I inspect the postgresql schema in my IDE, the column in sales_fact is renamed to order_guid_id so it looks like I have done something wrong because this seems to reference the id field of the "parent table" dear_sales_header yet I need it to refer to dear_sales_header.order_guid which is unique but not the primary key. -
Get Response Cookies from Django redirect to SAP application VueJS
I'm working with Django 3.1 backend and Vue js frontend frameworks. The authentication is done by JWT tokens, however, I'm implementing the SSO authentication with SAML. The problem arises when I have to pass the JWT Tokens to VueJs after the SAML authentication is done. Then, the flow is something like this: View in frontend has a button to authenticate with SAML. It is redirected to http://backend/idp?=myIdp Backend go to IDP and IDP prompts to the user the credentials box. IDP redirects the successful SAML response to the backend. Backend generates the JWT for the session, log out the user, and redirected with response cookies for JWT tokens. The frontend view is shown to the user but I cannot get the cookies In the following diagram, I surrounded the part where I'm stuck (credits: https://jcbaey.com/oauth2-oidc-best-practices-in-spa) My redirected code looks like this: class Saml2JwtView(LoginRequiredMixin, RedirectView): url = "http://proxy.localhost/candidates/myServices" def get(self, request, *args, **kwargs): # Obtain JWT tokens for logged in user refresh = RefreshToken.for_user(request.user) response = super().get(request, *args, **kwargs) # Set JWT cookies response.set_cookie("access", str(refresh.access_token)) response.set_cookie("refresh", str(refresh)) # Logout session created by SAML logout(request) return response My networks show me that I'm setting the set-cookie and the 302 redirected to my … -
How to test Django Custom Forms/Views with .save() and .is_valid() form methods
I'm developing a web application and beginning to write tests for an app within the project 'users'. I'm using Python Unit-Testing and TestCase with coverage. I have approximately 83% tested so far however I can't seem to figure out how I should be testing the form.save() method. In addition to this, form.is_valid() seems to never be evaluating to true in my views.py file shown below: Views.py from django.shortcuts import render, redirect from users.forms import RegistrationForm, LoginForm from django.contrib import messages from django.contrib.auth import login, logout, authenticate # Register view def user_register(response): if response.method == 'POST': form = RegistrationForm(response.POST) if form.is_valid(): # Can be saved once valid form.save() # Clean inputs username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') messages.success(response, f'Account created for {username}') return redirect('home') else: form = RegistrationForm() return render(response, 'users/register.html', {'form': form}) I can't post an image here but running coverage with live-server, it shows that everything after the 'if form.is_valid()' is highlighted in red as too is the single line in the else condition 'form = RegistrationForm()' This is my testing code: test_views.py from django.test import TestCase, Client from django.urls import reverse from django.contrib.auth import get_user_model from users.forms import RegistrationForm … -
What is the best way to represent this spreadsheet as a django model
I have been scratching my head, thinking about how to put this as a Django model, my concern is the column that is used to group the rest of the data. -
django.db.utils.OperationalError: no such table: characters_race
I try to run python manage.py migrate or even python manage.py makemigrations characters and i still get errors, I tried to search all of the files for this table or even a similar one and i found nothing, I even tried to delete "db.sqlite3" and "ptcache" and try the lines again and still the same error. Here is the Traceback: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( errors.extend(model.check(**kwargs)) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 1264, in check *cls._check_fields(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 1343, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 836, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 482, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\related.py", line 100, in check *super().check(**kwargs), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line 200, in check *self._check_choices(), File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line 245, in _check_choices if not self.choices: File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 291, in __bool__ self._fetch_all() File "C:\Users\User\anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) … -
Django - User to User messaging on a website
I (and my team) am working on a university senior project which is something like a medical web app, I need to implement user to user messaging feature, like the patient to a doctor messaging and vice versa, would Django channels work for this feature? if not could you recommend anything that might help in this case? Thanks -
retrieve, update and delete by pk or id
I am using Django REST for my API, I have 2 questions: In my urlpatterns, in the retrieve, update and delete endpoints, I want to filter using an id. For some reason, I am not able to. In the update endpoint, I do not see the JSON data that is in the database Here is my views.py: from django.http import HttpResponse from django.shortcuts import render from rest_framework.response import Response from .serializers import mySerializer from .models import myModel from rest_framework import generics # Create your views here. class CreateShipment(generics.CreateAPIView): queryset = myModel.objects.all() serializer_class = mySerializer class ListPoint(generics.ListAPIView): queryset = myModel.objects.all() serializer_class = mySerializer class RetrievePoint(generics.RetrieveAPIView): queryset= myModel.objects.all() serializer_class= mySerializer lookup_url_kwarg = "id" class UpdatePoint(generics.UpdateAPIView): queryset = myModel.objects.all() serializer_class = mySerializer lookup_url_kwarg= "id" class DeletePoint(generics.DestroyAPIView): queryset = myModel.objects.all() Here is my urls.py: from django.urls import path from rest_framework.routers import DefaultRouter from .views import * urlpatterns = [ path('api/create/', CreatePoint.as_view()), path('api/list/', ListPoint.as_view()), path('api/retrieve/<int:id>', RetrievePoint.as_view()), path('api/update/<int:id>/', UpdatePoint.as_view()), path('api/delete/<int:id>/', DeletePoint.as_view()), ] Thanks. -
How do I dynamically generate link tags in header based on installed languages in Django?
For example, I have multiple languages installed and would like to dynamically generate the link tags. Preferably in my base.html's header. <link rel="canonical" href="https://example.com/{{ LANGUAGE_CODE }}{{ URL }}"/> <link rel="alternate" href="https://example.com/da{{ URL }}" hreflang="da"> <link rel="alternate" href="https://example.com/de{{ URL }}" hreflang="de"> <link rel="alternate" href="https://example.com/en{{ URL }}" hreflang="en"> This is what I am currently using but would there be a way to do this by looping all the installed languages so I wouldn't need to update the HTML each time I add another language? -
Django drf customer user model authentication over https
I have a Django project, where I'm using DRF (Django Rest Framework) with custom user model authentication. I'm using rest framework TokenAuthentication. Everything works fine over http where I send authentication request with username/password and I get back token successfully or if I send request with token and I get my data successfully. I'm in need to set up https connection (with proper ssl certificate). I already got ssl certificate installed (Ubuntu Apache2 setup) using wsgi. However once my https is enabled and I send auth request over https connection, I don't get back token and I get 404 Unauthorized. I already have below in my settings.py file ENABLE_SSL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'users', 'api', 'corsheaders' ] AUTH_USER_MODEL = 'users.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100, 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } REST_AUTH_SERIALIZERS = { 'TOKEN_SERIALIZER': 'users.serializers.CustomTokenSerializer', } REST_SESSION_LOGIN = True CORS_ORIGIN_ALLOW_ALL=True Can someone please tell me if I'm missing anything -
how can make hashtag clickable and show it in the post in Django?
User can make hashtag. Now I want to make hashtag clickable. Bellow is my Models.py for Hashtag: class Hashtag(models.Model): hashtagname = models.CharField(max_length=3000, blank=True, null=True) hashtagcount = models.IntegerField(null=True, blank=True) post_pk = models.ManyToManyField(PostUser) atetime = models.DateTimeField(auto_now_add=True) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) user_pk = models.IntegerField() and in my views.py I get all the hashtags and send it by dictionary to html as bellow codes: mosttrending = Hashtag.objects.all().order_by('-hashtagcount')[:10] and already I have a model for all the Posts as bellow class PostUser(models.Model): posttype = models.CharField(max_length=3000, default='postuser') content = models.TextField(null = True, blank= True) media_image = models.FileField(null = True, blank= True) media_video = models.FileField(null = True, blank= True) per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) datetime = models.DateTimeField(auto_now_add=True) like = models.IntegerField(null=True, blank=True) comment = models.IntegerField(null=True, blank=True) share = models.IntegerField(null=True, blank=True) user_pk = models.IntegerField() And in my html with a for loop I get all the PostUser: {% for readposts in readposts %} <p class="card-text">{{readposts.content|linebreaks}}</p> {% endfor %} How Can I make the link for hashtag and when a user click on the hashtag show the user the all the post? -
Why am I getting this "Converting circular structure to JSON\n --> starting at object with constructor" error?
I'm trying to build a like button in my React/Django/DjangoRestFramework social app, and I am getting this error when I try to post a like to the backend: "Converting circular structure to JSON\n --> starting at object with constructor 'HTMLButtonElement'\n | property '__reactFiber$295h0s4sjuq' -> object with constructor 'FiberNode'\n --- property 'stateNode' closes the circle" Here is my current code: AddLike.js import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { withRouter } from "react-router-dom"; import { addLike, deleteLike } from "./LikeActions"; function LikeButton(props) { return ( <button onClick={props.onClick}> Like </button> ) } function LikedButton(props) { return ( <button onClick={props.onClick}> Liked </button> ) } class AddLike extends Component { constructor(props) { super(props); this.state = { like: false, } } onChange = e => { this.setState({ [e.target.name]: e.target.value }); }; handleAddLike = id => { const post = { post: id }; this.setState({like: true}) this.props.addLike(post); }; handleDeleteLike = id => { const post = { post: id }; this.setState({like: false}) this.props.deleteLike(post); } render() { const like = this.state.like; let button; if (like) { button = <LikedButton onClick={this.handleDeleteLike}/>; } else { button = <LikeButton onClick={this.handleAddLike}/>; } return ( <div> {button} </div> ); } } …