Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I do a hierarchical validation in Django?
I'm writing a Django app, where users can upload CSV files. Therefore I've created an upload model with three validators: One that checks the file extension (FileExtensionValidator), one for the MIME type validation (ValidateFileType), and a third one for parsing the CSV file and checking for data types, right number of columns and so on (ValidateCsv). It'd be reasonable to check the upload only with the next validator if the preceding validation didn't raise a ValidationError. For instance, the user could upload a .py file. This would raise an error in all three validators, but I want to avoid, that Django checks the MIME type or even tries to treat and parse a .py file as a CSV file, although the file extension wasn't correct right from the beginning. So here is my model for the user's upload: models.py from django.db import models from .utils import unique_file_path from django.core.validators import FileExtensionValidator from .validators import ValidateFileType, ValidateCsv class Upload(models.Model): date_uploaded = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=unique_file_path, validators=[FileExtensionValidator(['csv']), ValidateFileType, ValidateCsv], max_length=255) With this validators list all three validations are always performed and I can see all the error messages in upload_form.errors. For example: File extension 'py' is not allowed. Allowed extensions are: 'csv'. … -
Beginner Django 2.2 tutorial pt.2 Timezone, datetime, pub_date
From the Official Django 2.2 Tutorial pt2 running manage.py makemigrations polls I don't see the expected "- Add field question to choice" after - Create model Choice and - Create model Question It Could be be something that depends from the settings of my enviroment or system, pycharm... etc.) From that "stupid" point * everything goes wrong. I'm trying and trying since two days with just copy and paste from the original tutorial. Always the SAME in the same point: few tutorial lines after I face problems with the function was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Pycharm tells me: "pub_date: Expected type "timedelta", got "dateTimeField" instead this is my polls/models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Off course I don't see nothing related to "Add field question to choice" not even after passing the command "python manage.py sqlmigrate polls 0001". This is my terminal output, instead: BEGIN; -- -- Create model Question -- CREATE TABLE "polls_question" ("id" integer … -
How to trigger an events by django when html buttons are cliked
here is the html file form <form action ="fetch" method="post"> <input type="text" name="t1"> <input type="text" name="t2"> <input type="submit" name="b1"> <input type="cancel" name="b2"> </form> now when we click on submit button its properly calls the fetch function but when i click on cancel button same fetch function is called so i don't want that to happen i want to trigger different event/function when user click's on cancel button here is the html file form <form action ="fetch" method="post"> <input type="text" name="t1"> <input type="text" name="t2"> <input type="submit" name="b1"> <input type="cancel" name="b2"> </form> my views.py def fetch(request): a = request.GET.get("t1") b = request.GET.get("t2") return render(request,'student.html') -
Django is not sending email after rest-auth registration
After I change user model to using email instead of username, email is not sending when I access rest-auth.registration.views.RegisterView. What should I do to make working? My email setup is: EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" It's correct configuration, sending email on rest_auth.views.PasswordResetView works fine. My code: users/urls.py: app_name = "users" urlpatterns = [ path("register/", include("rest_auth.registration.urls")), ... ] config/urls.py: from allauth.account.views import AccountInactiveView urlpatterns = [ ... path("api/v1/users/", include("myproject.users.urls")), # this url is used to generate email content # https://github.com/Tivix/django-rest-auth/blob/master/demo/demo/urls.py path("password-reset/<uidb64>/<token>/", TemplateView.as_view(), name="password_reset_confirm") # for some reason required for rest-auth register view working path("account-inactive/", AccountInactiveView.as_view(), name="account_inactive"), ] config/settings.py ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False After accessing register view, there's no error. User object is created and response (code 201) is: { "detail": "Verification e-mail sent." } However there's no email sent. Thanks for help! -
django best way to whitelist domains?
I have a view with this line: def my_view(request): redirect_url = get_url() return HttpResponseRedirecr(redirect_url) I want to make sure that this redirect url is in my whitelisted set of urls. What's the django way of doing this? I know i can just create a temporary list in the view and then check if the domain of redirect_url matches any of the domains in the list, but I'm wondering if there's a better way of accomplishing this -
Django: ManytoMany extra fields gives back duplicate key error
I am trying to use the following code to create a new entry in my model: ContactRelation.objects.create( lead=True, event=request.event, contact=contact ) However, I am always running into that error message: duplicate key value violates unique constraint "contacts_contactrelation_pkey" DETAIL: Key (id)=(14) already exists. I expected Django to count up pk by itself. pk=14 already exists. If I write, ContactRelation.objects.create( pk=199, lead=True, event=request.event, contact=contact ) then my entry is successfully created. ContactRelation acts as many-to-many relationship table with extra fields. Do you understand why Django is dealing with pks that way? class ContactRelation(TimeStampedModel): """ Stores data about individual events the contact interacted with. :param event: ForeignKey to the event. :type organizer: Event :param contact: ForeignKey to the contact. :type contact: Contact :param lead: If true, contact used the sign up form. :type lead: bool :param attendee: Contact assigned to ticket as attendee. :type attendee: bool :param purchaser: Contact made an order for the respective event. :type purchaser: bool """ event = models.ForeignKey( 'events.Event', related_name='contact_relation', on_delete=models.CASCADE ) contact = models.ForeignKey( Contact, related_name='contact_relation', on_delete=models.CASCADE ) lead = models.BooleanField( verbose_name='Lead', default=False ) # Contact who 'Signed Up' attendee = models.BooleanField( verbose_name='Attendee', default=False ) # Contact assigned to ticket purchaser = models.BooleanField( verbose_name='Purchaser', default=False ) # … -
Python PDFJinja/PDFtk Errors Trying to Fill a PDF
I am attempting to use a fork of pdfjinja, which uses PDFtk to fill PDFs in an application. I feel like the code I have written to fill the PDF and return it in a view should be accurate, but for some reason I am getting FileNotFound errors, even though I know the file location is correct. Can somebody point me in the right direction? Here is my view: def pdf(request, client_url): # this is an accurate location template = os.path.join(BASE_DIR, 'apps', 'residents', 'templates', 'residents', 'test.pdf') data_dict = { 'first_name': 'John', 'last_name': 'Smith', 'email': 'mail@mail.com', 'phone': '889-998-9967', 'company': 'Amazing Inc.', 'job_title': 'Dev', 'street': '123 Main Way', 'city': 'Johannesburg', 'state': 'New Mexico', 'zip': 96705, 'country': 'USA', 'topic': 'Who cares...' } pdfjinja = PdfJinja(filename=template) # fine print(pdfjinja.filename) # fine and everything looks accurate print(pdfjinja.fields) # [WinError 2] The system cannot find the file specified pdfout = pdfjinja(data_dict) # ------- doesn't get here output = BytesIO() pdfout.write(output) response = HttpResponse(output, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="completed.pdf"' return response Here is the file I am currently using for PDFJinja, I can edit it as I need though it is local to my project now too. https://github.com/yoongkang/pdfjinja -
Django: Update user fields using a custom form
Staff members can register/update profile of users. My registration function works fine, but not the profile update. I'm getting this error: 'int' object has no attribute '_meta'. forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm class RegisterForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) is_active = forms.BooleanField(initial=True, required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'group_name', 'is_active', ) class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('email', 'is_active', 'group_name', ) views.py @login_required @group_required('Staff') def registerView(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = RegisterForm() return render(request, 'accounts/register.html', {'form': form}) # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): if request.method == 'POST': form = UpdateForm(request.POST, instance=id) if form.is_valid(): user = form.save() group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) return redirect('accounts:users') else: form = UpdateForm(instance=id) return render(request, 'accounts/update_user.html', {'form': form}) urls.py path('users/<int:id>/update', views.updateUserView, name='update'), What am I missing? Is there an easier way to do it? -
Send a HDF5 temporary file as download on a Django website
I'm working on a Django written website where I want to provide downloadable HDF5 files generated based on user's demand. The problem is that I work with huge datasets (up to 1Go per file for big requests) so I wanted to create the file as TemporaryFile to avoid writting it on the server, but I don't find any way to send it with HttpResponse. I tried to write the generated HDF5 file on my disk (by providing an output_path variable to my createHDF5 function) and it worked : it contained the required data (60Mo with my test case) and was available as download by providing the path of the file, but I felt that writing directly files on the disk is a bad way to go (maybe I'm mistaken ?). So I tried by generating a temporary HDF5 file (with TemporaryFile()/NamedTemporaryFile()), and send it to the user, with and without using the FileWrapper method. LPFDataParser (HDF5 creation) : def createHDF5(self, hdf5_x, hdf5_y, param, start_date, end_date, output_path=None): if output_path: new_hdf5 = h5py.File(output_path, 'a') else: new_hdf5 = h5py.File(tempfile.NamedTemporaryFile()) hdf5_dataset = np.array([hdf5_x, hdf5_y]) new_hdf5.create_dataset(name="LPFdata", data=hdf5_dataset, dtype="f8") new_hdf5.attrs.create('name', np.string_(param.name)) ... return new_hdf5 views.py (download function with disk written file) : def download_custom(request, param_id, start_stamp, … -
in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg))
board = Board(name='Django', description='This is a board about Django.') Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/babak/myproject/venv/lib/python3.6/site-packages/django/db/models/base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Board() got an unexpected keyword argument 'description' -
How to make django urls dynamic
I want to make my urls dynamic. So far the problem occurs when any of the url is not listed among these urls the page shows not found 404 error. For eg: If i want to access the /dashboard i can easily do it because it is listed. Now i want to access follow-up tab after that which is in my sidebar /dashboard/follow-up i can do that too but when i want to access another tab lets say table so the url will be /dashboard/follow-up/table it will not be accessed. I know it is not possible to add all possible combinations of URL because there would be many. I am new to django. Please someone guide me how to solve the problem. I have provided my urls.py I TRIED MY BEST TO EXPLAIN IF YOU STILL DID NOT UNDERSTOOD MY QUESTION PLEASE ASK YOUR QUERY IN THE COMMENTS I WILL EDIT THE QUESTION AS BEST AS I CAN. urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', TemplateView.as_view(template_name='home.html'), name='home'), path('dashboard/notifications', TemplateView.as_view(template_name='notifications.html'), name='notifications'), path('dashboard/Login_request', TemplateView.as_view(template_name='Login_request.html'), name='Login_request'), path('dashboard/follow-up/', TemplateView.as_view(template_name='follow-up.html'), name='follow-up'), path('accounts/password_change/', TemplateView.as_view(template_name='password_change'), name='password_change'), path('accounts/password_change/done/', TemplateView.as_view(template_name='password_change_done'), name='password_change_done'), path('dashboard/settings/', TemplateView.as_view(template_name='settings.html'), name='settings'), path('dashboard/', views.chart, name='dashboard'), path('table/', views.offense, name='table'), path('dashboard/user/', TemplateView.as_view(template_name='user.html'), name='user'), ] -
Populate Django DB with local JSON file
I create a web application with Django and I need basic data. To do this, I have a JSON that contains a lot of data that I would like to import into my Django database. So I'm looking for a way to import this data without modifying the JSON file. Extract from JSON: [ { "key": "sword", "name": "Sword", "tier": 1 }, { "key": "bow", "name": "Bow", "tier": 1 }, ... ] My file contains a lot of data and it would take a long time to change it. Is there a script / program to import all this data corresponding to the following model: from django.db import models class Item(models.Model): name = models.CharField(max_length=120) tier = models.PositiveIntegerField() I saw the example on the django site, but it would be necessary to add to each item in my JSON a property model which would be very long Example from Django website: [ { "model": "myapp.person", "pk": 1, "fields": { "first_name": "John", "last_name": "Lennon" } }, { "model": "myapp.person", "pk": 2, "fields": { "first_name": "Paul", "last_name": "McCartney" } } ] -
Django, django-stores: File not found when using Google cloud storage
Ive created a file field on my model: class File(models.Model): """ Files added to the message. """ file = models.FileField(verbose_name=(_("File")), upload_to="mail/%Y/%m/%d") message = ParentalKey( "message.EventDetailMessage", on_delete=models.CASCADE, related_name="files" ) Im now trying to access the uploaded file and attach this to an email, but I cant get it to work reliably in production and locally. Right now its always working locally, but I cant seem to access the file in production (which uses django-stores with GOOGLE settings, since I use Google cloud buckets). When running the code below in production I get the message: "File was not found" for message_file in message.files.all(): logger.info(f"Attaching file {message_file}") file = message_file.file email.attach(basename(file.name), file.read(), guess_type(file.name)[0]) file.close() Can anyone point me in the right direction? -
""" Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\\-detail\\/(?P<id>[0-9]+)$']"""
I'm new in django, I got"""Reverse for 'sample' with keyword arguments '{'id': ''}' not found. 1 pattern(s) tried: ['sample\-detail\/(?P[0-9]+)$']""" in my project and I don't know what can I fix it.please help me with codes. views.py def home(request): ctx={} ctx['sampleBotes'] = sampleBot.objects.all() return render(request,'home.html',ctx) def sample_details(request,id): ctx={} ctx['other_sample'] = otherSampleBot.objects.filter(id=id) return render(request,'sample-details.html',ctx) urls.py from django.contrib import admin from django.urls import path,include from app_base import views urlpatterns = [ path('',views.home), path('sample-detail/<int:id>',views.sample_details, name= 'sample'), ] home.html <a href="{% url 'app-base:sample' id=other_sample.id %}"><span class="more-course">other samples</span></a> -
How I can Add an extra 'status' field in auth_user Table in Django?
I want to add 'status' field in my django auth_user table, Please let me know how i can add this field. I was trying to add by signup form but i am unable to migrate from there, I am getting error. Is there are any other option where i can add this field in Django default login functionality. -
I need to convert raw MySQL query to Django ORM query
I have models.py that represent below: ` from django.db import models from django.db.models.signals import post_save # Create your models here. from django.http import request class Task(models.Model): created = models.DateTimeField(auto_now_add=True) description = models.CharField(max_length=512) cost = models.DecimalField(decimal_places=2, max_digits=8) def __str__(self): return self.description + "-" + str(self.cost) class TaskStatus(models.Model): STATUS = ( (0, 'Created'), (1, 'Taken'), (2, 'Reissued'), (3, 'On approve'), (4, 'Done'), ) task_id = models.IntegerField() created = models.DateTimeField(auto_now_add=True) status = models.PositiveSmallIntegerField(choices=STATUS, default=0) def __str__(self): return str(self.task_id) + ' ' + str(self.status) def create_status(sender, instance, **kwargs): if kwargs['created']: task_status = TaskStatus.objects.create(task_id=instance.id) post_save.connect(create_status, sender=Task) ` I have to translate that mysql query to django ORM query. I got stack on this for 2 days. And please suggest me some useful links to understand how to perform. `SELECT t.created, t.description, (SELECT MAX(s.created) FROM task_statuses s WHERE s.task_id = t.id AND s.status_type = 3 GROUP BY s.task_id) as task_on_approve FROM task t WHERE t.created BETWEEN '2019-04-01 00:00:00' AND '2019-04-30 23:59:59'; ` -
What "command" does Celery's app.control.broadcast expect?
I thought that app.control.broadcast would take an @task, but when running the following: app.send_task("workerTasks_supervisor.task_supervisor_test", args=[], queue='supervisor') app.control.broadcast("workerTasks_supervisor.task_supervisor_test", args=[], queue="supervisor") The first succeeds and the second fails with: [2019-08-01 12:10:52,260: ERROR/MainProcess] pidbox command error: KeyError('task_supervisor_test',) Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 104, in dispatch reply = handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 126, in handle_cast return self.handle(method, arguments) File "/usr/local/lib/python3.5/dist-packages/kombu/pidbox.py", line 120, in handle return self.handlers[method](self.state, **arguments) KeyError: 'task_supervisor_test' The worker is started with celery worker -A workerTasks_supervisor -n Supervisor --concurrency=1 --loglevel=info -Q supervisor -f /logs/celery_supervisor.log --pidfile=/logs/supervisor_pid.pid And the task itself is simple: @app.task() def task_supervisor_test(): print("working") What am I doing wrong? Thanks. -
Conditional checks not working while processing form in Django
I have a ModelForm (EditGoalForm) which I use to edit an instance of a model (Goal). Some conditions must be met before saving form data. I used if statements to check these conditions and it still saves, instead of giving an error - like the if statement does nothing. I have the following: models.py class Goal(models.Model): goal_name = models.CharField(max_length=250) goal_status = models.ForeignKey(GoalStatus, on_delete=models.CASCADE, related_name='goal_status') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='scrumy_goal_user') class GoalStatus(models.Model): status_name = models.CharField(max_length=250) forms.py class EditGoalForm(forms.ModelForm): goal_status = forms.ModelChoiceField(queryset=GoalStatus.objects.all(), empty_label="Select Goal Status") class Meta: model = Goal fields = ('goal_status',) views.py def move_goal(request, goal_id): goal_instance = Goal.objects.get(goal_id=goal_id) ERROR_MESSAGE = '''BlahBlahBlah''' has_perm_cannot_move_to_done = request.user.has_perm('application.cannot_move_to_done') has_perm_can_move_goal_anywhere = request.user.has_perm('application.can_move_goal_anywhere') has_perm_can_move_someones_goal_from_verify_to_done = request.user.has_perm('application.can_move_someones_goal_from_verify_to_done') has_perm_can_move_anybodys_goal_to_any_column = request.user.has_perm('application.can_move_anybodys_goal_to_any_column') if request.method == 'POST': form = EditGoalForm(request.POST, instance=goal_instance) if form.is_valid(): if (has_perm_cannot_move_to_done and form.cleaned_data['goal_status'] != 'Done Goal'): form.save() messages.success(request, 'Goal Update Successful') return redirect('home') else: messages.error(request, ERROR_MESSAGE) else: form = EditGoalForm(instance=goal_instance) return render(request, 'move_goal.html', {'form': form}) After if form.is_valid, I checked if the authenticated user has the permission and if the goal_status field was not set to Done Goal. If both are True, then save. However, if I set the goal_status field to Done Goal, it still saves instead of displaying an error message. What could be … -
How to deploy django app via putty with ssl certificate on aws ec2? Step-by-step
Unable to connect django app with ssl certification via putty. I've ec2 aws instance, public IP and I had already connected to the server through putty, and set postgres database and hosted django app via http protocol. I want to deploy app with ssl certificate. Kindly guide me step-by-step. Note: I only have ec2 instance, public ip, .pem key, lan ip and putty and have no access to AWS account. Error: Not permitted to connect to http://0.0.0.0:443 -
How to list in django all users profiles registered in the frontend?
This is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', enter code hereupload_to='profile_pics') This is my views.py, in my template profile.html iam trying to list in a for loop but with no sucess def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Conta criada com sucesso para! Agora é possivel efectuar o login') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form} @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Conta actualizada com sucesso!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, "title": "profile" } return render(request, 'users/profile.html', context) template is in the users app profile.html -
How to Access Context Variables Sent from Django Application in Javascript
I have sent a variable in context from my django python code as so: context = { "data": data, } return render(request, "template.html", context) but do not know how to access it in my javascript file. I have tried accessing it like this: data_from_django = {{ data }} However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable. -
How can I get the keycloak ID using mozilla-django-oidc using django?
I'm using mozilla-django-oidc for my keycloak authentication with django. I can only retrieve the user email from this but can't get the other credentials like username, id etc. From keycloack config it should have in this key value pair: "claims_supported":["aud","sub","iss","auth_time","name","given_name","family_name","preferred_username","email"] but as I'm using this package I'm really confused how can I get the id means sub from it. This is my view file where i want to show the user id of the logged in user: views.py <html> <body> {% if user.is_authenticated %} <p>Current user: {{ user.email}}</p> {# shows the user email #} <p> username {{ user.sub) }}</p> {# but doesn't show the user id #} <p>Secured</p> {% else %} <a href="{% url 'oidc_authentication_init' %}">Login</a> {% endif %} </body> </html> -
Using django custom manager method as part of Q object chain
I have a custom manager with a method: # managers.py class MyModelQuerySet(models.QuerySet): ### def close_matched(self, radius=5): return self.filter( matched=True, separation__lte=radius, ) Is there anyway to use the filtering in close_matched with a set of Q object filters, for use in a view? As a simple example, something like: q = Q(another_constraint=True) | MyModel.objects.close_matched(4) but with a corrected object on the right side of the | (currently gives a TypeError since it is a queryset). If not, I'm not sure what would be best practice here to avoid duplicating the code whereywhere, is it best to rewrite the filtering logic of close_matched as a Q object that I can call in close_matched and elsewhere in views.py etc.? -
Http failure response for Django local server: 0 Unknown Error
I can see that there are several questions with this same error, I have read many of them and most are related to CORS problem. In fact, my browser is also generating CORS related warnings. I had this same problem a while ago and managed to solve by reconfiguring the header of my application. Now I'm using the same configuration, but for a different server, and I can't get over this error. I have an Ionic v4 app running in port 8100 and my Django v2.2.4 server is running in port 8000. My app header and request method (http.post using HttpClient) : const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8000, http://localhost:8100', 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', 'Accept': 'application/json' }) }; this.http.post("http://localhost:8000/converter2/", jsonFile, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ).subscribe(res => { if (res['success']) { this.presentToast('File uploaded complete') } else { this.presentToast('File uploaded failed') } }); I tried to configure the CORS in Django too, adding django-cors-headers with pip and configuring: # settings.py MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True but can't see changes. Browser Warnings: Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in … -
How to make CheckboxSelectMultiple checked in admin panel while editing?
I am a new Django programmer and the current version of the Django I am using is 1.11.20. I created models: Restaurants and Facilities. facilities = ( (1,'Accepts Credit Cards'), (2,'Wireless Internet'), (3,'Privat Parking'), (4,'Wheelchair Accesible'), (5,'Bike Parking'), (6,'Reservations'), (7,'Smoking Area'), (8,'Coupons'), ) class Restaurant(models.Model): restaurant_name = models.CharField(max_length=255) location = models.ForeignKey(Places, on_delete=models.CASCADE) restaurant_overview = RichTextField(blank=True) users_rating = models.DecimalField(decimal_places=1, max_digits=2) restaurant_image = models.ImageField(upload_to='restaurants') created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True) class Menu(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) menu_name = models.CharField(max_length=255) menu_items = RichTextField(blank=True) class Facilities(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) items = models.CharField(max_length=255) Created a form to turn charfield of Facilities into multi seclectable checkbox in admin panel. The code in my forms.py is as following: from .models import Facilities, facilities class FacilitiesForm(forms.ModelForm): items = forms.MultipleChoiceField(choices=facilities, widget=forms.CheckboxSelectMultiple) class Meta: model = Facilities exclude = ['created_at', 'updated'] The code in my admin panel: class MenuInline(admin.TabularInline): model = Menu max_num = 1 class FacilitiesInline(admin.TabularInline): model = Facilities form = FacilitiesForm max_num= 1 class RestaurantAdmin(admin.ModelAdmin): inlines = [ # RestaurantInline, MenuInline, FacilitiesInline, ] admin.site.register(Restaurant, RestaurantAdmin) It works fine when creating a new record. But, when I edit existing record Checkboxes set to unchecked. How can I keep the state of the checkboxes while editing the record? Do …