Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Printing a 2d list in Django template
I have a model with a JSONField class Session(models.Model): title = models.CharField(max_length=50) application_list = JSONField(blank=True, null=True) and i want to bring the values on frontend and use it through django template for some filtering. An example of what this JSONField may contain: [{"type": "questionnaire", "primary_key": "13"}, {"type": "questionnaire", "primary_key": "4"}, {"type": "questionnaire", "primary_key": "8"}]. I managed to get the data in a list with: app_data = Session.objects.values_list('application_list', flat=True) pub_data = [] for app in app_data: for x in app: pub_data.append( [x['type'], x['primary_key']]) print(pub_data) which prints [['questionnaire', '13'], ['questionnaire', '4'], ['questionnaire', '8'], ['seriousgame', '16']]. My question is how do I access each individual 'type' and 'key' in django template. I tried using {% for app in pub_data %} {{app}} {% endfor %} or with app(0) app[0] but none of them work. -
How do I make a ModelChoiceField's values show the actual values on a page instead of numbers?
There is a field (categories) in my form (NewListing) that should has 4 values that can be selected in a form on one of my pages. However, when I want to show which value was selected I get a number instead of the value. The values are: New Refurbished Opened Used So if New was selected earlier, when this value is shown on another page it is shown as 1 instead of New. How do I fix this? models.py: class Listing(models.Model): ... condition = models.CharField(max_length=20) forms.py: condition_choices = ( (1, 'New'), (2, 'Refurbished'), (3, 'Opened'), (4, 'Used'), ) class NewListing(forms.Form): ... condition = forms.ChoiceField(choices=condition_choices, widget=forms.Select(attrs={ 'class': 'condition', })) html: (irrelevant but shows where it would be used - it selected on another page though - this works fine) <div class="condition"> <p> Condition: <strong> {{ listing.condition }} </strong></p> </div> -
Django filter then count objects in queryset that don't match user
I have committees where you cannot vote on yourself. I am trying to have committee_member_count filter out users where the user matches the approval_request's provider. How can I filter out credentialing_committee_members that match the provider? This was my attempt: "credentialing_committee__members", distinct=True, filter=~Q(credentialing_committee__members=self.first().provider.user), ), -
Django | set the default value of a model field to be the email of the logged in user
I'm trying to display user specific content in my django website and I am one step away from completing this task. In models.py I need the contact_email field to have its default value to be the email of the logged in user. I've tried many methods of doing this but nothing has worked yet. models.py class Account(AbstractUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) name = models.CharField(max_length=45, unique=False) username = models.CharField(max_length=100, default='') date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'is_employee'] objects = MyAccountManager() class Meta: permissions = [ ("post_jobs", "Can post jobs"), ] def __str__(self): return self.name def has_perm(self, perm, obj=None): return True def has_perms(self, perm): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Job(models.Model): company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer") description = models.TextField(null=True) role = models.CharField(max_length=25) area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="") contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='')#stuck on setting this default created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) def __str__(self): return self.company views.py @login_required(login_url='login') def manage_jobs(request): if request.user.is_employee: return redirect('home') else: form = … -
Django form showing up in template as form variable name
I have created a custom user model in Django and am trying to create a login form. Instead of the form showing up in the Django template, login_form, the name of the variable, shows up. forms.py class ProfileLogin(forms.ModelForm): password = forms.CharField(label="Password", widget=forms.PasswordInput) class Meta: model = Profile fields = ("username", "password") def clean(self): username = self.cleaned_data.get('username', None) password = self.cleaned_data.get('password', None) if not authenticate(username=username, password=password): raise forms.ValidationError("Invalid username and/or password.") return None views.py def login_views(request): context = {} user = request.user if user.is_authenticated: return redirect('index') if request.POST: login_form = ProfileLogin(request.POST) if login_form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: login(request, user) return redirect('index') else: login_form = ProfileLogin() context['login_form'] = ['login_form'] return render(request, "capstone/login.html", context) html <form method="post"> {% csrf_token %} {% for field in login_form %} <h5>{{ field.label_tag }} {{ field }} {% if field.help_text %} <span>{{ field.help_text }}</span> {% endif %} {% for error in field.errors %} <p>{{ error }}</p> {% endfor %} {% if login_form.non_field_errors %} <div>{{ login_form.non_field_errors }}</div> {% endif %} </h5> {% endfor %} <button type="submit">Login</button> </form> I tried changing {% for field in login_form %} <h5>{{ field.label_tag }} {{ field }} to {{ login_form }}, but the same thing happens. … -
Edit Form Submit handler for a Model
I have a fairly simple django model in a Wagtail CMS; essentially: from django.db import models class Thingy(models.Model): name = models.CharField(max_length=255, blank=False, null=False, unique=True) # Many other fields. panels = [ FieldPanel("name"), # ... ] I need to perform an action when this model is saved via the Wagtail model edit form (eg /admin/section/thingy/123/edit). Currently, I have registered a post_save signal, however this has resulted in the method being called when the model is saved programmatically (via an import sync task). I've had a look in the Django docs, but can't see anything obvious... is there a way to register a signal for the form submission (ideally after the internal submission and save is handled). (If it's any relevance; I need to trigger a search reindex based on a relation to the model; anything that references instance 123 of thing Things that was saved needs to be reindexed) -
Set Django Rest Framework endpoint a timeout for a specific view
I'm running Django 4.0.5 + Django Rest Framework + Gunicorn Sometimes, I'm going to need to handle some POST requests with a lot of data to process. The user will wait for a "ok" or "fail" response and a list of ids resulting from the process. Everything works fine so far for mid size body requests (this is subjective), but when I get into big ones, the process will take 1min+. It's in these cases when I get a 500 error response from DRF, but my process in the background will keep running till the end (but user will not know it finished successfully). I was doing some investigation and changed the Gunicorn timeout parameter (to 180), but didn't change the behavior in the service. Is there a way to set a timeout larger than 60s at the @api_view or somewhere else? -
Django join tables with ForeignKey
I'm trying to join 3 tables with ForeignKey but it returns Null values. Here are my models: class schedule(models.Model): login_id = models.CharField(primary_key=True,max_length=20) agent_name = models.CharField(max_length=100, blank=True, null=True) team = models.CharField(max_length=100, blank=True, null=True) class place_no(models.Model): place_id = models.CharField(max_length=50, blank=True, null=True) pc_no = models.CharField(max_length=50, blank=True, null=True) class Insight(models.Model): login_id = models.CharField(primary_key=True,max_length=20) place_id = models.CharField(max_length=50, blank=True, null=True) agent_name = models.ForeignKey(schedule, on_delete=models.CASCADE,blank=True, null=True) pc_no = models.ForeignKey(place_no, on_delete=models.CASCADE,blank=True, null=True) My View: def listings(request): data = Insight.objects.select_related('agent_name', 'pc_no') return render(request, 'pages/listings.html', {'data':data}) -
JSON Parse error: Unrecognized token '<' while requesting/posting data with react-native and django
I just started building a react-native frontend and a Django backend application and I tried making requests from react native to the Django server but I got "JSON Parse error: Unrecognized token '<'" I am assuming that this is caused by an error in the API code but I could not figure it out. here's my code: views.py- from django.shortcuts import render from rest_framework import viewsets, status from .serializers import UserSerializer, ProfileSerializer from .models import Profile from rest_framework.response import Response from rest_framework.decorators import action from django.contrib.auth.models import User from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer @csrf_exempt def login(request): if request.method == 'POST': valid = False if 'username' in request.data: username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: valid = True else: valid = False elif request.method == 'GET': valid = True data = { 'valid': valid, } return JsonResponse(data) login.js- import { StatusBar } from 'expo-status-bar'; import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView } … -
Django duplicate value violates unique constraint using Objects.create()
I have this object for save files: class File(Base): title = models.CharField(max_length=512, default="arquivo", verbose_name=_('Title'), blank=False) filename = models.FileField(max_length=512, verbose_name=_('File'), help_text=_("Select the logo file."), blank=False, null=False) slug = models.SlugField(max_length=512, verbose_name=_('Slug'), blank=False, null=False) extension = models.CharField(max_length=16, verbose_name=_('Extension'), blank=True, null=False) mimetype = models.CharField(max_length=256, verbose_name=_('Mimetype'), blank=True, null=False) size = models.IntegerField(blank=False, verbose_name=_('Size'), null=False) def save(self, *args, **kwargs): self.title = self.filename self.extension = self.filename.url.split('.')[-1] self.slug = slugify(self.filename) self.mimetype = self.filename.file.content_type self.size = self.filename.file.size super().save(*args, **kwargs) # Call the "real" save() method. # rename the file to new id pattern file_id = ('file_%019d' % self.id) current_directory = os.path.dirname(self.filename.path) os.rename(self.filename.path, f'{current_directory}/{file_id}') self.filename = file_id super().save(*args, **kwargs) The method save() it works when i add one file by admin page, the FileAdmin: @admin.register(File) class FileAdmin(admin.ModelAdmin, Base): form = FileModelAdminForm def save_model(self, request, instance, form, change): return Base.custom_save_model(self, request, instance, form, change) But, when i try create a File objects using File.objects.create(filename=file, user=request.user) return IntegrityError: duplicate key value violates unique constraint "core_file_pkey" DETAIL: Key (id)=(id_number) already exists. This is the code: number_file = request.FILES.get('number_file') f = File.objects.create(filename=number_file, user=request.user) The object is created in database, but without update the filename. The problem is in the second super().save(*args, **kwargs), but why this it work in normal insertion on Django Admin Page? -
Django - Accessing a boolean field of a model in html
My profile model has a BooleanField called teacher_status, and I want to give users with the teacher_status as True extra features within the website, and I am having trouble accessing the field. Profile model class Profile(models.Model): RANKS = [(f'{i}D', f'{i}K') for i in range(1,19)] for i in range(1, 10): RANKS.append((f'{i}D', f'{i}D')) user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') bio = models.CharField(max_length=225, blank=True, default='') rank = models.CharField(max_length=3, default='18K', choices=RANKS) teacher_status = models.BooleanField(default=False) def __str__(self) -> str: return f"{self.user.username}'s Profile" def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: img.thumbnail((300,300)) img.save(self.image.path) This is what I did in the html: {% if user.is_authenticated %} {% if user.profile.teacher_status == true %} <a class="btn btn-primary" href="{% url 'post-create' %}">Create Post</a> {% endif %} {% endif %} -
django cors headers not working (yes ik a 100th people asked before but their solutions didn't work)
my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'channels', 'chatterapi', 'chatterchannels', "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_ALL_ORIGINS: True *the chatter apps are my apps, and i'm also using django channels. tried moving cors headers up and down but had no luck. idk how to get the actual headers but here is the log : my views.py ? @api_view(['POST']) def createRoom(request): key = get_random_string(15) request.POST._mutable = True request.data['key'] = key request.POST._mutable = False print(request.data) serializer = RoomSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=400) I really don't know what's going on, let me know if there is any way I can help. Is it possible that django channels overriding the runserver command is causing a conflict or something? (if that sounds dumb, please forgive me, cause I AM dumb) -
How can i order queryset by another model data?
I have three models and i wanna order Products.objects.all() by is_it_good from ProductsRating model. How can i do it? I was traing something like: qs = Products.objects.annotate( biggest_rating = Max('productsrating__is_it_good') ).order_by('biggest_rating') but then i get an error "Cannot resolve keyword 'productsrating' into field" models.py class CusUser(AbstractUser): pass class Products(models.Model): name = models.CharField(max_length=300) category = models.CharField(max_length=300) cost = models.IntegerField() class ProductsRating(models.Model): is_it_good = models.IntegerField(validators=[MaxValueValidator(0), MinValueValidator(5)]) whose_rated = models.ForeignKey(CusUser, on_delete=models.CASCADE) -
What are best practices for API error response handling?
It is best practice to handle such API errors by try and catch or the API response suppose to be like Google, Facebook and Microsoft API call Google API call example Facbook API call example Microsoft API call example -
How do I get the current item in the model from the request?
When a submit button is clicked, I want to be able to know what item the user was on. The button would be on an item's page that the user gets taken to when they click on an item. This button is is part of a django form (PlaceBid) that allows the user to bid for the item. So I want to be able to update what the item's highest bid is if the bid is higher than the current highest. This means that I need to know what item the user was viewing. I also want to save the bid in a model called Bid and in that model I also need to know what listing the bid is for. So how do I get the correct item from the model? The models: Listing() is the model for the item Bid() is the model for the bid views.py: def bid(request): if request.method == 'POST': form = PlaceBid(request.POST) if form.is_valid(): current = Listing.objects.get(pk=request.id) # my attempt to get the current item highest = current.highest_bid if form.cleaned_data['bid'] < highest: obj = Bid() obj.price = form.cleaned_data['bid'] obj.item = current obj.user = User.objects.get(pk=request.user.id) obj.save() current.highest_bid = form.cleaned_data['bid'] current.save() return HttpResponseRedirect(request.path_info) forms.py: class PlaceBid(forms.Form): … -
'function' object has no attribute 'owner'
@login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) _check_topic_owner(request) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context) def _check_topic_owner(request): if topic.owner != request.user: raise Http404 The problem is when im trying open page in web app. Is thow problem "'function' object has no attribute 'owner'" -
Multiselect field in Django
I have a product model with multiselect field in django with choices. So that vendors can choose for which age group the product is for and customers can filter products based on their age. The issue here is if the vendor selects two age groups the products is for. eg. Child and Adult. In database it is put as Age(Child, Adult). Then if the customer must filter that product using only child or adult it won't display the product. The customer choose both to display. Clearly I don't want this to happen. I want the customer filter the product either by child or adult or both. Here is the code: {% for i in aging %} <li class="list-group-item"> <input class="filter-checkbox" data-filter="age" value="{{ i.0 }}" type="checkbox" />&nbsp; {{ i.1 }} </li> {% endfor %} def filter_data(request): age_group = request.GET.getlist('age[]') products = Product.objects.all().order_by('-id').distinct() if len(age_group) > 0: products = products.filter(age=age_group).distinct() t = render_to_string('ajax/category-products.html', {'data': products}) return JsonResponse({'data': t}) $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this).val(); var _filterKey=$(this).data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); // Run Ajax $.ajax({ url:'/filter-data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ console.log(res); $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); Please tell me if there is other way. I have been on this for several days. -
connection to server at "databaseendpoint", port 5432 failed: FATAL: password authentication failed for user "databasename"
I have a Django project which is deployed to Heroku and has been linked to a website domain name (e.g. https://www.myapp.com). I've recently tried connecting it to an AWS RDS Postgres Database, however when I try to access the site using my website URL and perform a POST request it comes up with the error in the title. What's interesting is that it works fine using the Heroku domain name (appname.herokuapp.com) and if I run it locally. Even more bizarre is that it's trying to use the database name as the username and I cannot find any reference to this in my code. Any help with this would be appreciated, I'm going round in circles here. Details: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) (only uses this when running it locally) Heroku Config Vars postgres://username:password@database-1.xxxxxxxx.eu-west-2.rds.amazonaws.com:5432/databasename I've tried removing the config and running heroku run python3 manage.py migrate to revert to the sqlite database and it still tries to look at the postgres db with the database name as the user Are there any other sources I have forgotten about where I define the database details? -
Django: Filter on model column with Regex
I have phone numbers stored as (921) 414-1313 in the database and I want to run a search lookup on that field, but I don't want to force them to include (, ' ', ) or -. I'm using Postgres and tried to work with SearchVector initially, however it ran into the same challenge (so for now, I'm doing it the old fashioned way). I have a model definition that returns an "unformatted" number as 9214141313, but I can't figure out how to query against my custom definition inside of the model? Ultimately, I want a customer to be able to type in 921414 and get the response for the matching record. GitHub: https://github.com/varlenthegray/wcadmin/blob/dev/main/views.py#L25 Model: class JobSite(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) quickbooks_id = models.IntegerField(editable=False, null=True, blank=True) name = models.CharField(max_length=200, null=True, blank=True) first_name = models.CharField(max_length=200, null=True, blank=True) last_name = models.CharField(max_length=200, null=True, blank=True) print_on_check_name = models.CharField(max_length=200, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) address_2 = models.CharField(max_length=200, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=20, null=True, blank=True) phone_number = models.CharField(max_length=30, null=True, blank=True) email = models.CharField(max_length=400, null=True, blank=True) service_interval = models.IntegerField(default=12) next_service_date = models.DateField(null=True, blank=True) primary_technician = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) active = models.BooleanField(default=True) access_code = models.CharField(max_length=10, … -
How Initial Foreign Key event in Function based View in Django
I have two models, one is link to the other using foreign key. The Event model is view on the detail page. What I want is to initial the foreign key foreign element to the my Function based view that helps me process the form in Ajax and save. I want to initial the event field with the current Event being viewed Views.py def create_attendance(request, slug): model = get_object_or_404(Event, slug=slug) context = { 'event': model } response_data = { 'msg':'Your form has been submitted successfully' # response message } if request.POST.get('action') == 'post': fullname = request.POST.get('fullname') phone_number = request.POST.get('phone_number') email = request.POST.get('email') company = request.POST.get('company') position = request.POST.get('position') event = model.objects.get(event=name) Attendance.objects.create( fullname = fullname, phone_number = phone_number, email = email, company = company, position = position, event = event ) return JsonResponse(response_data) print(event) return render(request, 'create_attendance.html', context) Model.py class Event(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) slug = models.SlugField(max_length=150, blank=True) class Attendance(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, null=True, blank=True) fullname = models.CharField(max_length=100) -
Is there a way to collapse Django Admin Modules in the lefthand nav sidebar?
In a project with multiple app modules, each containing many models, the lefthand side navbar of the default Django admin page has a lot of entries which results in a lot of scrolling. Is there a way to collapse or toggle the visibility of a single module? A cursory glance through the Django docs was unfruitful, but that doesn't mean it isn't there. -
should i have a table for each product type in a database
i am very confused about this, i have three different types of products, first i have physical products which simply are art products and affiliate products, and digital products such as courses , books, art pictures, my first approach was to create a separate table for each one like this: class Category(models.Model): name = models.CharField() class ArtType(models.Model): name = models.CharField() class PhysicalArtProduct(modes.Model): category = models.ForeignField(Category) madeOf = models.ManyToManyField(AffeliateProduct) artType = models.ForeignKey(ArtType) ........ class AffeliateProduct(models.Model): ........ class Course(models.Model): artType = models.ForeignKey(ArtType) ....... class Book(models.Model): ....... because PhyscialArtProduct are related to AffeliateProduct because PhysicalArtProduct are made of AffeliateProduct that's why i had to add many-to-many field in PhysicalArtProduct my second approach is to make a single Product table and a ProductType table and build the relationship between the products themselves and the category and arttype by adding the necessary tables which approach i should go with here, any help would be really appreciated -
Django Import-Export import error - localtime() cannot be applied to a naive datetime
Using: Python 3.10.4 Django 4.06 Django-import-export 2.8.0 I am trying to import data to use as demo data into my django application. I keep getting an error of localtime() cannot be applied to a naive datetime (after working around another error that I asked separately). I am not worried about this particular field being naive datetime. It's one that needs to be set manually in real application. ### models.py class Reservation(models.Model): reservation = models.OneToOneField(Vehicle, on_delete=models.CASCADE, primary_key=True,) delivered = models.BooleanField('Delivered',default=False) date_reserved = models.DateTimeField('date reserved', default=datetime.datetime.now) ... ### admin.py class ReservationResource(resources.ModelResource): class Meta: model = Reservation exclude = ('id',) import_id_fields = ('reservation',) fields = ( 'reservation', 'delivered', 'date_reserved', ... ) class ReservationImportExport(ImportExportModelAdmin): resource_class: ReservationResource @admin.register(Reservation) class ReservationAdmin(SimpleHistoryAdmin, ReservationImportExport): fields = ["delivered","date_reserved",...] ### demo-reservations.yaml (Note: Problem happens using different data file formats) - reservation: 50001 delivered: False date_reserved: 7/15/2022T00:00:00+00:00 ... Here's the error (slightly obfuscated) Line number: 1 - localtime() cannot be applied to a naive datetime 50001, False, 7/15/2022T00:00:00+00:00, CHRIS EDWARDS, 16, ROSE TYLER Traceback (most recent call last): File "c:\Users\...\lib\site-packages\import_export\resources.py", line 670, in import_row diff = self.get_diff_class()(self, original, new) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 221, in __init__ self.left = self._export_resource_fields(resource, instance) File "c:\Users\...\lib\site-packages\import_export\resources.py", line 242, in _export_resource_fields return [resource.export_field(f, instance) if instance else … -
How two make the object to update of a form static?
I have some objects created. I would like updating them if needed. Problem : If I try to update one object his title change. For example: I would like to update this object «2022-07 - Django - tesr - Multi-device - IAB - CPM». The string to update is testr to test. How can I do that without changing the header. @login_required def update_campaign_naming_tool(request, pk): # Instance to update cnt = get_object_or_404(CampaignNamingTool, id=pk) if request.method == 'POST': form = CampaignNamingToolForm(data=request.POST, instance=cnt) if form.is_valid(): form.save() msg = "«{}» successfully updated".format(str(cnt)) messages.success(request, msg) return redirect('list_of_campaign_naming_tool') else: msg = "{} already exists. \ Please check your attributes !".format(form.instance) messages.error(request, msg) context = { 'cnt': str(cnt), 'form': form, } return render(request, 'update.html', contex) form = CampaignNamingToolForm(instance=cnt) context = { 'cnt': str(cnt), 'form': form, } return render(request, 'update.html', context) The form -
Blocked by CORS policy - 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'
I am trying to send a POST request to my backend but keep getting an error. Access to XMLHttpRequest at 'http://localhost:8000/api/create-room' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am using Django + Next.js. I have the django-cors-headers dependency installed. In settings.py I have included 'corsheader' in INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' in MIDDLEWARE. I am also using the config CORS_ALLOW_ALL_ORIGINS: True. For the frotend, I am sending the POST request using axios. axios.post('http://localhost:8000/api/create-room', {some data}) In past projects, I've never had this problem sending requests to my Django backend. How can I satisfy the access control check No 'Access-Control-Allow-Origin' header is present on the requested resource.