Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enforcing permissions through a related model in Django Rest Framework
I'm working on building out permissions for an API built with Django REST Framework. Let's say I have the following models: from django.db import models class Study(models.Model): pass class Result(models.Model): study = models.ForeignKey(Study) value = models.IntegerField(null=False) I have basic serializers and views for both of these models. I'll be using per-object permissions to grant users access to one or more studies. I want users to only be able to view Results for a Study which they have permissions to. There are two ways I can think of to do this, and neither seem ideal: Keep per-object permissions on Results in sync with Study. This is just a non-starter since we want Study to always be the source of truth. Write a custom permissions class which checks permissions on the related Study when a user tries to access a Result. This actually isn't too bad, but I couldn't find examples of others doing it this way and it got me thinking that I may be thinking about this fundamentally wrong. Are there existing solutions for this out there? Or is a custom permissions class the way to go? If so, do you have examples of others who've implemented this way? -
Django filter by many-to-many field doesn't work
There is a model of Article and it has many-to-many categories field. I want to filter it by that field but it doesn't work as i expected. For example: MyModel.objects.filter(categories__id__in = [0, 1, 2]) it gets model with categories 0 and 1 even if it hasn't category with id 2. i tried something like this: MyModel.objects.filter(Q(categories__id = 0) & Q(categories__id = 1) & Q(categories__id = 2)) but it even doesn't work. it doesn't even gets model if it has all of this categories. By the way, i don't want to use more than 1 filter method So, is there any solution for me? Thanks. -
Rules in views for custom user types
in my app I created two types of users by one-to-one relations. class Teacher(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... class Student(models.Model): user = models.OneToOneField(AuthUser, primary_key=True, on_delete=models.CASCADE) ... in views now I'm checking user role as follows: student = Student.objects.get(pk=request.user.id) teacher = Teacher.objects.get(pk=request.user.id) but it throws an exception, which better way should I use it? -
Deploy django app with gunicorn and nginx. ERROR supervisor: child process was not spawned
I'm trying to deploy my django app in a digital ocean droplet. I'm using nginx and gunicorn following this tutorial This is how gunicorn_start looks like #!/bin/sh NAME="PlantArte" DIR=/home/paulauzca/PlantArte USER=paulauzca GROUP=paulauzca WORKERS=3 BIND=unix:/home/paulauzca/run/gunicorn.sock DJANGO_SETTINGS_MODULE=project.settings DJANGO_WSGI_MODULE=project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME\ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- This is PlantArte.conf file #!/bin/sh [program:PlantArte] command=/home/paulauzca/bin/gunicorn_start --daemon user=paulauzca startsecs=0 autostart=true autorestart=true redirect_stderr=true environment=PYTHONPATH=$PYTHONPATH:/home/paulauzca/bin/python stdout_logfile=/home/paulauzca/logs/gunicorn-error.log Following the tutorial I run sudo supervisorctl status PlantArte And I always get PlantArte RUNNING pid 3566, uptime 0:00:00 With 0 second runtime. Which is weird. If I go into gunicorn-error.log I get supervisor: couldn't exec /home/paulauzca/bin/gunicorn_start: EACCES supervisor: child process was not spawned I've tried the "solutions" to this problem I've found on the internet but there is not much information about this... -
Django and SuspiciousFileOperation:Detected path traversal attempt
I find myself in an odd situation only when deployed (debug == false): My model throws a path traversal attempt exception. I want to create a directory for every file uploaded and save the file within the directory (some.zip) used in example. In my dev environment I have no problems and everything works just fine. models.py: class Template(models.Model): def get_folder(self, filename): filename_PATH = Path(filename) template_dir = filename_PATH.stem return Path(settings.TEMPLATES_FOLDER).joinpath(template_dir, filename) name = models.CharField("template", max_length=32, unique=True) file = models.FileField("templatefile", upload_to=get_folder, null=True, max_length=260, storage=OverwriteStorage()) class OverwriteStorage(FileSystemStorage): #this is actually above def get_available_name(self, name, max_length=None): self.delete(name) return name forms.py: class TemplateAdminForm(forms.ModelForm): def __init__(self,*args,**kwargs): super().__init__(*args, **kwargs) class Meta: model = Template fields = ["name", "file", ] def clean(self): cleaned_data = super().clean() upFile = Path(str(cleaned_data["file"])) if upFile.suffix == ".zip": path = self.instance.get_folder(cleaned_data["name"]) logging.error(f"{path}") unpack_zip(path) ## works! the directory is created/filled else: raise forms.ValidationError("unknown file type ...") logging.error("DONE!") # I see this output return cleaned_data ## signal to see when the error might be happening: @receiver(post_save, sender = Template) def testing(sender, **kwargs): logging.error("we never get here") settings.py: TEMPLATES_FOLDER = PATH(MEDIA_ROOT).joinpath("TEMPLATES") but: ERROR:django.security.SuspiciousFileOperation:Detected path traversal attempt in '/opt/project/media_root/TEMPLATES/some/some' WARNING:django.request:Bad Request: /admin/appName/template/add/ -
How to get categories in django
I have a django programme of diffrent categories of books and I want to get the books in a particular category. I can do this using django, but when using rest framework I get stuck at various points.I have the following blocks of code: models.py class Category (models.Model): name = models.CharField(max_length=20, db_index=True) slug = models.SlugField(max_length=40, unique=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name serializers.py class categories_serializer(serializers.ModelSerializer): class Meta: model = Category fields = "__all__" views.py class product_CategoryView(generics.ListCreateAPIView): serializer_class = categories_serializer def get_queryset(self): return { "categories": Category.objects.all() } ================ class Book(models.Model): categories = models.ManyToManyField(Category) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="book_owner") name = models.CharField(max_length=150) slug = models.SlugField(max_length=255, blank=True, null=True) product_class = models.CharField(max_length=50) image = models.ImageField(upload_to="images/books/") .... Whenever I try to access the category using path(book/category', views.book_CategoryView.as_view(), name="book_category"),, I encounter the following error: AttributeError at /book/category Got AttributeError when attempting to get a value for field `name` on serializer `categories_serializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'name'. I don't understand why I am getting the error. How do I go about this? -
http.client - ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
def checkUrl(url): p = urlparse(url) conn = http.client.HTTPConnection(p.netloc) conn.request('HEAD', p.path) resp = conn.getresponse() return resp.status < 400 all_urls = URL.objects.all() for u in all_urls: my_url = u.url result = checkUrl(my_url) print(result) There are 3090 urls in model "URL". It works but after object 2895, the error occurs: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host How to fix it? -
Heroku Django - I need to run collectstatic for every change I make in development
I have successfully deployed my web app to heroku. Now I want to continue development on the local host I get from 'python manage.py runserver', but it doesn't reload the CSS until I do 'python manage.py collectstatic'. (I have tried F5 and Ctrl+F5). Before deployment it would automatically reload all css on refresh. Here is my settings.py file: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.7. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ import os from pathlib import Path import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env() environ.Env.read_env() # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ '192.168.1.6', '127.0.0.1', 'mahmoudhamdyportfolio.herokuapp.com' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
Do I really need to accommodate both GET and POST request formats in a django form?
I'm new to django but something I don't understand is the need for accommodating both the GET and POST request types when developing a form. Please refer to code below from django docs: from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) The reason this confuses me is because I have developed a GET based form and it is working and I have no need for the POST portion above? See below: # views.py def simplifier_form(request): form = LabelForm() return render(request, "simplifier.html", {"form": form}) # forms.py class LabelForm(ModelForm): labels = forms.ModelChoiceField( queryset=Label.objects.all(), to_field_name='label_name', widget=forms.Select(attrs={'class': 'labels'}), ) class Meta: model = Label fields = ['labels'] -
Use IntegerChoices in model Meta class
I'm creating some constraints in my Meta class that reference an IntegerChoices enum. The issue I'm having is that I can't seem to figure out how to reference that IntegerChoices enum. class MyModel(models.Model): States = models.IntegerChoices('States', 'PROGRESSING INSTALLED DELETED') state = models.PositiveSmallIntegerField(choices=States.choices, help_text='Defines the cluster\'s current state') class Meta: constraints = [ models.CheckConstraint(check=models.Q(state__in=States), name='cluster_state_valid'), ] self.States isn't working, no self object. MyModel.States isn't working either since MyModel isn't fully instantiated at this point. Any advice/recommendation would be appreciated, thanks! -
how to link django signals and ajax
I am trying to implement a data collection system using iot devices. currently the data transmission is through an API using django REST framewokrs. That works excellent I would like to know some approach so that a trigger is generated when it receives data and these on the user's website are refreshed using ajax. maybe the use of signals but would not know how to bind that signal with ajax. I am somewhat newbie to javascript. some path should I follow? -
AttributeError: 'WSGIRequest' object has no attribute 'get' heroku
Am having a get request but it's failing on heroku with this error : AttributeError: 'WSGIRequest' object has no attribute 'get' I have failed to get the root cause of it Below is my view : class PostDetail(generics.GenericAPIView): """Blog post details""" queryset = Post.objects.all() serializer_class = serializers.PostSerializer authentication_classes = (JWTAuthentication,) permission_classes = (PostsProtectOrReadOnly, IsMentorOnly,) lookup_field = 'slug' def get_post_object(self, slug): post = get_blog_by_slug(slug) return post def get(self, request, slug): post = self.get_post_object(slug) if not post: return response.Response({ 'errors': _('Sorry, Blog post with the specified slug does' 'not exist') }, status=status.HTTP_404_NOT_FOUND) # track views of a viewed blog post. ip_address = get_ip_address(request) obj = CustomIPAddress.objects.create(address=ip_address) post.address_views.add(obj) serializer = self.serializer_class(post, context=request) return response.Response(serializer.data, status=status.HTTP_200_OK) Methods am calling above : def get_blog_by_slug(slug: str): """Get post by slug.""" try: obj = Post.objects.get(slug=slug) return obj except Post.DoesNotExist: return None def get_ip_address(request): """get ip address.""" try: client_ip, is_routable = get_client_ip(request) if client_ip is None: return uuid.uuid4() else: return client_ip except AttributeError: return uuid.uuid4() except: return uuid.uuid4() Am wondering why on local it's working but on heroku server am getting this error. -
django sql server studio backend doesn't support altering from/to AutoField
Please help me I tried to connect to the database The connection was successful and the rules were lifted, but I have this problem raise NotImplementedError("the backend doesn't support altering from/to %s." % t.name) NotImplementedError: the backend doesn't support altering from/to AutoField. Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying profiles.0001_initial... OK Applying goals.0001_initial...Traceback (most recent call last): File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) File "C:\Users\athamma.virtualenvs\src-NXdWuPOU\li Apply all migrations: account, admin, auth, contenttypes, goals, notifications, profiles, sessions, sites, socialaccont Running migrations: Applying goals.0001_initial... OK Applying goals.0002_approvedgoals... OK Applying goals.0003_auto_20210928_1206... OK Applying goals.0004_goal_cer... OK Applying goals.0005_auto_20211027_1918...Traceback (most recent call last): -
Django Parameters in URL from POST Request
I'm trying to create a search bar in Django, where users can enter a value to search for, click enter / search button, and then the url redirects to https:localhost:3000/usearch/abc, if they for example search for abc. This is URL paramter can always change based on the search, and it should send the parameter to the views.py file to be processed, though I can't get it to work. urls.py urlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path('usearch/', views.usearch, name='usearch'), path('usearch/<str:query>', views.usearch_query, name='usearch_query' ] views.py def usearch(request): return render(request, 'myapp/usearch.html') def usearch_query(request, query): context = {'query': query} print(query) # Testing the search result return render(request, 'myapp/usearch_query.html'} usearch.html <form method="POST" action="{% url 'usearch_query' %} <input type="search" placeholder="Search here..."> <button type="submit"> Search </button> </form> usearch_query.html {{ query }} I essentially want the user to search something, have it navigate to usearch/<search_parameter> and process the search in the usearch_query function so I can do some computations with it. -
Filtering by length of substring of a name django queryset?
I am trying to find a efficient way of filtering based on a length range of a full name field in my model. E.g the full name is separated as "John-Doe" in the model. John is the first name and Doe is the last name My goal is to find all objects in the model whose first_name is greater than 2 but less than 5. One approach I thought was of adding two additional field in the model called first_name and last_name and running a management command to extract the first_name and last_name and save it in those fields. This is a legacy db. So, there are close to 1million records. number_of_character_filter |= Q(first_name__length__gte=start, first_name__length__lte=end) Is there any other efficient approach I can take to resolve this? -
Update data using Django and AJAX
I have an issue with making a choice field in the input field from Django data. the models.py is: class Manifold_monitoring(models.Model): MFD_type = models.ForeignKey(Manifo_types , on_delete=models.CASCADE) DATE_TEST = models.DateField() Pressure_MFD = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) Pressure_SP = models.DecimalField(max_digits=15, decimal_places=3,null=True, blank=True) ..... def __str__(self): return str(self.MFD_type.MFDsID.MFDsID +' '+ self.MFD_type.Type +' '+ self.MFD_type.Fluid_N) class Meta: ordering = ('-post_date',) unique_together=[['MFD_type','DATE_TEST']] and the updating views.py: class UpdManifold_Monto(View): form_class = Manifold_monitoring_F def get(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) task.delete() return JsonResponse({"message":"success"}) return JsonResponse({"message": "Wrong request to delete"}) def post(self,request, pk, *args, **kwargs): if request.is_ajax(): task = Manifold_monitoring.objects.get(pk=pk) print('request.is_ajax()1', task.MFD_type_id) data = { "MFD_type_id": task.MFD_type_id, "DATE_TEST" :task.DATE_TEST, "Pressure_MFD":task.Pressure_MFD, "Pressure_SP":task.Pressure_SP } print('request.is_ajax()2', task.MFD_type ,data ) form = self.form_class(request.POST, initial=data) if form.is_valid(): MFD_type = form.cleaned_data['MFD_type'] DATE_TEST = form.cleaned_data['DATE_TEST'] Pressure_MFD = form.cleaned_data['Pressure_MFD'] Pressure_SP = form.cleaned_data['Pressure_SP'] print('request.is_ajax()3', MFD_type) if form.has_changed(): task.MFD_type_id = MFD_type task.DATE_TEST = DATE_TEST task.Pressure_MFD = Pressure_MFD task.Pressure_SP = Pressure_SP task.save() return JsonResponse({"message": "success"}) return JsonResponse({"message":"No change"}) return JsonResponse({"message":"Failed"}) return JsonResponse({"message": "Wrong request"}) The HTML code of the edit form: <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLable" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form id="formEdit" action=""> {% csrf_token %} <div class="modal-body"> <div class="form-group validate"> … -
how can I calculate a value from user input which are not saved to database and value from database using django
I am doing the site with calculating of calories in products, so I need to do this action. I have different objects of products and for each - different value in "calories per 100 gram" field. So idk how to do the calculation not saving it to database, I am sure it is easy, but I am newer, so.. This is my code: views.py: class CurrentProductView(FormView): template_name = "cur_product.html" form_class = ProductForm success_url = reverse_lazy("product") def form_valid(self, form): obj = form.save(commit=False) calc_value = (obj.cur_weight * obj.calories) / 100 return HttpResponse(calc_value) forms.py: class ProductForm(forms.ModelForm): cur_weight = forms.IntegerField() class Meta: model = Product fields = ["calories"] models.py: class Product(models.Model): name = models.CharField(max_length=100) calories = models.PositiveIntegerField() #calories per 100 gram description = models.TextField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) html: {% block content %} <form method="post"> {% csrf_token %} {{ form.cur_weight }} <input type="submit" value="Count"> </form> {% endblock %} -
Django-rest-framework: 3rd Level Custom endpoints
I'm new to the Django rest framework and I'm trying to achieve 3rd level custom endpoints. I just want someone advice to solve 3rd level custom endpoints. I have read the official document: https://www.django-rest-framework.org/api-guide/routers/ but I'm confused to solve this. Please needs some advice. To achieve these endpoints: /admin/advisor/(default admin) /user/<user-id>/advisor /user/<user-id>/advisor/<advisor-id>/ /user/<user-id>/advisor/booking/ models.py from django.db import models class Advisor(models.Model): advisor_name = models.CharField(max_length=200) advisor_photo_url = models.ImageField(null=True, blank=True) def __str__(self): return self.advisor_name class User(models.Model): advisor_fk = models.ForeignKey(Advisor, related_name='advisors', on_delete=models.CASCADE) name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.name class Booking(models.Model): user_fk = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) booking = models.DateTimeField() def __str__(self): return '{0}'.format(self.user_fk) serializers.py from rest_framework import serializers from usersite.models import Advisor, User, Booking from django.utils import timezone class DateTimeFieldWihTZ(serializers.DateTimeField): def to_representation(self, value): value = timezone.localtime(value) return super(DateTimeFieldWihTZ, self).to_representation(value) class AdvisorSerializer(serializers.ModelSerializer): class Meta: model = Advisor fields = ['advisor_name', 'advisor_photo_url', 'id'] class BookingSerializer(serializers.ModelSerializer): booking = DateTimeFieldWihTZ(format='%I:%M%p') #%b %d %Y %I:%M%p class Meta: model = Booking fields = ['user_fk', 'booking'] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['advisor_fk', 'name', 'email', 'password'] -
How to delete label of a form in Django
How can I delete label of form in Django. I have something like this. class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['user_image'] widgets = { 'user_image': forms.FileInput(attrs={'class': 'image-upload', 'label': ''}), } image-upload class does not include label. I have a auto-generated label and is written 'user-image' -
I can't run a function from the service layer in Django
I am a novice programmer. I'm trying to integrate PayPal IPN into my project, implement recurring subscription payments. I wrote a function that works fine in the console, BUT I DO NOT KNOW HOW TO RUN THIS FUNCTION SO THAT IT WOULD WORK AUTOMATICALLY. The ideal option for me would be if, when the data I need appears in the PayPal table, the IPN function would automatically start and perform the actions I need. For example, when these conditions appear in the table: ipn = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] my function would start, bypass the data in the table and perform the actions that I needed. I have tried such methods: def Proverka_1(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.exists(): return Podpiska() def Proverka_2(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0,mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if ipn_12.count() > 0: return Podpiska() def Proverka_3(): ipn_12 = PayPalIPN.objects.filter(payment_status='Completed', txn_type='subscr_payment', txn_id__gt=0, mc_currency='USD', payment_gross__gt=0, signal_1=False, pometka_1=False).order_by("-pk")[:20] if len(ipn_12) > 0: return Podpiska() From the console, the Podpiska() function is launched, and works as expected. But when I write this in a python document, nothing works. I do not know how to run it all. I don't even know how to … -
Is it best practice to define a join table for Django many to many relationships?
I have the following code: class Tutors(models.Model): first_name = models.CharField(max_length=20, default=None, blank=False) #you need to add default none and blank false to enforce the Not-Null constraint last_name = models.CharField(max_length=20, default=None, blank=False) email = models.EmailField(max_length=254,default=None, blank=False) birth_day = models.DateField(auto_now=False, auto_now_add=False, default=False, blank=False) def __str__(self): return(self.first_name + ' ' + self.last_name) class ArtSubjects(models.Model): subject_name = models.CharField(max_length=20, default=None, blank=False) tutors = models.ManyToManyField(Tutors) def __str__(self): return self.subject_name My question is, should I define many to many relationships like this? Or should I define a new class for the table? The reason I ask is that I can get objects from the join table by querying by ArtSubjects class like so - adobeAI.tutors.all() returns <QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]> But I can't think of a way for querying the join table by tutors to see what classes an individual tutor teaches. Any advice on this? -
`xhr.getAllHeaders()` is missing some headers in a browser extension context?
I am working on a browser extension. In a script running on the popup page, I am making an ajax request. On the first line of my handler for the xhr.onload event, I have console.log(xhr.getAllResponseHeaders()). However, some headers from the response are missing. I know that this could be a problem with my manifest.json file, so here it is, with some extra details removed: { "manifest_version": 2, "name": "...", "version": "1.0", "description": "...", "options_ui": { "page": "options.html" }, "icons": { "16": "icons/favicon-16x16.png", "32": "icons/favicon-32x32.png" }, "browser_action": { "default_popup": "popup.html", "default_icon": "./icons/favicon-32x32.png" }, "key": "...", "permissions": ["identity"], "content_security_policy": "script-src 'self' https://unpkg.com https://apis.google.com https://www.gstatic.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'", "content_scripts": ["..."] } These are the actual response headers, according to the network debugging tab: HTTP/1.1 200 OK Date: Wed, 27 Oct 2021 18:09:36 GMT Server: WSGIServer/0.2 CPython/3.9.6 Content-Type: text/html; charset=utf-8 Hx-Trigger: setupLogin X-Frame-Options: DENY Content-Length: 220 Vary: Cookie, Origin X-Content-Type-Options: nosniff Referrer-Policy: same-origin Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: chrome-extension://kcegdmcjklppcfbmfjgkkomecpaofoec However, this is the output of console.log(xhr.getAllResponseHeaders()) on the first line of the xhr.onloaded event handler: content-length: 220 content-type: text/html; charset=utf-8 CORS I should note that I have no obvious CORS errors. I am using Django with the django-cors-headers library, and I have all these headers, … -
Cannot authenticate in Django
I implemented my CustomUser model and as far as I have understood I need to override an authentication method. I've done it, but my login form always returns the message "incorrect login/password" The registration form works fine my new accounts appear in the database. By the way, I tried to add the print function in authenticating backend method and it didn't print anything setting.py AUTHENTICATION_BACKENDS = ['account.forms.CustomBackend'] AUTH_USER_MODEL = 'account.CustomUser' I use built-in Django LoginForm urls.py path('login/', LoginView.as_view(template_name='login.html', authentication_form=CustomLoginForm), name='login'), models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """Define a model manager for User model with no username field.""" def _create_user(self, email, password=None, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password=None, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return … -
How to scroll a line chart with the help of a mouse in Django?
I have a line chart rendered with Chart.js 2.4.0. According to the business requirement, the user should be able to move data points shown in the line chart using the mouse. Particularly, clicking the data point, hold the mouse clicked and move the point somewhere. Like drag and drop. Any ideas how to start? -
TypeError problem when I create "context_processor" in django
what is wrong here? I created 2 classes in the context_processor file, this problem I was facing when I was trying to return none dictionary objects but now doesn't understand what is wrong here. settings.py TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'accounts.context_processor.CreateNotification', 'accounts.context_processor.NotificationFeatures' ], }, }, ] context_processor.py from accounts.models import Notification, User class CreateNotification: def __init__(self, from_user, to_user, notification_type, role_sender, role_receiver, read_notif=False, active=False): self.from_user = from_user self.to_user = to_user self.notification_type = notification_type self.role_sender = role_sender self.role_receiver = role_receiver self.active = active self.read_notif = read_notif def send(self): if self.notification_type == "register": self.active = True Notification.objects.create( from_user=self.from_user, to_user=self.to_user, notification_type=self.notification_type, role_sender=self.role_sender, role_receiver=self.role_receiver, read_notif=self.read_notif, active=self.active ) return {} def read(self, id=None): if id: if self.active == True: self.read_notif = True return Notification.objects.filter(id=id).update(read_notif=self.read_notif) return {} class NotificationFeatures: def NotificationObject(self, req): notifications = Notification.objects.all() user_request = User.objects.get(username=req.user.username) if req.user.is_authenticated: # who is sender three_roles = notifications.distinct() for roles in three_roles: print(user_request.roles) if user_request.roles == roles: notifications.filter(from_user__roles__id=roles) return {} the traceback is: init() missing 4 required positional arguments: 'to_user', 'notification_type', 'role_sender', and 'role_receiver' knowing that: when I use the same classes that are in "context_processor file" in other locations like index views, for example, it works. so, I think that the problem …