Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'plotly' in Django
As you can see, I have successfully installed plotly in my Django project. (base) PS C:\Users\user\source\VVV\V_Project> pip list Package Version ---------------------------------- ------------------- plotly 5.13.1 However, it keeps showing the error. Traceback (most recent call last): File "c:\Users\user\source\VVV\V_Project\mysite\Plotly.py", line 3, in <module> from plotly.offline import plot ModuleNotFoundError: No module named 'plotly' My code is as follow. from django.shortcuts import render from plotly.offline import plot import plotly.graph_objs as go def index(request): x_data = [0,1,2,3] y_data = [x**2 for x in x_data] plot_div = plot([Scatter(x=x_data, y=y_data, mode='lines', name='test', opacity=0.8, marker_color='green')], output_type='div') return render(request, "plotly.html", context={'plot_div': plot_div}) I don't know why it cannot find the module plotly. Please help me. -
How to Implement Paytm Payment Gateway with Django?
I am trying to implement payment facility for my project and the code was working fine and now suddenly getting error. Thats what I get when I print the response. {'head': {'requestId': None, 'responseTimestamp': '1678521927424', 'version': 'v1'}, 'body': {'extraParamsMap': None, 'resultInfo': {'resultStatus': 'F', 'resultCode': '501', 'resultMsg': 'System Error'}}} Here is the code of which generate paytm checksum and return response. class InitiatePayment(APIView): def post(self, request, *args, **kwargs): paytmParams = dict() paytmParams['body'] = { "requestType" : "Payment", "mid" : PAYTM_MERCHANT_ID, "websiteName" : "DIYtestingweb", "orderId" : generate_order_id(), "callbackUrl" : "https://<callback URL to be used by merchant>", "txnAmount" : { "value" : "500.00", "currency" : "INR", }, "userInfo" : { "custId" : "nehatkn786@gmail.com", }, } checksum = paytmchecksum.generateSignature(json.dumps(paytmParams["body"]), PAYTM_SECRET_KEY) paytmParams["head"] = { "signature" : checksum } post_data = json.dumps(paytmParams) # for Staging url = f'https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid={PAYTM_MERCHANT_ID}&orderId={paytmParams["body"]["orderId"]}' response = requests.post(url, data = post_data, headers = {"Content-type": "application/json"}).json() print(response) # result = { # "txToken" : response["body"]["txnToken"], # "orderId": paytmParams['body']['orderId'], # "amount": paytmParams["body"]["txnAmount"]["value"], # } # return Response({'token':result['txToken'], 'orderId':result['orderId'], 'amout':result['amount']}, status=status.HTTP_200_OK) # return HttpResponse('Its working') return Response(status=status.HTTP_200_OK) The same code was working fine and was getting the transaction token. but suddenly getting error. Please help me out guys. -
File retrieve API in djangorestframework
I am trying to send a file from Frontend ( react ). I want to retrieve that file in Backend (Django) and save to database. I didn't find the correct way to retrieve my file from request object. Can any one help me how to write view function to retrieve the file in Django ? I sent file from frontend. I am trying to retrieve that file from request object in django. -
Impossible to import model_utils module in Django models.py
I follow the official documentation of the django-model-utils model and I've just done pip install django-model-utils in my virtual environment. However, VSCode indicates that Import "model_utils.managers" could not be resolved as shown below. VSCode error display With pip list I've checked that the module is effectively installed. Package Version ------------------------ -------- asgiref 3.6.0 autopep8 2.0.1 defusedxml 0.7.1 diff-match-patch 20200713 Django 4.1.5 django-admin-rangefilter 0.9.0 django-extensions 3.2.1 django-import-export 3.1.0 django-model-utils 4.3.1 django-phonenumber-field 7.0.2 djangorestframework 3.14.0 et-xmlfile 1.1.0 import-export 0.3.1 MarkupPy 1.14 odfpy 1.4.1 openpyxl 3.1.1 phonenumbers 8.13.4 Pillow 9.4.0 pip 22.0.2 pycodestyle 2.10.0 pytz 2022.7.1 PyYAML 6.0 setuptools 59.6.0 sqlparse 0.4.3 tablib 3.3.0 tomli 2.0.1 xlrd 2.0.1 And I've look that the folder exists with the right name and a __init__.py file as shown below. Screenshot of lib folders How can I solve this please ? -
django UniqueConstraint violation_error_message message not handled
I have this model: class DataMapping(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.ForeignKey(Location, null=True, blank=True, on_delete=models.CASCADE) department = models.ForeignKey(LocationDepartment, null=True, blank=True, on_delete=models.CASCADE) catagory = models.ForeignKey(CompanyCategory, on_delete=models.CASCADE) reason = models.ForeignKey(ReasonForProcessing, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint( name='unique_data_map', fields=['company', 'location', 'department', 'catagory', 'reason'], condition=Q(location__isnull=False), violation_error_message="This data map has already been added.", ), UniqueConstraint( name='unique_data_map_both_none_dep_none', fields=['company', 'location', 'catagory', 'reason'], condition=Q(department__isnull=True), violation_error_message="This data map has already been added." ), UniqueConstraint( name='unique_data_map_both_none', fields=['company', 'catagory', 'reason'], condition=Q(location__isnull=True) & Q(department__isnull=True), violation_error_message="This data map has already been added." ) ] with a basic modelform class DataMapForm(forms.ModelForm): class Meta: model = DataMapping fields = ( 'location', 'department', 'catagory', 'reason', ) widgets = { 'company': forms.HiddenInput() } and a view of: def data_mapping_new(request): company = get_current_logged_in_company(request) if request.method == "POST": form = DataMapForm(request.POST or None) if form.is_valid(): catagory = form.save(commit=False) catagory.company = company if form.is_valid(): form.save() I have a similar setup on a different model that works fine, but this one just raises an error django.db.utils.IntegrityError: duplicate key value violates unique constraint "unique_data_map_both_none" Should it not check the constraint at the first if form.is_valid(): What am I missing here? -
Django set homepage at http://127.0.0.1:8000
I made a chatbot with django framework, and I'm trying to deploy with heroku but it kept showing cannot be deployed, my app is working fine locally if i go to http://127.0.0.1:8000/chatbot/ but maybe if I set the homepage http://127.0.0.1:8000/ Heroku might be work so I wonder how should I change my urls.py to set my homepage as http://127.0.0.1:8000/ urls.py from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='home'), ] in templates folder i have one html file called index.html how should I change the code to set the homepage at http://127.0.0.1:8000/ views.py from django.shortcuts import render import openai openai.api_key = API_KEYS def chatbot(prompt): response = openai.Completion.create( model="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0 ) return response.choices[0].text.strip() def chatbot_view(request): chatbot_response = "" if request.method == 'POST': question = request.POST.get('question') chatbot_response = chatbot(question) return render(request, 'index.html', {'chatbot_response': chatbot_response}) I treid to change my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.chatbot_view), ] but it wasn't working -
Roles and Permissions between users and organizations
I'm building an application that allows users to belong to multiple organizations and can perform specific operations within each of these organizations as long as they have the required roles and permissions to do so. However, I kind of have issues implementing a satisfiable model that suits this requirement, especially given that roles and permissions in Django are typically related to the user's model and so it's impossible for them to vary with a particular user per organization. What I have done so far is implement a third model that records the role of a user with a particular organization in a separate table: class OrgUserPerms(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) user = models.ForeignKey("accounts.CustomUser", on_delete=models.CASCADE) user_role = models.CharField(max_length=25, choices=[ ("organization_admin","admin"), ("organization_manager", "manager"), ("organization_member", "member") ]) The problem with this model is that a user can have multiple OrgUserPerms referencing the same organization, I currently handle this by filtering the last saved OrgUserPerm object as the user's latest role in an organization then throw away the remaining OrgUserPerm objects with the same user&organization occurrence. I however feel this might eventually lead to operational bottlenecks in speed, security e.t.c and would deeply appreciate advice/suggestions from people with experience implementing something similar, thank you! -
How to add and fetch makrs to a subject which has foreignkey relation with class?
I want to add subject marks to specific classes of students. Where Subject has ManyToMany relation with Class and Class has ForeignKey relation with Student. class Subject(models.Model): name = models.CharField(max_length=50) mark = models.IntegerField(null=True, blank=True) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=30) subjects = models.ManyToManyField(Subject, blank=True) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=100) class_name = models.ForeignKey(Class, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name -
My django project on heroku cannot connect to postgresql
I am trying to alter the table of my database because i cannot migrate the changes in my models.py. I tried to connect to my database using command "heroku psql" or "psql + the needed url" but i keep receiving the error message "psql: error: connection to server at "ec2-3-211-6-217.compute-1.amazonaws.com" (159.100.251.128), port 5432 failed: Connection timed out (0x0000274C/10060) Is the server running on that host and accepting TCP/IP connections?" how to fix this? Thanks for the help in advance :) -
Not Found: /api/img/grid.png "GET /api/img/grid.png HTTP/1.1" 404 2468
Currently working on APIs using Django on VScode. Apis work fine, but every single time I access the urls this gets sent back to me. Didn't really try anything yet. I feel like there is a simple solution, but still beyond my abilities to find the problem. I have no images. I don't look to load images. Just working on some basic JSON apis using rest_framework. Debug tool shows nothing because the server runs fine. -
Auto increment on a dual unique constraint
I am trying to create a website using Django and MariaDB. here is my models.py file in my forum app. class Forum(models.Model): forum_name = models.CharField(max_length=30, unique=True) forum_date = models.DateTimeField('date_published', auto_now_add=True) class Topic(models.Model): forum = models.ForeignKey(Forum, on_delete=models.CASCADE) topic_order = models.IntegerField() topic_name = models.CharField(max_length=30) topic_exp = models.CharField(max_length=250) topic_date = models.DateTimeField('date published', auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint(fields=['forum', 'topic_order'], name='topic_const') ] as you can see i have 2 models(Forum & Topic). and inside topic class i have this meta class which makes forum and topic_order a dual unique constraint. and here is my MariaDB Topic database id topic_order topic_name topic_exp topic_date forum_id 1 1 people 2023-02-26 16:23:50 1 2 2 jobs 2023-02-26 16:25:59 1 3 3 metal 2023-02-26 16:26:52 1 8 1 people 2023-02-27 13:03:32 2 11 2 jubile 2023-03-10 10:36:52 2 now all i want to is to make topic order an auto-increment field.for instance: if another forum_id=1 is added i want topic_order=4 to be added automatically.however if a forum_id=2 field is added the next topic_order must be 3. Has anyone ever seen something like that before? Thank you. I tried to make topic_order an auto-increment field with django's models.AutoField() class.but that didn't worked out. -
django template not rendering data
`i am writing a blog website and for every blog post i made a detail page template but it doesn't render any data **my views.py ** def Post(request ): posts=post.objects.all() context= {'posts':posts} return render(request, 'post.html', context) def detail(request,pk): posts=post.objects.all() context= {'posts':posts} return render(request, 'detail_page.html', context) my urls.py path('', views.Post, name='Post'), path('detail/int:pk', views.detail, name='detail'), post.html file {% for post in posts %} {{post.title}} - {{post.author}} {{post.body}} {% endfor %} ** my detailpage** {{post.title}}your text {{post.author}} {{post.body}} after rendering it just shows me a blank template` -
Django group_send messages are not sent instant
i am trying to build a lobby system for a game. I want the lobby to be startable and once started there should happen a countdown that is sent to each connected client. The problem is now that all messages are sent after the complete time has passed and not each second for the countdown. The weird thing for me is also, that the messages on the other client that are not the host are getting the message like they should (every second). I fell like the messages are grouped and then sent after all time is passed. PS: tried normal sent function and this is working like it should but i cant sent to other group members async def init_starting(self): if not self.lobby.status == "waiting": print("Already Started") return False else: print("Starting Countdown") #self.lobby.status = 'starting' #await self.save_lobby() await self.send_status_message_with_status(status='starting', data={'has_started': self.lobby.has_started, 'host': self.host.username, 'players': self.players, 'lobby_code': self.lobby_code, 'countdown': 3}) countdown = 3 while countdown >= 0: countdown_data = { 'countdown': countdown } await self.send(json.dumps({"type": "msg", "message": countdown})) await self.send_status_message_with_status(status='starting', data=countdown_data) print(countdown) countdown -= 1 await asyncio.sleep(1) await self.send_status_message_with_status(status='started', data={ 'message': "Test" }) return True async def send_status_message_with_status(self, status, data): send_data = { 'type': 'status', 'status': str(status), } send_data = … -
Cannot delete record from ReactJS webpage, getting the error "method not allowed"
I am trying to make a React JS page that shows a list of appointments, and will delete the appointments if the Cancel/Finish buttons are clicked. However, I am getting the error "Method not Allowed." I have executed the same delete view in Insomnia's back-end and my delete view is working. Therefore, the problem is only in the ReactJS file. `import React, {useState, useEffect } from 'react'; function ListAppointments() { const [appointments, setAppointments] = useState([]) const getData = async () => { const response = await fetch('http://localhost:8080/api/services/'); if (response.ok) { const data = await response.json(); setAppointments(data.appointment) } } useEffect(()=>{ getData() }, []) const handleDelete = async (e) => { const url = `http://localhost:8080/api/services/${e.target.id}` const fetchConfigs = { method: "Delete", headers: { "Content-Type": "application/json" } } const resp = await fetch(url, fetchConfigs) const data = await resp.json() setAppointments(appointments.filter(appointment => String(appointment.id) !== e.target.id)) } return ( <div> <h1>Appointments</h1> <table className="table table-striped"> <thead> <tr> <th>VIN</th> <th>Customer Name</th> <th>Date</th> <th>Time</th> <th>Technician</th> <th>Reason</th> <th>Status</th> </tr> </thead> <tbody> {appointments.map(appointment => { return( <tr> <td>{ appointment.automobile.vin }</td> <td>{ appointment.customer}</td> <td>{ appointment.appointment_date}</td> <td>{ appointment.appointment_time}</td> <td>{ appointment.technician.name}</td> <td>{ appointment.reason }</td> <td> <button onClick={handleDelete} id={appointment.id} className="btn btn-primary" style={{backgroundColor:"red", border: '1px solid red'}}>Cancel</button> <button onClick={handleDelete} id={appointment.id} className="btn btn-primary" style={{backgroundColor:"green", border: '1px … -
reverse url django admin
small problem of Django and its reverse url, I try to have a link from a model to another model in the same admin:app I have this function to run reverse('admin:jobs_xml_jobboardexterne') I run from this page admin/jobs_xml/countjobboarderrors/ and I get an error: https://i.stack.imgur.com/Uf00J.png here the code was make the call : class CountJobBoardErrorsAdmin(admin.ModelAdmin): list_display = ("have_error_job_board", "have_not_error_job_board", "total_job_board") def have_error_job_board(self, obj): url = reverse('admin:jobs_xml_jobboardexterne') return mark_safe(f'<a href={url}>{JobBoardExterne.objects.count()}</a>') ok, so Django can't find my link, in my settings.py I have the application noted INSTALLED_APPS = [ ..., 'jobs_xml', ... ] my project urls.py also admin.autodiscover() urlpatterns = [ ..., url(r'^admin/', admin.site.urls), ] an idea ? I can't find the error. thank you for your help :) -
Unique together between field and model connected by ForeignKey django
I have two models. class Post(models.Model): title = models.CharField(max_length=150) class Attachment(models.Model): type = models.CharField(choices=AttachmentChoices.get_choices(), max_length=15) link = models.URLField() post = models.ForeignKey('Post', on_delete=models.PROTECT, related_name='attachments') I want to do something like this in meta class of Post model class Meta: unique_together = [('title', 'attachments')] but it dosn't work couse django can't find attachments field. Is there a solution provided by django that can solve this problem. -
Django Tinymce file tinymce.min.js not found
i am trying to integrate tinymce with a django app but django can't find the tinymce javascript file this is my settings.py : BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' MEDIA_URL = 'media/' STATICFILES_DIRS = [BASE_DIR/"staticfiles"] STATIC_ROOT = BASE_DIR/"static_root" MEDIA_ROOT = BASE_DIR/"media_root" #TinyMce TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_URL, "tinymce/js/tinymce") TINYMCE_DEFAULT_CONFIG = { 'height' : 300, 'plugins': "image,imagetools,media,codesample,link,code,paste", 'cleanup_on_startup': True, 'menubar': True, 'toolbar': "styleselect |undo redo | bold italic | alignleft aligncenter alignright | link image media codesample code", 'image_caption': True, 'image_advtab': True, 'paste_as_text': True, 'custom_undo_redo_levels': 10, 'file_browser_callback' : "myFileBrowser" } and on localserver logs i have this : [10/Mar/2023 22:48:14] "GET /static/static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980 but i this it should be : [10/Mar/2023 22:48:14] "GET static/tinymce/js/tinymce/tinymce.min.js HTTP/1.1" 404 1980 -
How to style django forms
I am trying to make an interactive from similar to the one shown in this image I am using python django, I am looking to incorporate react if its needed! I have searched youtube for interactive forms and nothing in this similar style shows nor on Google! -
DRF GET serializer: get parent id in a nested relationship (extra fields in a nested manytomany relationship with through model)
Having the following models class House(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=1024, blank=True) zone = models.ForeignKey(Zone, on_delete=models.CASCADE) vehicles = models.ManyToManyField(Vehicle,through="VehicleHousing", through_fields=('house', 'vehicle'),) habitants = models.ManyToManyField(settings.AUTH_USER_MODEL,through="UserHousing", through_fields=('house', 'habitant'),) def __str__(self): return self.name class CustomUser(AbstractUser): username = models.TextField(default=None, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) phone_number = models.CharField(max_length=12,default=None, blank=True, null=True) houses = models.ManyToManyField(House,through="UserHousing", through_fields=('habitant', 'house'),) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class UserHousing(models.Model): register_date = models.DateTimeField(auto_now_add=True, editable=False) habitant = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) house = models.ForeignKey(House, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) class Meta: unique_together = [['habitant', 'house']] The user model is a custom user model replacing the base one, of course replaced in the settings.py AUTH_USER_MODEL I got the following serializers to get the data to the view: class UserBasicInfoSerializer(serializers.ModelSerializer): admin = serializers.SerializerMethodField('get_admin') def get_admin(self, obj): admin = UserHousing.objects.get(habitant=obj).isAdmin return admin class Meta: model = get_user_model() fields = ['id', 'email', 'first_name', 'last_name', 'phone_number', 'admin'] class VehicleSerializer(serializers.ModelSerializer): class Meta: model = Vehicle fields = ['id','license_plate','brand','model','hexcolor'] class HouseSerializer(serializers.ModelSerializer): habitants = UserBasicInfoSerializer(many=True, read_only=True) vehicles = VehicleSerializer(many=True, read_only=True) class Meta: model = House fields = ['id','name', 'address', 'vehicles', 'habitants'] class UserFullInfoSerializer(serializers.ModelSerializer): houses = HouseSerializer(many=True, read_only=True) class Meta: model = get_user_model() fields = ['id', 'email', 'first_name', 'last_name', 'phone_number', 'houses'] Ending up with the … -
python-oracledb Executing PLSQL not working
Im trying to execute the example in python-oracledb example. But every time the server reloads I get the following error. django.db.utils.NotSupportedError: Python value of type VariableWrapper not supported. Here is my views.py from django.views.generic import TemplateView from django.db import connection import oracledb class Profile(TemplateView): """blarg""" template_name = 'profile.html' cursor = connection.cursor() out_val = cursor.var(int) cursor.callproc('myproc', [123, out_val]) print(out_val.getvalue()) # will print 246 I can confirm the procedure is created inside a package in the database. -
Change model fields if type is different
I have two services: Job and Server. They are quite similar, but Server also has fields "host" and "port". I need the model to recognize the service type, and if it is Job it must set "host" and "port" fields to None automaticly and save it to db table. Is it possible? I`ve tried to use different types of validators in Serializer, but nothing worked. Here is my model: class Service(models.Model): class ServiceType(models.TextChoices): JOB = 'Job', _('Job') SERVER = 'Server', _('Server') type = models.CharField(max_length=10, choices=ServiceType.choices, default=ServiceType.JOB) code_name = models.CharField(max_length=200) human_name = models.CharField(max_length=200) description = models.CharField(max_length=200) host = models.CharField(max_length=200) port = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(65535)]) def __str__(self): return self.type As you can see, there can be only two types: Server and Job. And I need to automacitally set host and port fields to None, if type == 'Job'. Sounds easy, but I think Im not expirienced enough to find out the solution. Ive also tried to use validator in my Serializer, but it didn`t help: class ServiceSerializer(serializers.ModelSerializer): class Meta: model = Service fields = '__all__' def validate(self, data): if data['type'] == 'Job': data['host'] = None data['port'] = None return data I expect to see host and post fields in database equal to … -
Unsure why Django model form many to many field validation failing on is_vaild()
I have the following form and model in my django app: Form: class AdditionalDealSetupForm(ModelForm): required_css_class = "required" lead_underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), label="Lead Underwriter(s):", required=False, widget=forms.SelectMultiple( attrs={"class": "lead_underwriter"} ), ) underwriters = forms.ModelMultipleChoiceField( queryset=Underwriters.objects.all(), required=False, label="Underwriter(s):", widget=forms.SelectMultiple(attrs={"class": "underwriter"}), ) class Meta: model = AdditionalDeal fields = [ "cutoff_date", "closing_date", "deal_private", "lead_underwriters", "underwriters", ] Model: class AdditionalDeal(TimestampedSafeDeleteModel): id: PrimaryKeyIDType = models.AutoField(primary_key=True) # Relations deal_setup: ForeignKeyType[t.Optional["DealSetup"]] = models.ForeignKey( "DealSetup", on_delete=models.SET_NULL, null=True, blank=True, related_name="additional_deal_set", ) if t.TYPE_CHECKING: deal_setup_id: ForeignKeyIDType lead_underwriters = models.ManyToManyField( Underwriters, related_name="DealLeadUnderwriter" ) underwriters = models.ManyToManyField(Underwriters, related_name="DealUnderwriter") class Meta: db_table = "Additional_Deal" verbose_name_plural = "Additional Deal" unique_together = ("deal_setup",) So I have a multi select form on the front end that can create new tags/ underwriters which are instances of the Underwriters model. When I try to submit the form the newly returned value from the form that does not exist in the Underwriters model already is failing validation. Right now I am creating the new Underwriter objects before I call is_valid() on the form object. I cant figure out why this is. I tried overriding some of the ModelForm clean_* methods but they are not getting called as I expected to before this failed validation: -
Django SimpleListFilter: ValueError not enough values to unpack (expected 2, got 0)
Context: I'm creating a custom input filter in Django using the SimpleListFilter class. I've followed the steps in here https://hakibenita.com/how-to-add-a-text-filter-to-django-admin, but I'm encountering a ValueError when trying to use the filter. Here is my code: filters.py: from django.contrib import admin from django.db.models import Q class InputFilter(admin.SimpleListFilter): title = 'Language' parameter_name = 'language' template = 'admin/input_filter.html' def lookups(self, request, model_admin): # Dummy, required to show the filter. return ((),) def queryset(self, request, queryset): if self.value(): return queryset.filter(Q(language__icontains=self.value())) def choices(self, changelist): all_choices = super().choices(changelist) query_params = changelist.get_filters_params() if not self.lookup_choices: return [] for lookup, title in self.lookup_choices: query_parts = changelist.get_query_string({self.parameter_name: lookup}).split('&') if query_parts and len(query_parts) >= 2: query = '&'.join([f'{k}={v}' for k, v in query_parts]) choice = { 'query_string': f'?{query}&{query_params}', 'display': title, 'selected': self.value() == lookup, } all_choices.append(choice) return all_choices I get the following error when accessing the admin page: ValueError at /repoman/admin/aws_storage/raw_file/ not enough values to unpack (expected 2, got 0) I'm not sure what is causing this error or how to fix it. Any help would be appreciated! -
CSRF error when making POST request to Django API
I am currently developing an application that has a React JS front end and Python Django backend. After successfully logging in, the backend created the necessary cookies, which includes the CSRF token, however when the front end makes a POST request the API returns an error with: "CSRF Failed: CSRF token missing or incorrect" even though the CSRF token is within the cookies that are passed to the API. I have looked online and the fix is to include the CSRF token in the X-CSRFToken header, which I have successfully tested by manually putting the CSRF token in the front end code when it makes the API call. When I try to use Cookies.get('csrftoken'), or even just console.log(document.cookie), it does not return anything because the domain of the CSRF token is the backend URL and therefore different to the front end domain so it does not let me use it within the frontend code. Is there a way for me to use the CSRF token in the cookie to validate the request within the API or can I somehow access it within the frontend to pass it via the X-CSRFToken header even though it is a different domain? I have … -
Using pyarmor in a django project with celery
I'm using pyarmor to obfuscate my django project, following this steps: pyarmor init --entry=manage.py pyarmor build Running the content in dist/, works fine. But I would like running celery too. It's possible? Do I need put it in init too?