Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How should Structure of url in Django? Css not working on some url
When I want to make a blog / slug page, css doesn't work in Django. Simple structure is working. What can i do? url.py url(r'^(?P<cats>[\w-]+)/$', category_detail, name='cats'), #css is working url(r'^blog/(?P<slug>[\w-]+)/$', blog_detail , name= 'detay'),#css is not working ] urlpatterns += static(settings.STATIC_URL,document_root = settings.STATIC_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') -
django.utils.datastructures.MultiValueDictKeyError: 'email'
I am trying to make a simple login form and this is the error it is popping every time I try to run the code. views.py function def login2(request): email1 = request.POST.get('email1') password1 = request.POST.get('password1') if email1 is "tuhin" & password1 is "tuhin": return render(request, 'welcome.html') else: messages.info(request, "Wrong credentials") return render(request, 'login2.html') login2.html code <html> <head> <title> </title> </head> <body> <form method="post" action="login2"> <input type="text" placeholder="Enter your email" name="email2"> <input type="password" placeholder="Enter your password" name="password2"> <input type="submit" value="Login"> {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} </form> </body> </html> Error in the brwser is attached in the picture.[enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/a3JfN.png [2]: https://i.stack.imgur.com/fB96x.png -
Prevent over-written converted plot images or Seperate two images in Django template
With the code, given below, I get two images but they seem also written on the top of each other. I don't know how to prevent this behavior, because I don't know how this bytecode conversion works with buffers in python. in the view in view: def data_stats(request): cate_table_name_and_num_prj= list( Category.objects.filter(project__is_mini=False).annotate(num_prjs=Count('project')).values_list('name', 'num_prjs') ) cate_table_name_and_num_ski= list( Category.objects.annotate(num_prjs=Count('project')).values_list('name', 'num_prjs') ) prj_wedge_sizes=[row[1] for row in cate_table_name_and_num_prj] ski_wedge_sizes=[row[1] for row in cate_table_name_and_num_ski] def func(pct, allvalues): absolute = int(pct / 100.*np.sum(allvalues)) return "{:.1f}%".format(pct, absolute) pie_fig_cate_by_skis = plt.pie( x=ski_wedge_sizes, autopct=lambda pct: func(pct, ski_wedge_sizes), labels=[row[0] for row in cate_table_name_and_num_ski], ) fig_ski = plt.gcf() buf_ski = io.BytesIO() fig_ski.savefig(buf_ski, format = 'png') buf_ski.seek(0) string_ski = base64.b64encode(buf_ski.read()) uri_ski = urllib.parse.quote(string_ski) pie_fig_obj_cate_by_prjs = plt.pie( x=prj_wedge_sizes, autopct=lambda pct: func(pct, prj_wedge_sizes), labels=[row[0] for row in cate_table_name_and_num_prj], ) fig_prj = plt.gcf() buf_prj = io.BytesIO() fig_prj.savefig(buf_prj, format = 'png') buf_prj.seek(0) string_prj = base64.b64encode(buf_prj.read()) uri_prj = urllib.parse.quote(string_prj) return render(request, 'data_stats.html', { 'uri_ski':uri_ski, 'uri_prj':uri_prj, }) the snippets from the template: <img src = "data:image/png;base64,{{ uri_prj }}"> <img src = "data:image/png;base64,{{ uri_ski }}"> screen-shots of the two browser-displayed images: -
django model relationship with rest api
Description the hospital is the user, a patient belongs to an hospital and a patient as an object has a card and diagnoses. I dont know whats wrong maybe its the relationship, i dont known. i need help Error message TypeError at /patient/diagnoses Got a TypeError when calling Diagnoses.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Diagnoses.objects.create(). You may need to make the field read-only, or override the PatientsDiagnosesSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/rest_framework/serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "/usr/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.8/site-packages/django/db/models/query.py", line 431, in create obj = self.model(**kwargs) File "/usr/lib/python3.8/site-packages/django/db/models/base.py", line 500, in init raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Diagnoses() got an unexpected keyword argument 'owner' urls.py of patient app urlpatterns = [ path('', views.PatientListAPIView.as_view(), name="patient"), path('<int:id>', views.PatientDetailAPIView.as_view(), name="patient"), path('card', views.PatientCardListAPIView.as_view(), name="card"), path('card/<int:id>', views.PatientCardDetailAPIView.as_view(), name="card"), path('diagnoses', views.PatientDiagnosesListAPIView.as_view(), name="diagnoses"), path('diagnoses/<int:id>', views.PatientDiagnosesDetailAPIView.as_view(), name="diagnoses") ] serializers.py from rest_framework import serializers from .models import Patient, Card, Diagnoses class PatientsSerializer(serializers.ModelSerializer): class Meta: model = Patient fields = ['id', 'name', 'phone', 'email', 'state','country'] class … -
Pass crispy-form in ajax post request
I'm trying to pass crispy form in through ajax POST request in JS within the HTML page. $.ajax({ type: "POST", url: "confirmed", data: {form : {{form}}, accessCode : '{{code}}' }, csrfmiddlewaretoken: '{{ csrf_token }}', success: function (data) { } }); whenever this function is triggered. I get 'Uncaught SyntaxError: Invalid or unexpected token'. The source looks like this ... $.ajax({ type: "POST", url: "confirmed", data: {form : '<tr><th><label for="id_submit_name">Requested For:</label></th><td><input type="text" name="submit_name" value="sa" class="textinput textInput form-control" id="id_submit_name"></td></tr> <tr><th><label for="id_email">Email:</label> ... I'm guessing it becomes multi-line, which causes the issue. I have also tried to pass it direct, instead of string which gives "Uncaught SyntaxError: Unexpected token '<' " error (as the form start with table row element) Ps. I'm new to web-development, feel free to correct me if i'm doing anything wrong. -
S3 media files for my django-heroku app are not displaying in the browser, but S3 static files are
I currently have a website (Django app) deployed on Heroku. On the site have static file images displayed, as well as user uploaded media file images. I am using AWS S3 to store and serve my static and media files. When I visit my website, the static file images are always shown. However the media files are not displayed. Instead if I click on the blank icon where the media file image is supposed to be, I receive the Privacy Error message below. If I tell the browser to proceed anyways, then it will show the media file image. What I am confused by is why the static images are shown (without a warning) but not the media images? In my S3 bucket I have both a static folder and a media folder. The static folder holds the css, js and images that I used to construct my website. The media folder only holds files that are user uploaded. I suspect this is happening because I have no SSL set up for my website yet. However it confuses me why certain files in my bucket are shown, while others are hidden because they are not secure. All of these files … -
Django switch from sqlite to postgres error
(virtual) user@user-HP-Pavilion-dv6-Notebook-PC:~/user/hobby$ python manage.py runserver (virtual) user@user-HP-Pavilion-dv6-Notebook-PC:~/user/hobby$ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 06, 2020 - 23:05:26 Django version 3.0.9, using settings 'hobby.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Internal Server Error: / Traceback (most recent call last): File "/home/user/user/virtual/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "shop_product" does not exist LINE 1: ...hop_product"."price", "shop_product"."image" FROM "shop_prod... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/user/user/hobby/shop/views.py", line 14, in home_view return render(request, "product_detail.html", context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/user/user/virtual/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, … -
I can't see the version of python in cmd
When i type 'python −−version' on CMD; it does not show me the version of python i am using instead it displays:python: can't open file 'ΓêÆΓêÆversion': [Errno 2] No such file or directory -
django-dotenv tries reading .env from project folder before root?
I'm chaching my settings to use django-dotenv. I've manage to have my site running again, but seeing this warning: $ python manage.py runserver D:\web_proyects\ministerios_elim\mysite\settings.py:19: UserWarning: Not reading D:\web_proyects\ministerios_elim\mysite\.env - it doesn't exist. Why does it try to read from mysite (name of project)? manage.py: #!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": dotenv.read_dotenv(override=True) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) wsig.py: import os import dotenv from django.core.wsgi import get_wsgi_application dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() -
Django Rest Framework Nonetype object has no attribute user while calling authenticate
I am working on a custom ObtainAuthTokenView which is as follows: class ObtainAuthTokenView(APIView): throttle_classes = () permission_classes = () parser_classes = ( parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser, ) renderer_classes = (renderers.JSONRenderer,) def post(self, request): serializer = serializers.AuthCustomTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) content = { 'token': unicode(token.key), } return Response(content) Serializer Class from rest_framework.authentication import authenticate class AuthCustomTokenSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, attrs): email_or_username = attrs.get('username') password = attrs.get('password') if email_or_username and password: # Check if user sent email user_request = get_object_or_404( User, email=email_or_username, ) email_or_username = user_request.username user = authenticate(username=email_or_username, password=password) if user: if not user.is_active: msg = _('User account is disabled.') raise exceptions.ValidationError(msg) else: msg = _('Unable to log in with provided credentials.') raise exceptions.ValidationError(msg) else: msg = _('Must include "email or username" and "password"') raise exceptions.ValidationError(msg) attrs['user'] = user return attrs When authenticate function in the serializer is called it shows the following error: 'NoneType' object has no attribute 'user' Stuck here since a while Any help would be appreciated -
Django prompt the user for login in class based view
I have a class based view which lets a user to add a product to the cart, but the user should be logged in. I have used LoginRequiredMixin to restrict the access to AddToCart CBV, but the product page can be viewed by everyone. I would like to prompt the user asking them to login in whenever they click Add To Cart button and when they are logged in then only they can add product to their respective cart. class AddToCart(LoginRequiredMixin, TemplateView): """ Add an item to the cart """ def get(self, *args, **kwargs): slug = self.kwargs['slug'] print(slug) item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=self.request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) print(order_qs) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug): pass # message : Item already in cart else: order.items.add(order_item) # message : Item was added to cart return redirect("products:product") else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) # message : Item was added to cart return redirect("products:product") A possible solution; I can remove LoginRequiredMixin and check for request.user and if it says AnonymousUser I can return a message via Django Message Framework and display the message to user. But this doesn't sound like a good solution. … -
Get "this field is required" in django-auth-registration
What I want to do Make a user to register to django Authentication Version django : 3.1 djangorestframework:3.11.1 python : 3.7.6 django-allauth : 0.42.0 django-rest-auth : 0.9.5 Situation I entered a registration page that django provides by accessing to localhost:8000/rest-auth/registration/. In order to register to the site, I entered username, password1 and password2 in fields. However, every time I sent POST request, I got an error and that says it below. { "password1": [ "This field is required" ], "password2": [ "This field is required" ] } I absolutely typed exact same passwords in these fields. And, I do really not know why I get this error although I surely entered passwords. How could I fix it out? I would like you to teach me how to do that. Thank you very much. -
How to serialize correctly? Ajax updates all instances of a django upvote button in a object forloop when pressed
OK so I have an index page with items that can be up or downvoted. The issue is that when I upvote/downvote one item, all items on the page are upvoted/downvoted and the appearance of all buttons on the page all change instead of just the one object that was upvoted/downvoted. Can anyone help me serialize each for loop object correctly? my index page: {% for post in posts %} <span id="post_{{forloop.counter}}" data-value="{{post.id}}"></span> <button class="vote_action" value="upvote_button"> + </i></button> <span id="votes_{{forloop.counter}}">{{post.points}}</span> <button class="vote_action" value="downvote_button"> - </button> {% endfor %} ... <script type="text/javascript"> // JQUERY - AJAX SCRIPT FOR voting $(document).ready(function(){ {% for post in posts %} $('.vote_action').click(function(e) { var postid = document.getElementById('post_{{forloop.counter}}').getAttribute('data-value'); var button = $(this).attr("value"); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "vote" %}', data: { postid: postid, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'postvote', button: button, }, success: function(json){ if (json.length < 1 || json == undefined) { //empty } document.getElementById("votes_{{forloop.counter}}").innerHTML = json['result'] //change button looks $("#uvb_{{forloop.counter}}").addClass("disabled"); $("#dvb_{{forloop.counter}}").addClass("disabled"); }, error: function(xhr, errmsg, err) {} }) }) {% endfor %} }) </script> My views function: @login_required def post_vote(request): if request.POST.get('action') == 'postvote': # get information from request about what item id it is id = int(request.POST.get('postid')) # And also which button … -
Heroku application error: unicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3>
I am trying to deploy my Django app on Heroku however, whenever I go to my app I am getting an error: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> I have now two settings file so in my projects folder which contains the wsgi.py I have a a folder called settings which is: settings --common.py --development.py --productions.py In my production.py I have: from register.settings.common import * import os import django_heroku DEBUG = False ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1','appname.heroku.com'] SECRET_KEY = os.environ.get('SECRET_KEY') EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) And in my wsgi.py and manage.py I have: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'register.settings.production') Now I have added the Postgres add-on from the dashboard and can check that I also have it using the Heroku CLI . I have also added a custom domain name of www.myapp.com as well which I do not know if this is causing the issue. For pushing to master i did: heroku config:set DISABLE_COLLECTSTATIC=1 and then: git push heroku master What is causing this issue? When I do python manage.py run server I also get the error: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. -
Django DateField not saving the selected date from picker
I have a django model with some models.DateField and a default value. The forms.py looks like this: class DateInput(forms.DateInput): input_type = 'date' class AddNewCar(forms.ModelForm): image = forms.ImageField(label ="Imagine Masina", required=False) vigneta = forms.DateField(label ="Valabilitate Rovinieta", widget=DateInput()) class Meta: model = Car fields = ('image',) The models.py class Car(models.Model): owner = models.ForeignKey(Users, null = True, on_delete = models.CASCADE) vigneta = models.DateField(default=datetime.date.today, blank = False) And in views.py def post(self, request, *args, **kwargs): form = AddNewCar(request.POST) if form.is_valid(): m = form.save() m.owner = request.user m.save() return redirect("home") The problem is when I submit the form, don't give any errors but the date that's saved is not the selected one, is the default date. -
Django Serializer defining initial object
I can't seem to figure out how to pass in an initial value to a serializer. I have a multitenant django site and I am trying to now get APIs setup. The client field exists but needs to be hidden and read only. I thought this worked like a form and a view in traditional django. I would normally pass in the get_initial in the view. I tried that first but it doesn't work. I think I need to get the value directly in the serializer but I can't seem to get it to work. model: class Location(ClientAwareModel): client = models.ForeignKey(Client, on_delete=models.PROTECT) name = models.CharField(max_length=64, blank=True) address = models.CharField(max_length=64) address2 = models.CharField(max_length=64, blank=True) city = models.CharField(max_length=64) state = USStateField() zip_code = USZipCodeField() serializer (you can see all my failed attempts commented out: class LocationSerializer(serializers.ModelSerializer): def get_client(self, obj): # return client_from_request(self.request) return client_from_request(self.context['request']) # client = serializers.SerializerMethodField('get_client') # client = serializers.SerializerMethodField() # client = serializers.Field(source='get_client', read_only=True) # client = serializers.ReadOnlyField(source='get_client') # client = serializers.PrimaryKeyRelatedField(read_only=True, default='get_client') client = serializers.PrimaryKeyRelatedField(read_only=True, source='get_client') # client = serializers.HiddenField(default=get_client(self)) class Meta: model = Location fields = ['name', 'address', 'address2', 'city', 'state', 'zip_code', 'client'] viewset: class LocationViewSet(viewsets.ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): … -
How to create form using foreign keys and inlines
I am just trying to make an polling app and just want to have a simple HTML page where I can have poll_text and 3/4 choice_text fields. currently my models looks like following #models.py class Poll(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) poll_text = models.CharField((""), max_length=250) pub_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.poll_text class Choice(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, default = '') choice_text = models.CharField( max_length=200) no_of_votes = models.IntegerField(default = 0) def __str__(self): return self.choice_text and this is how my forms.py looks like. #forms.py from django.forms import ModelForm from .models import Poll, Choice class CreatePollForm(ModelForm): class Meta: model = Poll fields = ('poll_text',) and finally the admin.py, looks like this, this gives me correct presentation in localhost/admin, and that presentation I want in a HTML page. #admin.py from django.contrib import admin from .models import Poll, Choice from django.contrib.auth.models import User # Register your models here. class ChoiceInLine(admin.TabularInline): model = Choice extra = 5 class PollAdmin(admin.ModelAdmin): fieldsets = [(None, {'fields': ('user','poll_text',)})] inlines = [ChoiceInLine] please guide me what changes needs to be made, also please suggest how can i tweak my model to have a record of that an user has voted this poll. -
How to call a function after ALL Django apps have started
I want to load a number of classes I've put in a module that's not part of the settings.INSTALLED_APPS list. (I want my customers to be able to write their own subclasses which can be dynamically loaded or reloaded.) I have a function called load_classes() to do so. The question is where to call it when my project initially starts. My first attempt at this was placing load_classes in the ready() function of AppConfig as per this question, but that apparently only is invoked after the particular app with the AppConfig is done loading, not all of them. Since these class definitions import models and functions from other apps in the project, I ended up with this error: File "/Users/dylan/.local/share/virtualenvs/pipeproj-oDyHbVBN/lib/python3.8/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Where can I place my importing code, so it's triggered once all of the Django apps have been loaded? -
Request failed with status code 401 for React Native Expo on IOS only but working everywhere else
I am working with a React Native with the Expo SDK. im having issues with IOS Simulator when Fetching ApI (GET Request) i Have tried PostMan and on Android it is working very fine but on IOS it just throws Running application on iPhone 11. Request failed with status code 401 - node_modules/axios/lib/core/createError.js:15:17 in createError - node_modules/axios/lib/core/settle.js:16:9 in settle - node_modules/axios/lib/adapters/xhr.js:52:6 in handleLoad - node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:567:4 in setReadyState - node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse - node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0 - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue * [native code]:null in callFunctionReturnFlushedQueue below is my function for GET Request on const token = await AsyncStorage.getItem("userToken"); auth_token = 'Token ' + token axios .get("http://127.0.0.1:8001/api/user-info", { headers: { "Authorization": auth_token, } }) .then(function (response) { console.log(response) const groupData = {}; groupData["groupName"] = response.data.user.group; groupData["userName"] = response.data.user.username; groupData["jobTitle"] = response.data.user.job_title; console.log(groupData); groupName(groupData); }) .catch(function (error) { console.log(error) }); also i did debug request im getting on fetch , i somehow know that Authorization is not there in request.headers here's my request.headers, Authorization is not there {'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate', 'Host': '127.0.0.1:8001', 'Content-Type': 'application/json;charset=utf-8', 'Content-Length': '47', 'Connection': 'keep-alive', 'Accept-Language': 'en-us', 'User-Agent': 'Expo/2.16.0.108985 CFNetwork/1128.0.1 … -
Django-admin grant and revoke permissions
hey guys can i grant and revoke permissions of objects of models in django admin if so how can i do that? i have Profile model and in admin Groups i have admin and departmentHead groups the thing is i want the departmentHead to only have permission of his own department users. the model is the following. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) Male = 'M' Female = 'F' Gender = [ (Male, 'M'), (Female, 'F'), ] gender = models.CharField(max_length=1, choices=Gender, default="",) image = models.ImageField(default='default.jpg', upload_to='profile_pics', blank=True, null=True) department = models.ForeignKey(Departments, default="", on_delete=models.CASCADE, blank=True, null=True) classLevel = models.ForeignKey(ClassLevel, default="1", on_delete=models.CASCADE, blank=True, null=True) semester = models.ForeignKey(Semester, default="1", on_delete=models.SET_DEFAULT, blank=True, null=True) specialization = models.ForeignKey(Specialization, default="", on_delete=models.SET_DEFAULT, blank=True, null=True) date_registered = models.DateTimeField(default=timezone.now) is_online = models.BooleanField(default=False) def __str__(self): return self.user.username def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Meta: verbose_name_plural = "Profile" -
Form validation error not showing in the HTML page in Django
I am developing a simple sign up and sign in web application in Django. I am using Django form for the user inputs. I write the clean function in the forms.py file. If username already exist in the database it should display the error message in the HTML page but nothing display on the webpage, can someone find out the mistake in my code. Here is my code: view.py def RegistrationView(request): form=Registration_Form() if request.method=='POST': form=Registration_Form(request.POST) if form.is_valid(): form.save() return redirect('login_view') else: # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } def clean_username(self): user_name=self.cleaned_data['username'] if User_Registration.objects.filter(username=user_name).exists(): raise forms.ValidationError("Username Already Exist") registration.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <div class="form-group"> <br><br><br> <h2 style="padding-left: 480px;">Registration Form</h2> <br> <form method="POST" action=""> … -
How to filter the related many-to-many field in Django admin screen in a self referencing scenario of Django Models
I have written a Django Model called Job. I tried self referencing the Job Model and created a Many To Many field. A job can have other jobs as dependencies, But it cannot have dependency on itself. In the Django Admin page for Job, what I am expecting to see was a multi select field without the job which is currently in edit mode. Basically I cannot add the same object as its dependent. I am trying to somehow filter out the multi select field in Django Admin page to display only the other jobs and it should not include the same job which is under editing. If I allow it, it may create a circular dependency and my program wont work as expected. This problem occurs only when editing the object, when creating the object, this problem wont occur because the job was not yet created. Any help on filtering the related self referencing many to many field will be appreciated. Here is my Model code: class Job(models.Model): name = models.CharField(max_length=100,blank=False,null=False) job_category = models.ForeignKey(to=JobCategory,on_delete=models.CASCADE,null=False,blank=False) additional_arguments = models.CharField(max_length=100,blank=True) **dependencies = models.ManyToManyField(to="self",symmetrical=False,blank=True)** active = models.BooleanField(default=True,null=False) Admin Screen Screenshot for the Job Model -
How to Pass Data from Model into Chart JS - Django
I am attempting to pass user submitted data from a django model form into a Chart.js chart that renders on a detail view page. I am having trouble figuring out why I cannot call values from an instance of the model form submission in my views.py and subsequently pass that to the js which renders the chart. When I hardcode values into my class-based view defined variables for TAM and LTM_sales the chart renders. Please see code below: Models.py: class Strategy(models.Model): total_addressable_market = models.IntegerField(blank=True, null=True) last_twelve_months_sales = models.IntegerField(blank=True, null=True) Views.py def strategy_detail(request, id): strategy = get_object_or_404(Strategy, id=id) .... context ={ 'strategy': strategy, .... } return render(request,'hypo_app/strategy_detail.html', context) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, default=None): strategy = Strategy.objects.all() TAM = strategy.total_addressable_market LTM_sales = strategy.last_twelve_months_sales labels = ['TAM', 'LTM Revenue'] default_items = [TAM, LTM_sales] data = { "labels": labels, "default": default_items, } return Response(data) URL from django.urls import path from .views import UserExperimentListView, ChartData from . import views urlpatterns = [ .... path('chart_data/', ChartData.as_view(), name='chart_data'), ] JAVASCRIPT <script> {% block jquery %} var endpoint = '/chart_data/' var defaultData = [] var labels = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ labels = data.labels defaultData = data.default … -
Django cookie banner: window.wpcc undefined
On my GitHub pages website, I have been using https://www.websitepolicies.com/ to create a simple cookie consent banner. Trying to use the same snipped in my new Django app does not work however. The HTML code for the banner goes into the HTML head and looks like <link rel="stylesheet" type="text/css" href="https://cdn.wpcc.io/lib/1.0.2/cookieconsent.min.css"/> <script src="https://cdn.wpcc.io/lib/1.0.2/cookieconsent.min.js" defer></script> <script>window.addEventListener("load", function(){window.wpcc.init({"border":"thin","corners":"small","colors":{"popup":{"background":"#f6f6f6","text":"#000000","border":"#555555"},"button":{"background":"#555555","text":"#ffffff"}},"position":"bottom","transparency":"10","content":{"href":"https://www.websitepolicies.com/policies/view/<hashcode_to_my_policy>"}})});</script> Adding this to the head of base.html inside my Django app doesn't work. No banner is displayed and instead, the console logs the error: Loading failed for the <script> with source “http://wpcc.io/lib/1.0.2/cookieconsent.min.js”. Uncaught TypeError: window.wpcc is undefined Why is the snipped working fine with my GitHub pages site but not with my Django app? Why can http://wpcc.io/lib/1.0.2/cookieconsent.min.js not be loaded? If I copy it into the address bar, it loads. -
webpush django with pywebpush
I wrote the following simple code to send web push messages to an Angular application: profile = Profile.objects.filter(user__id=1).first() subscription_info = { "endpoint": profile.notification_url, "keys": { "auth": profile.auth, "p256dh": profile.p256dh } } data = {"notification":{"title":"Notifications","body":"Test","icon":"https://www.shareicon.net/data/256x256/2015/10/02/110808_blog_512x512.png","vibrate":[100,50,100],"data":{"url":"https://x.com"}}} webpush(subscription_info, data,, vapid_private_key="valid_key", vapid_claims={"sub": "mailto: x@gmail.com"}) Upon executing this I get the following error back: content[i:i + chunk_size], TypeError: unhashable type: 'slice' Changing the 'data' variable to just a string like 'test' it is able to execute properly but then my Angular application in Google Chrome gives me the following error: ngsw-worker.js:2031 Uncaught SyntaxError: Unexpected token T in JSON at position 0 How can I send a web push notification to Angular (in Chrome) using pywebpush ?