Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get number of objects into a merged queryset
I've developed a Django's view that merge two queryset usingchain; below the code. def sharedcategories_list(request): """ Con questa funzione definisco la lista dei post della singola categoria """ list = SharedCategories.objects.all() context = {"list": list} return render(request, "shared-categories/shared_categories_list.html", context) def single_sharedcategory(request, slug): object = get_object_or_404(SharedCategories, slug=slug) wms = OGCLayer.objects.filter(categories=object) webgis = WebGISProject.objects.filter(categories=object) context = { "single_object": object, "objects": list(chain(wms, webgis)), } template = "shared-categories/single_shared_categories.html" return render(request, template, context) The views use the models below: class SharedCategories(CategoryBase): icon = models.ImageField(upload_to=settings.UPLOADED_IMAGE_FOLDER, blank=True, null=True) is_active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("single-sharedcategory", kwargs={"slug": self.slug}) class OGCLayer(BaseModelPost, OpenLayersMapParameters): set_zindex = models.IntegerField(default=1) set_opacity = models.DecimalField(max_digits=3, decimal_places=2, default=1.0) ogc_layer_path = models.ForeignKey(GeoServerURL, related_name="related_geoserver_url", on_delete=models.PROTECT, blank=True, null=True) ogc_layer_name = models.CharField(max_length=100) ogc_layer_style = models.CharField(max_length=100, blank=True, null=True) ogc_bbox = models.CharField(max_length=250, blank=True, null=True) ogc_centroid = models.CharField(max_length=250, blank=True, null=True) ogc_legend = models.BooleanField(default=False) is_vector = models.BooleanField() is_raster = models.BooleanField() categories = models.ManyToManyField(SharedCategories, related_name="related_ogc_categories") def get_absolute_url(self): return reverse("ogc-single", kwargs={"slug": self.slug}) class WebGISProject(WebGISProjectBase): categories = models.ManyToManyField(SharedCategories, related_name="related_webgisproject_categories") basemap1 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap1", blank=False, null=True) basemap2 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap2", blank=True, null=True) basemap3 = models.ForeignKey(Basemap, on_delete=models.PROTECT, related_name="related_basemap3", blank=True, null=True) main_layer = models.ForeignKey(OGCLayer, on_delete=models.PROTECT, related_name="related_main_wmslayer") layers = models.ManyToManyField(OGCLayer, related_name="related_wmslayer", blank=True) def get_absolute_url(self): return reverse("map-single", kwargs={"slug": self.slug}) I need to view in the template how many objects are related … -
default image being reuploaded when new account created
On my profile model I have a default image. However I would expect that all accounts that have the default image would be reading the same image, but when a new account is created the default.jpg is being re uploaded to the s3 bucket. The issue is being caused by a compression function if i remove it and the on save code the issue goes away. how can i not have it re save default.jpg def compress(image): im = Image.open(image) out_put_size = (300,300) im.thumbnail(out_put_size) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object im = im.resize([500,500]) #resize image im = im.convert("RGB") im = im.save(im_io,'JPEG', quality=75) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, max_length=30) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): initial = self._state.adding #image compression start if self.image and initial: # call the compress function new_image = compress(self.image) # set self.image to new_image self.image = new_image #image compression end super(Profile,self).save(*args, **kwargs) -
django enter password to enter the room
So I wanna ask you guys a feature I want to add to my chatroom project. I created a Room model so you can enter there and send your messages there so everyone can see them. here comes the problem that i wanna create a private room so when you create the room , u enter a password . and whenever a user want to enter the room should enter a password. here's my private room view: class CreatePrivateRoomView(View): form_class = CreatePrivateRoomForm template_name = 'room/create_room.html' def get(self, request): form = self.form_class return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data room = Room.objects.filter(room_name=cd['room_name']) if room: messages.error(request, 'a room with this name is already exists', 'danger') return render(request, self.template_name, {'form': form}) privateroom_slug = slugify(cd['room_name'][:25], allow_unicode=True) privateroom = Room(room_name=cd['room_name'], slug=privateroom_slug) privateroom.set_is_private(True) privateroom.set_password(cd['password']) privateroom.save() messages.success(request, f"Room {cd['room_name']} created", 'success') return redirect('room:room_inside', privateroom.id, privateroom.slug) messages.error(request, 'not valid', 'danger') return render(request, self.template_name, {'form': form}) I'll be happy if anyone gives me the Idea so I can add this feature. -
StreamingHttpResponse works like HTTP response on server
I am using StreamingHttpResponse for SSE but it works like and http response on server class WorkshopNotificationAPIView(View): def get(self, request, *args, **kwargs): res = StreamingHttpResponse(BusinessService.workshop_notification(kwargs.get('workshop'), kwargs.get('type'))) res['Content-Type'] = 'text/event-stream' return res def workshop_notification(self, workshop_id: str, workshop_type: str): initial_data = "" while True: data = list(DB['workshop_gocoin_transactions'].find({'workshop_id': workshop_id, 'type': TransactionType.Credit}, {'_id': 0, 'source': 1, 'remark': 1}).sort('created_at', -1).limit(1)) if data and not initial_data == data[0]: initial_data = data[0] yield "\ndata: {}\n\n".format(data[0]) enter image description here enter image description here -
SQL Django Null Constraint Error - cannot resolve?
What am I doing wrong? Django Models: USER MODEL class User(AbstractUser): # DEFINE MODEL FIELDS related_person = models.OneToOneField(Person, on_delete=models.CASCADE, default='') user_id = models.BigAutoField(verbose_name='User ID', primary_key=True, serialize=False, auto_created=True) email = models.EmailField(verbose_name='Email', max_length=80, blank=False, unique=True, null=False, default='') is_verified = models.BooleanField(verbose_name='Email Verified', blank=False, default=False) date_joined = models.DateField(verbose_name='date joined', auto_now_add=True, null=True) last_login = models.DateField(verbose_name='last login', auto_now=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = None last_name = None username = None # IMPORT MODEL MANAGER CLASS objects = UserManager() # SET LOGIN FIELD USERNAME_FIELD = 'email' # SET REQUIRED FIELDS REQUIRED_FIELDS = ['is_verified'] PERSON MODEL class Person(models.Model): class Titles(models.TextChoices): MR = 'Mr', _('Mr') MRS = 'Mrs', _('Mrs') MISS = 'Miss', _('Miss') MS = 'Ms', _('Ms') DR = 'Dr', _('Dr') related_entity = models.OneToOneField(Entity, on_delete=models.CASCADE) person_id = models.BigAutoField(verbose_name='Person ID', primary_key=True, serialize=False, auto_created=True) first_name = models.CharField(verbose_name='First Name', max_length=50, blank=False, null=False) last_name = models.CharField(verbose_name='Last Name', max_length=50, blank=False, null=False) title = models.CharField(verbose_name='Title', max_length=4, choices=Titles.choices, blank=True, null=False, default='') alias = models.CharField(verbose_name='Alias', max_length=150, blank=True, null=False) I have a Sign Up form that saves a person's email to the User Model, and password to the User Model, after checking the email doesn't already exist, and passwords (when entered twice), match. but then I get this … -
Count objects from a merged queryset
I've developed a Django's view that merge two queryset. def single_sharedcategory(request, slug): object = get_object_or_404(SharedCategories, slug=slug) wms = OGCLayer.objects.filter(categories=object) webgis = WebGISProject.objects.filter(categories=object) context = { "single_object": object, "objects": list(chain(wms, webgis)), } template = "shared-categories/single_shared_categories.html" return render(request, template, context) I need to view in the template how many objects are related to objects. I know that it is possible to get a count of objects for a single model with {{ wms.related_wms.count }}. But how I can do the same thing in my case? -
How can I show an error message If the username already exists for creating an account?
When I go to create a new account by the same user name that already exists in the database, then shows the below error. I just want to show an error message (the user already exists, try again with a unique username) if the users exist. How can I fix these issues? What will be the condition? Problem: IntegrityError at /singup UNIQUE constraint failed: auth_user.username Request Method: POST Request URL: http://127.0.0.1:8000/singup Django Version: 3.2.3 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: auth_user.username Exception Location: C:\Users\DCL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\Business_Website', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Mon, 28 Feb 2022 18:15:25 +0000 views.handle_singUp: def handle_singUp(request): if request.method == "POST": userName = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = request.POST['email'] pass1 = request.POST['pass1'] #pass2 = request.POST['pass2'] myUser = User.objects.create_user(userName,email,pass1) myUser.first_name = fname myUser.last_name = lname myUser.save() messages.success(request,"Your account has been created!") return redirect("/") else: return HttpResponse("404-Not found the page") urls.py: urlpatterns = [ path('', views.index, name="index"), path('singup', views.handle_singUp, name= "handle_singUp"), path('login', views.handle_login, name="handle_login"), path('logout', views.handle_logout, name="handle_logout"), path('contact', views.handle_contact, name="handle_contact"), path('frontend_orders', views.frontend_orders, name="frontend_orders"), path('hire_me', views.hire_me, name="hire_me") ] -
Override a specific argument in all django model queries?
I have a custom django user model that does not contain a username field, it uses email instead. I am attempting to implement a 3rd party package that makes queries to the user model based on username. Is there a way to override all queries (get, filter, etc.) to this model through a custom manager or otherwise so that username is simply converted to email? It would turn this: User.objects.filter(username="grrrrrr@grrrrrr.com") into User.objects.filter(email="grrrrrr@grrrrrr.com") -
How to avoid polling the server for each individual result - htmx
I've got 3 django-celery tasks running independently, they each finish at different times and take anywhere between 20-45 seconds. I could poll the server through 3 different hx-triggers in order to get my 3 different results as they become available, however this seems like unnecessary load on the server, as I'd like to poll every 5 seconds. Ideally I'd just have 1 hx-trigger set up which polls for all 3 results and then places the results in their divs when they become available but I'm not sure how to achieve this - I can alter the front end, if needed, to make it possible. -
How to change add another[object] behavior in TabularInline
I want to make admin InlineTabular add another object button take me to the object add page with prepopulated fields instead of creating an inline model Add Another[Object] button I tried to override the html and add hard coded url in in the tag by sending extra context in my admin model but it didn't work class SupplierAdmin(admin.ModelAdmin): inlines = [ProductViewInline,] def change_view(self, request, object_id, form_url='', extra_context=None): extra = extra_context or {} extra['ProductUrl'] = 'http://localhost:8000/admin/products/product/add/' return super(SupplierAdmin, self).change_view(request, object_id, form_url, extra_context=extra) # Tabular.html <script> ProductUrl = '{{ ProductUrl }}' </script> # Inline.js const addInlineAddButton = function() { ... $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + `"><a href=ProductUrl>` + options.addText + "</a></tr>"); addButton = $parent.find("tr:last a"); } else { ... -
my getjson is not working can someone help me
I get the data with a fetch url. the whole function works, there are no errors. there is only one error and that is that is can't see the data on tamplate. the data is being fetched, I see that on console. Thanks in advance... views.py def check(request): if request: if request.method == 'POST': data = json.loads(request.body) employeId = data['id_s'] empinfo = Employe.objects.filter(id=employeId) print(empinfo.values) print(data) return JsonResponse({'info': list(empinfo.values())}, safe=False, status=200) return HttpResponse() index.html <script type="text/javascript"> $(document).ready(function() { $(".info-employe").click(function(event){ $.getJSON('/checks/', function(response) { for(var key in response.info) $('#name').append('<p> Name: ' + response.info[key].name + '</p>'); $('#surname').append('<p>Surname : ' + response.info[key].surname + '</p>'); $('#worknumber').append('<p> Work number: ' + response.info[key].work_number + '</p>'); $('#workplace').append('<p> Rank: ' + response.info[key].rank + '</p>'); $('#rank').append('<p> Workplace: ' + response.info[key].workplace + '</p>'); $('#email').append('<p> Email ' + response.info[key].email + '</p>'); $('#phone').append('<p> Phone ' + response.info[key].phone + '</p>'); }); }); }); </script> javascript fetch function function checkEmp(id_s, action){ var url = '/checks/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'id_s': id_s, 'action': action}) }) .then((response)=>{ return response.json() console.log(response); }) .then((data)=>{ console.log(data); }) } -
Why is Sweetify not working on my project?
Sweetify does not work in my project. I went ahead according to document but it does not work Does anyone know what the problem is? this is my view enter image description here -
Take CSV file from HTML form and create a table in sqllite in django
Right now I've tried using pandas and converting the file into json and then creating a table with it. This my code HTML File <body> <form action="upload/" method="post" enctype="multipart/formdata"> {% csrf_token %} <div class="block has-text-centered"> <h3 class="is-size-3 has-text-centered is-family-primary has-text-success-dark" > Upload a CSV File </h3> <div class="file is-medium has-name is-info is-centered" id="csv-file"> <label class="file-label"> <input class="file-input" type="file" name="csv" accept=".csv" /> <span class="file-cta"> <span class="file-icon"> <i class="fas fa-upload"></i> </span> <span class="file-label"> Choose a file… </span> </span> <span class="file-name"> No file uploaded </span> </label> </div> <br /> <input class="button is-outlined is-rounded is-info" type="submit" value="Submit" /> <input class="button is-outlined is-rounded is-info" type="reset" value="Reset" id="csv-reset" /> </div> </form> </body> </html> VIEWS File from django.shortcuts import render def home(request): return render(request, 'results/home.html', {}) CSV LOGIC (csvviews.py) from django.shortcuts import render import pandas as pd from django.contrib import messages def form_page(request): if request.method == 'POST': file = request.FILES.get(u'csv') df = pd.read_csv(file) df.to_json(turned_json) my_obj = CsvModel.objects.create(csv_file=turned_json) my_obj.save() messages.success(request, 'CSV Uploaded!') return render(request, 'results/home.html') MODELS File from django.db import models class CsvModel(models.Model): csv_file = models.FileField() But using this code I'm getting the following error Invalid file path or buffer object type: <class 'NoneType'> How do I solve this? Are there any specific packages for csv in django? … -
image being re-uploaded when updating object
On my blog post model I override the save method to call a function to compress the image being uploaded. This works as expected. However when I use an update view and make a change to the post the image is then re uploaded to the s3 bucket and replaces the original image on the model. If i remove all the code from the compress function and just have it return image, when using the update view it does not re upload the image. How can I prevent the image from being re uploaded when on the updateview. model: def compress(image): img = Image.open(image) img = img.convert("RGB") (w, h) = img.size # current size (width, height) if w > 2000: new_size = (w//2, h//2) # new size img = img.resize(new_size, Image.ANTIALIAS) (w, h) = img.size if w > 2000: new_size = (w//2, h//2) # new size img = img.resize(new_size, Image.ANTIALIAS) im_io = BytesIO() img.save(im_io, 'JPEG', quality=70, optimize=True) new_image = File(im_io, name=image.name) return new_image class Post(models.Model): image = models.ImageField(storage=PublicMediaStorage(), upload_to=path_and_rename, validators=[validate_image]) .... def save(self, *args, **kwargs): self.slug = slugify(self.title) if self.image: # call the compress function new_image = compress(self.image) # set self.image to new_image self.image = new_image super(Post,self).save(*args, **kwargs) view: class … -
django get_full_name in admin
I know there are lots of similar questions but I couldn't find an answer. I'm trying to access to the get_full_name() method in the admin of my project. I extended the Django User model with a Bio class, connected through a "user" OneToOneField and updated via signals as exposed here. The main class of my models.py, ObjetArchi, is also related to the User model through the "auteur" ForeignKey field. I'd like to show the users full name's, as allowed by the get_full_name() method, in every part of the admin: on list_display, list_filter and fieldsets, as well as in the ObjetArchi form. How and where should I write this method? models.py: class Bio(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, null=True ) coordonnees = models.CharField( max_length=300, verbose_name='Coordonnées institutionnelles de l\'auteur', help_text='300 caractères max.', blank=True ) site_web = models.URLField( verbose_name='Site web personnel', blank=True ) biographie = models.TextField( blank=True, null=True, ) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Bio.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.bio.save() (...) class ObjetArchi(gis_models.Model): id = models.AutoField( primary_key=True, verbose_name= 'Identifiant' ) titre = models.CharField( max_length=100, verbose_name='Titre', blank=True, null=True ) date = models.DateField( default=timezone.now, verbose_name='Date de publication' ) auteur = models.ForeignKey( User, on_delete=models.SET_NULL, related_name='objets_archi_user', verbose_name='Auteur.e', blank=True, null=True ) resume … -
DRF error [<class 'decimal.ConversionSyntax'>] when calling a function in serializer
Below is my function in django models. def calc_totals(self): self.total_net_purchase_price = F('quantity') * F('net_purchase_price') self.total_net_sales_price = F('quantity') * F('net_sales_price') self.total_gross_purchase_price = F('quantity') * F('gross_purchase_price') self.total_gross_sales_price = F('quantity') * F('gross_sales_price') self.total_net_profit = F('total_net_sales_price') - F('total_net_purchase_price') self.total_gross_profit = F('total_gross_sales_price') - F('total_gross_purchase_price') When I call this function in DRF serializer: class PZItemSerializer(CountryFieldMixin, serializers.ModelSerializer): class Meta: model = PZItem fields = '__all__' def update(self, instance, validated_data): instance.calc_totals() instance.save() return instance It throws error: [<class 'decimal.ConversionSyntax'>] What's wrong? -
Accessing MongoDB Collection on Django
I have created table on MongoDB Atlas and trying to access it on Django Admin panel. I know how to create table and display on admin panel using models.py. But I am trying to do reverse here for example creating table(Collection) on Atlas MongoDB and access it on Django admin panel. How does that work? -
django-csp lib stripping single quotes?
I'm facing a weird behaviour with django-csp==3.7 and djangosaml2==1.3.3 I have spent a couple hours trying to find out why this happens, and I really don't see what the reason could be. I'm trying to add an exception to a viewset for which I'm willing to allow unsafe-inline The parent view is https://github.com/IdentityPython/djangosaml2/blob/v1.3.3/djangosaml2/views.py#L98 from djangosaml2.views import LoginView class CustomLoginView(LoginView): def get(self, request, *args, **kwargs): response = super().get(request) response._csp_update = {'script-src': ("'unsafe-inline'",)} return response However, when the header gets into the browser, I'm getting unsafe-inline instead of 'unsafe-inline' (note the single quotes) It does not happen in other views of the same project, where I get the expected outcome. -
The view home.views.login_view didn't return an HttpResponse object. It returned None instead
I am trying to create role based login system but it continuously showing the mentioned error N.B: I'm new to django ''' 'def login_view(request):' 'form = AuthenticationForm()' 'if request.method=='POST':' 'username = request.POST.get('username')' 'password = request.POST.get('password')' 'user = authenticate(username=username, password=password)' 'if user is not None and user.is_student==True:' 'login(request,user)' 'if request.GET.get('next'):' 'return render(request.GET.get('next'))' 'else:' 'return redirect('homepage')' ''' -
django query annotate values get list from reverse foreign key
I have a simple model like class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Blog(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) Here I want to query all authors with the title of all the blogs they have written like Author One : Blog One, Blog Two, Blog Three I want this from query and not loop Here my approach is to use subquery like blogs =Blog.objects.filter(author=OuterRef('pk')).values("title") authors = Author.objects.annotate(blogs=Subquery(blogs), output_field=CharField()) But here I am getting error like sub-select returns 2 columns - expected 1 How can I get all the authors with all the blogs they have written ? I do not want to use loop. I want this through query -
Django flush command doesn't clear all tables
I have a django app that contains 4 modules. Each of is modules store data into a table in the database. Which leaves us with 4 tables. When I run a flush command in order to delete existing data in these tables : python manage.py flush --noinput It clears data from 2 tables, but leaves data in the 2 other tables. I find it weird as a behavior. Do you have an idea on how is this possible to solve ? -
Django, Create domain block list for sign up
I am trying to create domain block list for my sign up form and I am having an issue. I made table for domain block list and I want sign up form to raise error if domain is in block list. Apparently, my code doesn't work unless I hardcode it. How do I make this work? :( class MyCustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') company_name = forms.CharField(max_length=50, label='Comapny Name') class Meta: model = DomainBlock fields = ('blocklist') ## block common domain from sign up def clean_email(self): data = self.cleaned_data['email'] if data.split('@')[1].lower() in 'blocklist': raise forms.ValidationError("This email is not allowed") # if data.split('@')[1].lower() == 'gmail.com': # raise forms.ValidationError("Gmail is not allowed") # if data.split('@')[1].lower() == 'msn.com': # raise forms.ValidationError("MSN email is not allowed") # if data.split('@')[1].lower() == 'yahoo.com': # raise forms.ValidationError("Yahoo email is not allowed") return data -
Null ID in Django Admin
I'm trying to add a new product in my Products model in Django Admin, yet for some reasons the id field always become null after adding. Below is my code: models.py from django.db import models class Products(models.Model): id = models.BigAutoField(primary_key=True) # incremental id title = models.CharField(max_length=200) def __str__(self): return self.title admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import * class ProductsAdminConfig(ImportExportModelAdmin): model = Products search_fields = ('title',) list_filter = ('title', ) list_display = ('id', 'title', ) admin.site.register(Products, ProductsAdminConfig) Originally I created my database table Products with SQLAlchemy, converting CSV to Mysql. However, I wanted to be able to add a new product inside Django Admin as well. I have tried emptying my SQL table, clearing my migration folder and run py manage.py makemigrations and py manage.py migrate, but the error still persisted. When I tried adding a new product, the data rows with null ids still got generated. Could you suggest me a way to solve this? Thank you! -
How to add a object to a users watch list via a link in Django
I have a website that recommends anime and I want each anime to have some text besides them as they appear, offering to add to a users 'list' which is a page where all anime in the users account-unique list will be shown. I have it working, and can add via the django admin but not via a button on the website. models.py class UserList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) anime_in_list = models.ManyToManyField(Anime, blank=True) views.py @login_required def userList(request): return render(request, 'userlist.html') def add_to_userlist(request, anime_id): new_anime = get_object_or_404(Anime, pk=anime_id) #if UserList.objects.filter(user=request.user, anime_in_list=anime_id).exists(): #message fail user_list, created = UserList.objects.get_or_create(user=request.user) user_list.anime_in_list.add(new_anime) return render(request, "userlist.html") on the html where the anime shows <a href="{% url 'add_to_userlist' anime.id %}" role="button" class="btn btn-outline-success btn-lg">Add to list?</a> but navigating to the anime html page now the error NoReverseMatch at /anime/ Reverse for 'add_to_userlist' not found. 'add_to_userlist' is not a valid view function or pattern name. But I don't want to create a separate url to redirect them, I just want pressing the to add to the users list, and if the user now navigates to their /userlist, they find that it has updated with the anime they clicked the link on. Any help would be super appreciated, ty -
SwiftUI remove authorization for post requests
I'm trying to remove the authorization requirement for post requests to my Django API, but nothing seems to be working. Currently I have this basic authorization header, which allows the one user to send requests: request.addValue("Basic YWRtaW46dGVzdDEyMzQ1", forHTTPHeaderField: "Authorization") My question is, what do I need to put here to allow all requests? I tried just removing it all together, but it results in a forbidden request. I also tried adding this to my Django viewset: permission_classes = [permissions.AllowAny] Let me know if additional info is needed, thanks.