Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect is_staff user to custom template in Django?
I have a simple issue: I tried to redirect the login page to another page depending on the user role(staff/normal). Normal user have their own dashboard and staff user have the overall dashboard. The redirect function for normal user work perfectly fine. However, for the staff user, it keep redirect me to django-admin page instead of my custom template. I have tried this but it is not working. Staff Redirected Page views.py #login def login(request): if request.user.is_authenticated: if request.user.is_staff: return redirect('staff_dashboard') else: return redirect('user_dashboard') else: if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = auth.authenticate(request,username=username,password=password) if user is not None: if user.is_staff: auth.login(request,user) return redirect('staff_dashboard') else: auth.login(request,user) return redirect('user_dashboard') else: messages.info(request,"Username or Password is incorrect") return redirect('login') #staff_dashboard @login_required(login_url='login') def staff_dashboard(request): vid_size = [] img_query_set = model_images.objects.all() img_query_set_count = model_images.objects.all().count() vid_query_set = model_videos.objects.all() vid_query_set_count = model_videos.objects.all().count() for item in vid_query_set: size = round(item.vid_path.size / 1000000,1) vid_size.append(size) context = { "img_query_set": img_query_set, "vid_query_set": vid_query_set, "img_query_set_count": img_query_set_count, "vid_query_set_count": vid_query_set_count, } return render(request,'admin/index.html',context) urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), path('login', views.login, name='login'), path('user/dashboard', views.user_dashboard, name='user_dashboard'), path('staff/dashboard', views.staff_dashboard, name='staff_dashboard'), ] -
Django paginate huge millions data
I'm trying to handle 6 million row data with django pagination, my request taking really long time. get_query_set = self.get_queryset(). # it takes 1 second queryset = self.filter_queryset(get_query_set) # it takes 1 second page = self.paginate_queryset(queryset) # it takes 20 second serializer = self.get_serializer(page, many=True) # it takes 1 second After query to oracle queryset return almost 6 million row. It looks like pagination taking long time. Is there any suggestion, what should i do? I use Django==3.1.1 Thank you so much -
Django rest framework viewsets method return HTTP 405 Method Not Allowed
I am developing a cart api where add item in cart and remove. I craete a CartViewSet(viewsets.ModelViewSet) and also create two method in CartViewSet class add_to_cart and remove_from_cart..But when I want to add item in cart using add_to_cart and remove using romve_from_cart method then got HTTP 405 Method Not Allowed.I am beginner in building Django rest api.Please anyone help me. Here is my code: my configuration: Django==3.1.1 djangorestframework==3.12.0 models.py: from django.db import models from product.models import Product from django.conf import settings User=settings.AUTH_USER_MODEL class Cart(models.Model): """A model that contains data for a shopping cart.""" user = models.OneToOneField( User, related_name='user', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class CartItem(models.Model): """A model that contains data for an item in the shopping cart.""" cart = models.ForeignKey( Cart, related_name='cart', on_delete=models.CASCADE, null=True, blank=True ) product = models.ForeignKey( Product, related_name='product', on_delete=models.CASCADE ) quantity = models.PositiveIntegerField(default=1, null=True, blank=True) def __unicode__(self): return '%s: %s' % (self.product.title, self.quantity) serializers.py: from rest_framework import serializers from .models import Cart,CartItem from django.conf import settings from product.serializers import ProductSerializer User=settings.AUTH_USER_MODEL class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email'] class CartSerializer(serializers.ModelSerializer): """Serializer for the Cart model.""" user = UserSerializer(read_only=True) # used to represent the target of the relationship using its __unicode__ … -
Django, CSRF, iFrames and Safari
The question here is similar to the one referred to by the link below but this link is 8 years old, python, Django and Safari have all moved one since then. I would like to know if the solution is still relevant or if there is a new way of solving this. Also, these solutions do not describe the resolution in detail. Django Iframe Safari Fix The problem: When a view has an iFrame loaded from a non-same-site and that iFrame attempts to write to a cookie, Django logs the user out. Thanks! -
Adding font awesome icon as placeholder in django
I want to add a font awesome icon together with a username as a placeholder. I tried using mark safe but did not work. The snippet relating to that part is below username_placeholder = f'''{ mark_safe('<i class="fas fa-user"></i>')} username''' widgets = { 'username': forms.TextInput(attrs= {'placeholder': username_placeholder }), 'email': forms.EmailInput(attrs= {'placeholder': 'email'}) } The full code class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'Password' } )) confirm_password = forms.CharField(label='', widget=forms.PasswordInput( attrs={ 'placeholder': 'confirm Password' } )) class Meta: model = User fields = ('username', 'email',) username_placeholder = f'''{ mark_safe('<i class="fas fa-user"></i>')} username''' widgets = { 'username': forms.TextInput(attrs= {'placeholder': username_placeholder }), 'email': forms.EmailInput(attrs= {'placeholder': 'email'}) } labels = { 'username': _(''), 'email':_('') } help_texts = { 'username': None } def clean_confirm_password(self): cd = self.cleaned_data if cd['password'] != cd['confirm_password']: raise forms.ValidationError('Passwords do not match') return cd['password'] -
How can I handle POST data in django middleware?
I have Django middleware to handle POST request. class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, req): response = self.get_response(req) # want to do something with 'r.body', # but it is not able to be read return response As the request body is already read in get_response, I cannot read it again in middleware. Tried copy.copy(), but no luck since the copied stream references same object of the original one. copy.deepcopy() raises an exception. How can I handle POST data in middleware? I want to handle all requests, so implementing the logic in every view is not ideal. -
Count view not working on navbar after chancing page
I have a page with a navbar where the count of posts work very well, but after I go to a other page, lets say to contacts the counts display as (). How can I fix this problem? Thanks on index.html the result is : total posts (43434) on contacts.html the result is : total posts () index.html <div> total posts ({{ postcounts }}) </div> views.py def index(request): posts = Post.objects.filter(active=True) pcounts = posts.count() context = { 'postcounts':pcounts, } return render(request, 'posts/index.html', context) -
Django - I cant migrate my database because of my forms.py
I am trying to migrate my django project but there is this error: (venv) F:\repos\meetmetrics.eu>python src\manage.py migrate Traceback (most recent call last): File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: blog_category The above exception was the direct cause of the following exception: Traceback (most recent call last): File "src\manage.py", line 21, in <module> main() File "src\manage.py", line 17, in main execute_from_command_line(sys.argv) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 361, in execute self.check() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\commands\migrate.py", line 65, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 399, in check for pattern in self.url_patterns: File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "F:\repos\meetmetrics.eu\venv\lib\site-packages\django\urls\resolvers.py", line 577, in … -
Django - TestCase - response.status code failing
Hello everyone out there, I'm starting my journey trough django test-code. The start is not great. I'm starting some very basic testing ( tough important) as follows: from django.test import TestCase, SimpleTestCase from django.urls import reverse # Create your tests here. class RegistryTest(SimpleTestCase): def test_homepage_status(self): response = self.client.get('Registry/search/') self.assertEqual(response.status_code, 200) def test_homepage_url_name(self): response = self.client.get(reverse('search')) self.assertEqual(response.status_code, 200) def test_homepage_template(self): response = self.client.get('Registry/search/') self.assertTemplateUsed(response, 'registry/search_registry.html') here is my urls.py: from django.contrib import admin from django.urls import include from django.urls import path from django.conf.urls import url from .views import * app_name = 'registry' urlpatterns = [ path('search/', search, name='search'), #customerSupplier path('customerSupplier/detail/<int:idCS>/', detail_customerSupplier, name='detail_customerSupplier'), path('customerSupplier/new/', new_customerSupplier, name='new_customerSupplier'), ] this is my search view from views.py: def search(request): if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): azienda = form.cleaned_data['Company'] testo = form.cleaned_data['RagSociale'] tipo = form.cleaned_data['Tipologia'] result = CustomerSupplier.search(azienda, testo, tipo) return render(request, 'registry/search_registry.html', {'form': form, 'CustomerSupplierList':result }) else: form = SearchForm() return render(request, 'registry/search_registry.html', {'form': form }) when I run the test i get back this error: python manage.py test Registry System check identified no issues (0 silenced). FFE ====================================================================== ERROR: test_homepage_url_name (tests.RegistryTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carloc/Projects/100_CogniSpa/gestionale-cogni/src/Registry/tests.py", line 13, in test_homepage_url_name response = self.client.get(reverse('search')) File "/home/carloc/.local/lib/python3.7/site-packages/django/urls/base.py", line 90, in … -
Why my static files don't load with django and next js
In my django project, I created a frontend folder and i unpackage my react theme (I have download a Next.js theme for free) : public, src, .gitignore, next.config.js, package.json, package-lock.json, readme.md I have install project's dependencies : npm install with npm run build && npm run export, in the frontend folder are generated .next and out folders urls.py : from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), ] settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/out'), ], .... ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/out/_next/static') ] with python3 manage.py runserver I see the index.html but whitout static files -
Send file to a different server
I have an upload url in my backend and i want to upload a file in another server. My API view: class AssessmentFileUpload(APIView): parser_classes = (MultiPartParser, ) def post(self, request, format=None): tenant = request.user.tenant.id response = AssessmentFileUploadHelper(tenant).upload_file(request) response_text = json.loads(response.text) print(response_text) if response.status_code == status.HTTP_201_CREATED: return Response({"message": "success", "id": response_text.get('id')}, status=status.HTTP_201_CREATED) return Response({"message": "failed"}, status=status.HTTP_400_BAD_REQUEST) My class which sends request data to the other serve's url: class AssessmentFileUploadHelper: def __init__(self, tenant_id): self.tenant_id = tenant_id def upload_file(self, file): url = settings.ASSESSMENT_CONNECTION_SETTINGS["api_endpoint"] + "tenant/" + \ str(self.tenant_id) + "/fileupload/" return RequestSender().send_request(url, file) Now, the errors im getting is InMemoryUploadedFile is not json serilizaable . How to send request.FILES to that server ? -
Django Sitemap Problem Http Error 500 on Production
I'm using django sitemap to generate my sitemap. In local it works normally, I can visit 127.0.0.1:8000/sitemap.xml and see the data. But in production, I got http error 500 (site matching query not exist). I've been following solutions on the internet, and one of those is from this link https://dev.to/radualexandrub/how-to-add-sitemap-xml-to-your-django-blog-and-make-it-work-on-heroku-4o11 , but still not solving the error. Please kindly help. Thanks -
How to query all records from a model matching two or more values in Django Model using SqlLite
I have this query inside one of my views.py My query needs to search for football matches in all the leagues specified in my query value.In addition I would like to get all upcoming matches by selecting all matches with kickoff_date say 5 days from now topgames =Predictions.objects.filter(league='Epl' or 'Bundesliga' or 'Liga BBVA' or 'The Championship',kickoff_date= // I want to fiter the kickoff_date based on a time range ie. (5 days from now) // ) -
Could not resolve URL for hyperlinked relationship using view name "api:user-detail" in Django Rest Framework
I saw many similar questions and I have followed this question Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail" but look like nothing works. Inside the UserViewSet i'm using get_queryset instead in queryset. In my UserViewSet I want to list only current user objects. # app/serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): passwordStyle = {'input_type': 'password'} password = serializers.CharField(write_only=True, required=True, style=passwordStyle) url = serializers.HyperlinkedIdentityField(view_name="api:user-detail") class Meta: model = User fields = ['url', 'id', 'username', 'password'] def create(self, validated_data): validated_data['password'] = make_password(validated_data.get('password')) return super(UserSerializer, self).create(validated_data) # app/views.py class UserViewSet(viewsets.ModelViewSet): def get_queryset(self, *args, **kwargs): user_id = self.request.user.id print(user_id) return User.objects.all().filter(id=user_id) # want to list only current user objects serializer_class = serializers.UserSerializer permission_classes_by_action = { 'create': [permissions.AllowAny], 'list': [permissions.IsAuthenticated], 'retrieve': [app_permissions.OwnProfilePermission], 'update': [app_permissions.OwnProfilePermission], 'partial_update': [app_permissions.OwnProfilePermission], 'destroy': [permissions.IsAdminUser] } def create(self, request, *args, **kwargs): return super(UserViewSet, self).create(request, *args, **kwargs) def list(self, request, *args, **kwargs): return super(UserViewSet, self).list(request, *args, **kwargs) <- problem on this line def retrieve(self, request, *args, **kwargs): return super(UserViewSet, self).retrieve(request, *args, **kwargs) def update(self, request, *args, **kwargs): return super(UserViewSet, self).update(request, *args, **kwargs) def partial_update(self, request, *args, **kwargs): return super(UserViewSet, self).partial_update(request, *args, **kwargs) def destroy(self, request, *args, **kwargs): return super(UserViewSet, self).destroy(request, *args, **kwargs) def get_permissions(self): try: # return permission_classes depending … -
Django dynamic Search View based on filled GET request keys
please how is possible in Django to reach a view, which will be filtering based on filled keys from GET request? I am using only one search view, but two forms: I am taking these requests: q = request.GET.get('q') # this is for VIN and LOT number (two columns in Model/DB) make = request.GET.get('make') model = request.GET.get('model') year_from = request.GET.get('year_from') year_to = request.GET.get('year_from') There are no required fields/requests, so it should work dynamically. If the user fills "q" - it will filter out by VIN or LOT number. If the user will fill Make and Year, it will filter out by make and to year... How is possible to do this, some better way, than if , elif, elif, elif, ... Is there any proper way, please? This is my solution, but I really dont like it, it is not professional and I don't know, how to find a better solution def is_valid_queryparam(param): return param != '' and param is not None def search_filer(request): qs = Vehicle.objects.all() # VIN and Lot number q = request.GET.get('q') make = request.GET.get('make') model = request.GET.get('model') year_from = request.GET.get('year_from') year_to = request.GET.get('year_from') if is_valid_queryparam(q): qs = qs.filter(Q(vin__icontains=q) | Q(lot_number__icontains=q)) elif is_valid_queryparam(make): qs = qs.filter(make__name__exact=make) elif … -
Unable to figure out what's missing to run my Django Project successfully
Last year, I created a Django project on real estate business. Few days back, I cleaned up my PC & I believe I removed something useful because of which I'm unable to run it on my localhost now. It was working fine before. The major tools that I used in the project include Django, PostgreSql, pgAdmin4, Bulma. As I'm trying to run it via VSCode, it's showing the following traceback. Please help me find out what's exactly missing and how can I get back the proper working flow. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python37-32\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was … -
What is the reason for the error ' PermissionError: [Errno 13] Permission denied ' when running the django server
When I try to run the Django server, the server runs properly, but I also get the following error and my developing website does not load properly. What could be the problem? File "C:\Users\UserName\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\handlers.py", line 183, in finish_response for data in self.result: File "C:\Users\UserName\AppData\Local\Programs\Python\Python38-32\lib\wsgiref\util.py", line 37, in __next__ data = self.filelike.read(self.blksize) PermissionError: [Errno 13] Permission denied -
Field 'id' expected a number but got 'ANPKUR0724' while Importing Data in Django
I have two models, related through a Foreign Key, when im uploading the Model having Foreign key , the id value which is auto created is taking value of the Field which is the foreign key. What could be the possible reason?. class Station(models.Model): BS_ID = models.TextField(max_length=20,unique=True) BS_Name = models.CharField(max_length=20) City = models.CharField(max_length=20,null=True) State = models.CharField(max_length=20,null=True) City_Tier = models.CharField(max_length=10,null=True) Lat = models.DecimalField(max_digits=10,decimal_places=5,null=True,blank=True) Long = models.DecimalField(max_digits=10,decimal_places=5,null=True,blank=True) class CustomerLVPN(models.Model): Customer_Name = models.CharField(max_length=200) Order_Type = models.CharField(max_length=200,null=True) Feasibility_ID = models.IntegerField(null=True) Circuit_ID = models.CharField(max_length=250,null=True,blank=True) Req_BW = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) City = models.CharField(max_length=200,null=True) State = models.CharField(max_length=200,null=True) Region =models.CharField(max_length=200,null=True) L2_Lat = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) L2_Long = models.DecimalField(max_digits=6,decimal_places=3,null=True,blank=True) BS_ID = models.ForeignKey(Station,to_field='BS_ID',related_name='ConfirmedCustomer',on_delete=models.SET_NULL,null=True) So when im Uploading data for CustomerLVPN model im getting the following error - "BS_ID Field 'id' expected a number but got 'ANPKUR0724'." -
Single user Single Device Login using Django rest framework
I wanted to build a login system using Django Rest Framework so that user can only login in into his account through a single Device. Whenever he tried to login from a different device he automatically logged out of the previous device.What should i do for doing this? -
django.db.utils.ProgrammingError: permission denied to create extension "btree_gin" when migrate in django
I'm trying to migrate my Django project, and it creates a new database. The database has btree_gin extensions. However, when I run the command, it gives me the following error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, topup, vendor Running migrations: Applying myapp.0001_initial...Traceback (most recent call last): File "/home/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.InsufficientPrivilege: permission denied to create extension "btree_gin" HINT: Must be superuser to create this extension. -
Choice Field with Radio button not appearing on the admin panel
This is my passsenger model. When I go to my default django model, I can see every fields but not the choice field. I want the option to select the gender of the patient. ALso, I want this in my form. But, there is no field name Gender in my admin panel in the first place. What is the issue?? class Passenger(models.Model): # book_id = models.OneToOneField(Booking, # on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) Customer_id = models.CharField(max_length=50) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(label='Gender', widget= forms.RadioSelect(choices=CHOICES)) -
value error given username must be set on django python project
I'm trying register a user in my project, but when I try to do it I get next error: ValueError: The given username must be set ''' #View.py def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] first_name = request.POST['fname'] last_name = request.POST['lname'] user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect("register") else: return render(request,'register.html') ''' -
Django not null constraint failed altough positive is set
I am doing a pet project to learn django. I am coding a workout journal. When going through the admin to add a workout I input what seems reasonable data but then a NOT NULL constraint failed: workoutJournal_workout.reps error appears. Looking at the error log, it seems the data are correctly read : but I still get the above mentionned error. Below is the extract of my models.py : from django.db import models from django.contrib import admin from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.core.validators import RegexValidator class Exercise(models.Model): name = models.CharField(max_length=120, default="") def __repr__(self): return "self.name" def __str__(self): return self.name class planesOfMovement(models.TextChoices): SAGITTAL = "SA", _("Sagittal") FRONTAL = "FR", _("Frontal") TRANSVERSAL = "TR", _("Transversal") planesOfMovement = models.CharField( max_length=2, choices=planesOfMovement.choices, default=planesOfMovement.FRONTAL, ) class typeOfMovement(models.TextChoices): PUSH = "PS", _("Push") PULL = "PL", _("Pull") CARRY = "CA", _("Carry") LOAD = "LO", _("Load") typeOfMovement = models.CharField( max_length=2, choices=typeOfMovement.choices, default=typeOfMovement.LOAD, ) class Workout(models.Model): date = models.DateField(default=timezone.now) exercises = models.ManyToManyField( Exercise, through="WorkoutExercise", related_name="workout_exercises" ) def __str__(self): # __unicode__ on Python 2 return self.name class WorkoutExercise(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.DO_NOTHING) workout = models.ForeignKey(Workout, on_delete=models.PROTECT) sets = models.PositiveIntegerField() reps = models.PositiveIntegerField() tempo = models.CharField( max_length=11, validators=[ RegexValidator( r"[0-9]{1,3}-[0-9]{1,3}-[0-9]{1,3}", message="Please format your tempo as … -
Sweet Alert is not working inside ajax calls in django
Sweet Alert - https://sweetalert.js.org/guides/ I have imported Sweet Alert using CDN inside my base html file: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> I have tried to use Sweet Alert inside ajax calls in the following way: $.ajax({ type:'POST', url: 'deliveryupdate/'+barcode2+'/', dataType: 'json', data:{ barcode: barcode2, owner: owner2, mobile: mobile2, address: address2, atype: atype2, status: "Gecia Authority Approved", statusdate: today, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(){ console.log("success log"); swal("Success!","Asset request has been approved","success"); }, error: function(){ console.log('error', arguments) swal("Error!","Some error occurred","error"); } }); This is not working, even though there are successful changes in the database, the error function is executing instead of success function, and the error sweet alert flashes for a mini-second and vanishes. The console shows error log. But if I change sweet alert to normal browser alert, it works perfectly.( but that too only in Chrome, not in firefox ) Its working perfectly when I replace swal() with alert(). (only in Chrome though) I don't want the normal browser alert, I need a good looking alert like Sweet Alert. In my other templates where there are no ajax calls and simple alerts, sweet alert is working fine with no problems. Please Help. -
Django: many to many intersec not filtering. Had problem
models.py I have to filter Consumer_order through Newspaper as m2m but intersect not filter? class Newspaper (models.Model): newspaper = models.CharField(max_length=50) language = models.CharField(max_length=50, choices=Language) wh_price = models.DecimalField(max_digits=6,decimal_places=2) sa_price = models.DecimalField(max_digits=6,decimal_places=2) description = models.CharField(max_length=50) company = models.CharField(max_length=50) publication = models.CharField(max_length=50, choices=Publication) def __str__(self): return self.newspaper class Consumer_order(models.Model): #name = models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no = models.CharField(max_length=32) newspaper = models.ManyToManyField(Newspaper,related_name="Consumer_ac_no") added_date = models.DateField(max_length=32,auto_now_add=True) Actually i did filter Consumer_order.objects.filter(newspaper__publication = 'Weekdays').values() Answer >> {'id':1,'ac_no':'2000','added_date':datetime.date(2020,9,13)} Here intersect not filter; if i invoke intersec like this Consumer_order.newspaper.all() Answer >> sunnews,daynews Actually i excepert have to filter intersec newspaper also. guy plz me i stuck 2month about this ....