Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Test (StaticLiveServerTestCase) returns 404
I have a project which uses Angular and Django and I am experiencing a weird behavior when I test my application using StaticLiveServerTestCase and Selenium. When I start testing it everything seems to work but, if I refresh the main page I receive a 404. So, if I test without base url it works, but once Angular adds the base url the test returns 404: http://127.0.0.1:8000/baseURL/test My URL is defined as follows: re_path('test', views.index, name='index') So, summarizing, when I test http://127.0.0.1:8000/test it works, but if I test http://127.0.0.1:8000/baseURL/test it does not -if I run my app normally, buth URLs work. According to my novice knowledge and as the url pattern is defined both urls should work. Obviously I am missing something else. Thanks in advance. Note: Test class if defined as follows: class Tests(StaticLiveServerTestCase): def set_chrome_options(cls): options = Options() options.add_experimental_option("useAutomationExtension", False) return options @classmethod def setUpClass(cls): cls.host = "127.0.0.1" cls.port = 8000 super(Tests, cls).setUpClass() cls.selenium = webdriver.Chrome(executable_path=settings.DRIVER_PATH, options=cls.set_chrome_options(cls)) ... -
How to handle file processing request in Django?
I am making a Django Rest framework based server and in one of the request, I get an audio file from front-end, on which I need to run some ML based algorithm(I have script for same) and respond back to user with the result. Problem is that this request might take 5-10 seconds to execute. I am trying to understand following things: Will Celery help me reduce the workload on server, as in any case I need to wait for the result of the ML Algo and respond back to user. Should I create a different server to handle this type of request? Will that be a better approach? Also, is my flow of doing things correct. First, Upload the file to some cloud platform for storage and serialize the instance to get the url of file. Second run the script using celery and wait for the result. Third, Respond back with the result. Thanks for helping. -
How to retrieve Page content from streamfield in Wagtail?
So, I've created SolutionPage page and inside It's content there is short_portfolio block. I added several ProjectPage instances via Wagtail admin panel to PageChooserBlock. class SolutionPage(Page): ... content = StreamField([ ... ... ('short_portfolio', blocks.StructBlock([ ('title', blocks.CharBlock(required=False)), ('description', blocks.RichTextBlock(required=True)), ('projects', blocks.StreamBlock([ ('project', blocks.PageChooserBlock(ProjectPage)), ], required=False, max_num=4)), ])), ], blank=True, null=True, validators=[UniqueProjectsInShortPortfolioValidator()]) Now, I'm working on API view for PDF export and I need to extract all ProjectPage objects from a given SolutionPage import requests from django.conf import settings from django.http import HttpResponse from django.shortcuts import render from rest_framework import views from rest_framework.generics import get_object_or_404 from portfolio.models import ProjectPage from solutions.models import SolutionPage class PortfolioToPdfView(views.APIView): def get(self, request, *args, **kwargs): def get_404(): return HttpResponse( render( request=None, template_name='404.html', content_type="text/html" ), content_type='text/html' ) path = request.META['PATH_INFO'] if path.find('solutions') == -1: return get_404() slug = path[path[1:].find('/') + 2:] slug = slug[:slug.find('/')] solution_page = get_object_or_404(SolutionPage, slug=slug) short_portfolio = solution_page.content.stream_block.child_blocks["short_portfolio"] projects = [project.child_blocks["project"].target_model for project in short_portfolio.child_blocks["projects"]] ... response = HttpResponse(request, content_type='application/pdf') return response The problem is that in this way I can only extract something like a "schema" of the page but not it's actual content. TypeError at /solutions/ai-driven-machine-learning-software/portfolio-pdf/ 'StreamBlock' object is not iterable Debug variables -
manage.py flush not working during testing
I am using the tutorial on how to use Django Rest - React and it has some testing in it too. When I test it, error comes as: CypressError: cy.exec('npm run dev') timed out after waiting 60000ms. Because this error occurred during a 'before all' hook we are skipping the remaining tests in the current suite: 'Django REST framework / Rea...' Below is some part of the package.json, { "name": "django-drf-react-quickstart", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "flush": "pipenv run python ./project/manage.py flush --no-input", "e2e": "cypress open --project ./project/frontend/", "dev": "webpack --mode development ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js", "build": "webpack --mode production ./project/frontend/src/index.js --output ./project/frontend/static/frontend/main.js", "test": "echo \"Error: no test specified\" && exit 1" }, I think the issue is in flush part. I use virtualenv and I have tried many combinations like: run python ./project/manage.py flush --no-input virtualenv run python ./project/manage.py flush --no-input python ./project/manage.py flush --no-input I even tried installing pipenv, but to no use. Please help me with this. -
Django how to implement updateview in parent and child tables
I have two models class CustomUser(AbstractUser): role_name = models.CharField(max_length=100, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) super_id = models.IntegerField(default=1) class AdminDetails(models.Model): user = models.ForeignKey(CustomUser, default=1,unique=True,on_delete=models.CASCADE) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=200) and i have a form for creating/updating details in forms.py class AdminCreationForm(forms.Form): username = forms.CharField(label=_('Username')) password = forms.CharField(widget=forms.PasswordInput()) reenter_password = forms.CharField(widget=forms.PasswordInput()) email = forms.EmailField(label=_('Email')) first_name = forms.CharField(label=_('First Name')) last_name = forms.CharField(label=_('Last Name')) phone_number = forms.CharField(label=_('Phone Number')) address = forms.CharField(label=_('Address')) I have a update view in views.py like this . But can only update to single AdminDetails model only. class AdminUpdateView(UpdateView): fields = ('phone_number', 'address') model = models.AdminDetails template_name = 'accounts/admin_form.html' How can i update username ,first name along with this address in a single updateview ??? -
Approaching way for Many To Many Intermediate Model in Django Rest Framework
I would like to get your opinions is this approaching way correct? How can I do serializing m2m intermediate model better ? I would like to know how to combine Display and Create serializers.. models.py class Material(models.Model): name = models.CharField(max_length=120) class Product(models.Model): name = models.CharField(max_length=120) materials = models.ManyToManyField(Material, through='MaterialProduct') class MaterialProduct(models.Model): material = models.ForeignKey(Material, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) rate = models.FloatField(default=100) views.py class Products(APIView): def get(self, request, format=None): products = Product.objects.all() serializer = ProductDisplaySerializer(products, many=True) # Display return Response(serializer.data) def post(self, request, format=None): serializer = ProductCreateSerializer(data=request.data) # Create if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class MaterialSerializer(serializers.ModelSerializer): class Meta: model = Material fields = '__all__' class ProductMaterialRateSerializer(serializers.ModelSerializer): material = MaterialSerializer(read_only=True) material_id = serializers.PrimaryKeyRelatedField( write_only=True, source='material', queryset=Material.objects.all()) class Meta: model = MaterialProduct # attention!!! fields = ('material', 'material_id', 'rate') class ProductCreateSerializer(serializers.ModelSerializer): '''To create a product with existed material and a material rate(extra field) ''' materials = ProductMaterialRateSerializer(many=True) class Meta: model = Product fields = ('id', 'name', 'materials') def create(self, validated_data): showData(validated_data) materials_data = validated_data.pop('materials') product = Product.objects.create(**validated_data) for material_data in materials_data: MaterialProduct.objects.create( product=product, material=material_data.get('material'), rate=material_data.get('rate')) return product Displayed data: { "id": 29, "name": "product 4", "materials": [ { "material_id": 3, "rate": 30 }, { "material_id": 2, "rate": … -
Efficient way to remove duplicate slug from model in Django
In my Exam model slug field was not unique. But Now I want to make it unique. Soi added Unique=True constraint in my slug field, but in the database there are too many exam objects with same slug field. this causing problem in migrations I want to find an efficient way to find all duplicate slug and make it unique. suppose I have more than 10000 exams. -
react django rendering same content
I'm working on Django-react project and having issue with rendering React component on Django server. To be precise, React always render me the same content even if I change it. I'm using Webpack, Babel-loader and running it on localhost. project/templet/frontend/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django-React</title> </head> <body> <div id="app" class="columns"><!-- React --></div> {% load static %} <script type='text/javascript' src="{% static "frontend/main.js" %}"></script> </body> </html> Entry point: import ReactDOM from "react-dom"; import App from './components/App'; ReactDOM.render(<App/>, document.getElementById("app")); Scripts in package.json: "scripts": { "dev": "webpack --mode development ./frontend/src/index.js --watch ./frontend/static/frontend/main.js", "build": "webpack --mode production ./frontend/src/index.js --output ./frontend/static/frontend/main.js" } Babel config: module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; So, when I write some content in App component (eg. render div with "test") I can see it in my browser, but when I want to change it, and after refresing page, get the same content from div tag -
How to update JINJA template and add keyword args for custom filters functions
I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e. template = JINJA.from_string(text) The result template looks like this: Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',\n\n'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n \nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.\n\n')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:\n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button below\n'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.\n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:\n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])]) In the above template, there is a custom filter named as extra. As it is custom filter I will have to write a … -
HyperlinkedSorlImageField OSError: image file is truncated
I am using this serializer class for my Django-Rest-Framework API. (From: https://github.com/dessibelle/sorl-thumbnail-serializer-field) class HyperlinkedSorlImageField(serializers.ImageField): def __init__(self, geometry_string, options={}, *args, **kwargs): """ Create an instance of the HyperlinkedSorlImageField image serializer. Args: geometry_string (str): The size of your cropped image. options (Optional[dict]): A dict of sorl options. *args: (Optional) Default serializers.ImageField arguments. **kwargs: (Optional) Default serializers.ImageField keyword arguments. For a description of sorl geometry strings and additional sorl options, please see https://sorl-thumbnail.readthedocs.org/en/latest/examples.html?highlight=geometry#low-level-api-examples """ # NOQA self.geometry_string = geometry_string self.options = options super(HyperlinkedSorlImageField, self).__init__(*args, **kwargs) def to_representation(self, value): """ Perform the actual serialization. Args: value: the image to transform Returns: a url pointing at a scaled and cached image """ if not value: return None image = get_thumbnail(value, self.geometry_string, **self.options) try: request = self.context.get('request', None) return request.build_absolute_uri(image.url) except: try: return super(HyperlinkedSorlImageField, self).to_representation(image) except AttributeError: # NOQA return super(HyperlinkedSorlImageField, self).to_native(image.url) # NOQA to_native = to_representation Unfortunately it is failing sometimes on my server with this error: OSError: image file is truncated (44 bytes not processed) What can I do to fix this issue? I guess the image is somehow brocken. But I can view them all without a problem? -
Wrong default value for some dropdowns in django admin
I am seeing wrong default values for some dropdown fields in the Django admin, both in table and form view. Is there a known issue about this? The problem seems to be happening with some of my model fields, but not with other fields. Even though they are similarly defined. To be clear: the dropdown is properly populated, but the default value is wrong (does not correspond to the value in the database, but it is set to the non-defined value, which in the admin appears as ------ I am using Django 2.1 -
different request.POST on same page causing DeleteView error Django
My Django 2 app using Django Channels has a ThreadView or a page that displays a messaging thread between two users, with URL re_path(r"^(?P<username>[\w.@+-]+)", chat_views.ThreadView.as_view(), name='thread'), There is a text input form at the bottom of the page to submit a new message via request.POST which is handled via the ThreadView. I think the problem is arising when I try to put a request.POST delete form (DeleteView) on the page as well in order to delete the thread, URL path('<int:pk>/delete/', chat_views.ThreadDeleteView.as_view(), name='thread_delete'), When the delete form is submitted, I get the error DoesNotExist at /messages/2/delete/ User matching query does not exist. With these lines being cited at causing the error (from views.py and models.py) self.object = self.get_object() obj, created = Thread.objects.get_or_new(self.request.user, other_username) user2 = Klass.objects.get(username=other_username) The first line comes from the def post function on the ThreadView, and I'm not sure why that's being triggered. The thread isn't being deleted as when I go back to inbox, it's still there. I'm a beginner and may be getting this totally wrong so would appreciate any feedback. views.py class InboxView(LoginRequiredMixin, ListView): template_name = 'chat/inbox.html' context_object_name = 'threads' def get_queryset(self): return Thread.objects.by_user(self.request.user).exclude(chatmessage__isnull=True).order_by('-timestamp') class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url … -
Django Serializers with Foreign Key not working
I want to create a ListCreateView for my models. Here is are models - from django.db import models from training_service.models.advertiser import Advertiser class Config(models.Model): CONFIG_TYPE_CHOICES = ( ('DATA_DESCRIPTOR', 'DATA_DESCRIPTOR'), ('DATAFETCH', 'DATAFETCH'), ('BATCHSYSTEM', 'BATCHSYSTEM'), ('SPARKSYSTEM', 'SPARKSYSTEM') ) id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) config_type = models.CharField(max_length=100, choices=CONFIG_TYPE_CHOICES, blank=False) default_value = models.CharField(max_length=1000) class Meta: db_table = 'config' def __unicode__(self): return str(self.name) class AdvertiserConfig(models.Model): advertiser_id = models.ForeignKey( Advertiser, to_field="advertiser_id", db_column="advertiser_id", on_delete=models.DO_NOTHING) config_id = models.ForeignKey(Config, on_delete=models.CASCADE) value = models.CharField(max_length=1000) class Meta: db_table = 'advertiser_config' def __unicode__(self): return str(self.name) Below are the serializers for the models - class ConfigSerializer(serializers.ModelSerializer): class Meta: model = Config fields = ('name', 'config_type', 'value_type', 'default_value') class AdvertiserConfigSerializer(serializers.ModelSerializer): config_name = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = AdvertiserConfig fields = ('advertiser_id', 'config_name', 'value') But this is not working when I do a get on AdvertiserConfig I am not getting config_name in the response. And no error is thrown. Any idea what is wrong here? Also how would I do a create for AdvertiserConfig? -
noob question: how do I add the DJANGO_SETTINGS_MODULE from within a python script?
Apologies for a basic question but I honestly haven't found an actionable answer yet even though I'm sure this is a simple solve. I'm calling a python file which is part of a Django app (same folder as the models, views etc) from the command line, from a totally different working directory. The python file is called as a module and not as a package since I'm not using the "-m" argument. The python file imports from the models file, upon which I get a long Traceback through the init files etc ending in the below error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So I'm adding the following line in the python file before the import statement: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', "C:/Users/oktested/further_file_path/settings") Basically I'm putting the entire path to the settings.py file in there, without the .py extension. But upon doing this I get a ModuleNotFoundError: No module named 'C:\Users\oktested\'. How do I express the path to the settings.py file that already exists in my Django project? I am using Django 2.1 on Windows 10 FYI. -
Problems with Django admin view.py
Why is there an error? my error message (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '201903'') as cnt\n from lawyer y\n where y.lawyer_status = 'N'\n ' at line 5") @csrf_exempt def answer_stats_excel(request): if request.method == "POST": year = request.POST.get("year") month = request.POST.get("month") print(year+month) yearmonth = year+month stats_data = Lawyer.objects.raw( ''' select * from ( select y.lawyer_name, DATE_FORMAT(y.register_date, '%%Y-%%m-%%d') as reg_date, (select count(counsel_answer_idx) from counsel_answer where lawyer_idx = y.lawyer_idx and DATE_FORMAT(register_date, '%%Y%%m') = '%s') as cnt from lawyer y where y.lawyer_status = 'N' ) A order by A.cnt desc ''', [year+month]) dataF = DataFrame(stats_data) filename = '/folder/excel_.xlsx' dataF.to_excel(filename, 'Sheet1', index=False, engine='xlsxwriter') return redirect('/admin/visual/answer_stats') -
Unable to restore sql file in postgresql on windows
I'm trying to import sql file in postgresql but unable to do. I tried pgAdmin 4 to restore sql file. I get the error (pg_restore: [archiver] input file does not appear to be a valid archive). I've also tried to do this with the command prompt but unable to do. If I do D:\Program Files (x86)\PostgreSQL\9.1\bin>psql -h 127.0.0.1 -U postgres gorkha < D:/gorkha.sql It returns SET SET SET SET SET CREATE EXTENSION COMMENT REVOKE REVOKE GRANT GRANT -
How to login with username or email in Django | rest_framework_jwt?
I would like to log in pages with both username and email, I wrote a CustomBackend view to auth no matter how I changed, only username works, I use "email" to log in pages, always got error ofUnable to log in with provided credentials, partial code of views.py as below: from django.contrib.auth import get_user_model MyUser = get_user_model() class CustomBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = MyUser.objects.get(Q(username=username)|Q(email=username)) if user.check_password(password): return user except MyUser.DoesNotExist: MyUser().set_password(password) partial code of settings.py as below: AUTHENTICATION_BACKENDS = ( 'general.views.CustomBackend', 'django.contrib.auth.backends.ModelBackend' ) Any ideas will be highly appreciated. -
How to get variables along with their filter name from JINJA2 template
I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e. template = JINJA.from_string(text) The result template looks like this: Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',\n\n'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n \nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.\n\n')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:\n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button below\n'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.\n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:\n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'\n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])]) Now, what I want to do is that I want to get all the variables from this template and especially I am concerned … -
Unable to install tesserocr on Mac
I'm new to this. (Please forgive the noob lingo). So I'm trying to install tesserocr with the command: pip install tesserocr but I'm getting this error: tesserocr.cpp:298:10: fatal error: 'utility' file not found #include ^~~~~~~~~ 1 warning and 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 I have installed tesseract using: brew install tesseract I'm using Mojave 10.14.3 -
How to use the IN operator with uuid - Django?
How to use the IN operator with uuid - Django? clients = Client.objects.filter(nome__icontains=q).values_list('pk', flat=True) subscriptions = subscription.objects.filter(client_id__in=clients) I tried using this to convert and it still does not work. clients = [str(o) for o in clients] Where am I going wrong? Thank you. -
Why my django app can't send email to registered user?
I am trying to send user an email containing invitation/confirmation link.Command propmt is showing that email is being sent but user is not receiving any email.I am using my gmail account and also allows access by less secure apps on my account? What can be the possible errors? -
how to add an another core in django haystack using Solr Backend?
my old settings.py is : HAYSTACK_CONNECTIONS={ 'default':{ 'ENGINE': 'haystack.backends.solr_backend.SolrEngine', 'URL': 'http://127.0.0.1:8983/solr/core0', 'STORAGE': 'file', 'POST_LIMIT': 32 * 1024 * 1024, 'INCLUDE_SPELLING': True, 'BATCH_SIZE': 100, } } It works successful, now I want to add new core1 ,the core1 can be started ,but I don't kown how to add core1 in settings.py . The haystack'sdocs just says : # ...or for multicore... # 'URL': 'http://127.0.0.1:8983/solr/mysite' https://django-haystack.readthedocs.io/en/latest/tutorial.html?highlight=solr I have to see the question: Multiple Cores in Django Haystack using Solr Backend don't work for me. -
axios unable to get json from django view
I want to implement a front-end and back-end data interaction with axios and django view. Now I have succeed in posting data to django view with code below. axios.post("{% url 'main:getCommodityInfo'%}", param, {headers:{'X-CSRFToken': this.getCookie('csrftoken')}}) .then(response=>{ console.log(response); alert("response has been caught"); }) .catch(error=>{ console.log(error); alert("connection has error") }) But when I want to return json from view to axios: def getCommodityInfo(request): if request.method=="POST": # get POST parameters searchKey = request.POST.get('searchKey') category = request.POST.get('category') print("Enter the view! ", searchKey, category) # unique ID for each record for DB uniqueId = str(uuid4()) # spider setting settings = { 'unique_id': uniqueId, 'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } # taskId to indentify each task task = scrapyd.schedule('JDSpider', 'getCommodityInfo', settings=settings, searchKey=searchKey, category=category) print("It seems everything is running well? ") return JsonResponse({'taskId': task, 'uniqueId': uniqueId, 'status': 'started'},safe=False) the browser has no change! Firstly, I tried to figure out why it occurred independently. The potential clue maybe lie in urls.py. urlpatterns = [ # eg:127.0.0.1:8000/main/ path('', views.index, name = 'index'), path('getCommodityInfo/',views.getCommodityInfo, name = 'getCommodityInfo'), path('getCommodityCommentDetail/',views.getCommodityCommentDetail, name="getCommodityCommentDetail"), path('commodityInfo/<str:category>/<str:searchKey>/',views.commodityInfoPage, name = 'commodityInfoPage'), path('commentsInfo/<str:commodityId>/',views.commodityCommentPage,name = 'commodityCommentPage'), # path('?searchkey=<str:searchKey>&categroy=<str:category>/',views.getCommodityInfo, name = 'getCommodityInfo'), ] Because I found that the initial url http://127.0.0.1:8000/main/ in my browser after clicking on the button to post data … -
Django migration issues on production
Conflicts occurring in migration files on production, Is it needed to commit the migration files or not? Is it needed to run makemigrations? (python,django 2.11) -
Pass authentication headers when opening a new url
I will roughly describe the problem: I have a React.js application, which authenticates using IDAM and receives a token. I can use this token to make requests to the backend API. Everything is fine on the React.js side. Now I need to redirect to a Django application from the React.js application. I already have the authentication token, and I want to pass it to the Django application. I was thinking about putting the authentication header when doing window.open to open the Django url, but I realize that it is not possible to put headers with window.open. How can I pass the authentication headers when opening a new url?