Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How integrate mobile app and web app for authentication?
I'm new in android and django. Now, my team is building a chat application for android while other team is developing for the web. I want to authenticate user when login to web. So, when user sign in to the web using phone number, it will show such as a pop up at the mobile app that contain of verification code. User must put the verification code to the web app so that he/she can chatting from web (like pc version). Anybody know what tool or others that can help us to integrate mobile app and web app authentication like firebase phone authentication but not through sms? Thank's before -
Django POST Method not working Onyl getting GET method even form submit as well
I am trying t o run my django form but everytimeit isgoing as GET Method even aftersubmitiing the form as well it is getting GET. I wa looking for solution long time but no luck.. here it is server log from vs code [31/Oct/2019 16:15:13] "GET /static/bootstrap.min.js.map HTTP/1.1" 404 1684 [31/Oct/2019 16:15:13] "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1687 <<<<<< THIS IS GET METHOD >>>>>>>>>>> [31/Oct/2019 16:15:14] "GET /forgotpassword/ HTTP/1.1" 200 1808 [31/Oct/2019 16:15:14] "GET /static/bootstrap.min.js.map HTTP/1.1" 404 1684 [31/Oct/2019 16:15:14] "GET /static/bootstrap.min.css.map HTTP/1.1" 404 1687 [31/Oct/2019 16:15:17] "POST /successforgotpassword/ HTTP/1.1" 200 286 This is my models.py from django import forms class ForgotPasswordForm(forms.Form): mail = forms.EmailField(label="EMAILL - ID", label_suffix="*", max_length=50, min_length=4, widget=forms.EmailInput( attrs={"class": "form-control", "placeholder": "Enter Email Address"})) def clean_mail(self): passed_data1 = self.cleaned_data.get("mail") passed_data2 = self.cleand_data["mail"] print(passed_data1, passed_data2) req_data = "abc@gmail.com" if passed_data1 == req_data: raise forms.ValidationError("boss no gmail , why!!!") if passed_data1 == "": raise forms.ValidationError("boss no gmail , why!!!") return passed_data1 This is my forgotpassword.html <body> <div class="container" style="margin-top: 100px;"> <form action="/successforgotpassword/" method="POST" class="form-horizontal" enctype="multipart/form-data"> {% csrf_token %} <div class="jumbotron boxing"> <p style="text-align:center; background-color: rgb(246, 250, 8); color: rgb(250, 19, 19); font-size: 18px;"> Please provide your valid email address , We are going to send mail to mentioned email address … -
Django filter by hour of day when timezone info stored in database
With the following model structure: class Place(models.Model): ... timezone = TimeZoneField() # Defined in a package called django-timezone-utils ... class Session(models.Model): ... place = model.ForeignKey(Place, ...) created = models.DateTimeField(auto_now_add=True) # Saved in utc ... I want to get all sessions that are created inside 10th hour of day. Basic approach to this is: Session.objects.filter(created__hour=10) But with this, as expected, results are filtered by UTC time. How can I get Sessions objects that are created inside the 10th hour of day, in the timezone of the Place they are connected to? Note that there could be sessions made on different Places with different timezones, but I want to get the sessions that are created inside the 10th hour of day in their local timezones. Something like annotating each result with created time in local timezone, and then filtering on that annotated value might work, but I do not know how can I build that annotation -
SELF JOIN queryset on joined table in Django?
I want to make a self join on an joined table. I have a queryset: paymentsss = Transaction.objects.all().select_related('currency', 'payment_source__payment_type','deal__service', 'deal__service__contractor').order_by('-id') This is a fragment from a table payment_source. Fields that contain bank_card joined with Transaction, but bank_card_details is not. They have same payer_id. It is necessary that these two lines are combined into one. How i can do this? Models.py class Transaction(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE) deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE) # service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE) payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE) payment_date = models.DateTimeField(blank=True, null=True) amount = models.IntegerField(blank=True, null=True) status = models.CharField(max_length=255, blank=True, null=True) context = models.TextField(blank=True, null=True) class Meta: managed = False db_table = '"processing"."transaction"' class PayerPaymentSource(models.Model): id = models.BigIntegerField(blank=True, null=False, primary_key=True) # payer_id = models.BigIntegerField(blank=True, null=True) payment_type = models.ForeignKey(PaymentType, max_length=64, blank=True, null=True, on_delete=models.CASCADE) source_details = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = '"processing"."payer_payment_source"' -
How to specify the many to one models in django?
I'm trying to link two models: Department and User. They have a many-to-one relation. A department can have only admin (User) and a department can have many users. A User can only be in one department. Here is my code class Department(models.Model): admin = models.ForeignKey("applications.User", blank=True, null=True, on_delete=models.SET_NULL) class User(AbstractUser, models.Model): username = models.CharField(max_length=32, unique=True) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL, related_name="members") But I'm having this error: ERRORS: applications.Department.admin: (fields.E303) Reverse query name for 'Department.admin' clashes with field name 'User.department'. HINT: Rename field 'User.department', or add/change a related_name argument to the definition for field 'Department.admin'. I need to keep attributes naming as is. How to properly fix and model the relation between the tables? Is django assuming that Department may have many admins? -
Django multiple clients deployment solutions
I am building a Django app where there are several "user spaces" or "client domains". I was wondering how I could separate each clients from accessing other's data ? So far I have come up with several options : Distribute one project per client with their own database Keep one database and one django running (two options) a) Add some top level table with some ID to be referenced in each model. But then how do I restrict someone from impersonnating someone else's ID and access their data ? b) Build some Authorization layer on top of requests using a header or some query param to help discriminate which data the user can acces (but I don't really know how to do so) What is the state of the art in the domain of multiple clients using a same Django app ? Are my solutions appropriate and if so, how do I implement them ? I have seen few related posts / articles on internet so I'm resorting to ask here. Thanks in advance ! -
Checking if an M2M field is empty or not in Django
I have the following models: class Pizza(models.Model): toppings = models.ManyToManyField(Topping) has_toppings = models.BooleanField(default=False) def check_if_there_are_toppings(self): if len(self.toppings.all()) > 0: self.has_toppings = True @receiver(m2m_changed, sender=Pizza.toppings.through) def toppings_changed(sender, instance, **kwargs): instance.check_if_there_are_toppings() instance.save() What I want to do is update the has_toppings field whenever the toppings length is more than 0. What would be the correct way to do this? Thanks for any help. -
Python Django Forms and models
guys i have problem about django forms when post to my database here my code : forms.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') models.py : class InstagramUsernameForm(forms.ModelForm): nama_orang = forms.CharField(max_length=20) username = forms.ModelChoiceField(queryset=Instagram.objects.all()) nama_depan = forms.ModelChoiceField(queryset=Instagram.objects.values_list("nama_depan")) class Meta: model = InstagramUsername fields = ('nama_orang','username','nama_depan') so the problem is when i deactivate "nama_depan" in forms.py its can save to models database when i activate it cant save to models database anyone know it ty ;D -
Efficient method to get all many to many objects from queryset
I have models similar to the below: class Tag(models.Model): text = models.CharField(max_length=30) class Post(models.Model): title = models.CharField(max_length=30) tags = models.ManyToManyField(Tag) A Post can have many Tags and Tags can be associated with many Posts. What I need is to get a list of all posts along with all the tags associated with each post. I then create a Pandas DataFrame from that data. Here is how I am currently doing it: qs = Post.objects.all().prefetch_related('tags') tag_df = pd.DataFrame(columns=["post_id", "tags"]) for q in qs: tag_df = tag_df.append( { "post_id": q.pk, "tags": list(q.tags.all().values_list("text", flat=True)), }, ignore_index=True, ) post_df = pd.DataFrame(qs.values("id", "title")) final_df = post_df.merge(tag_df, left_on="id", right_on="post_id") The result is correct in terms of the data I require. The problem is how incredibly inefficient it is and the number of queries that run even though I'm using prefetch_related. It appears that a query is hitting the database for each iteration of the loop. Is there a better, more efficient way to do this (possibly without loops)? All I need in the end is a dataframe that contains all the posts along with a column which has a list of the tags for each post. -
Django: DRF and surrogates
I have a weird error from production related to utf-8 and surrogate pairs. Bellow the code to reproduce the issue(for simplicity I present everything in one file and omit some unnecessary details) class User(models.Model): username = models.CharField('Username', max_length=255,) class Meta: app_label = 'users' class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['username'] class UserViewSet(viewsets.ModelViewSet): queryset = models.User.objects.all() serializer_class = UserSerializer def test_create_user_and_set_password(django_app): response = django_app.post_json( reverse('users-list'), { 'username': '\ud83d', } ) assert response.status_code == 201 assert models.User.objects.count() == 1 as result of running the test I receive an error(the same as in production): def execute(self, query, params=None): if params is None: return Database.Cursor.execute(self, query) query = self.convert_query(query) > return Database.Cursor.execute(self, query, params) E UnicodeEncodeError: 'utf-8' codec can't encode character '\ud83d' in position 0: surrogates not allowed How should I handle such problems? My knowledge about encoding is limited but from common sense it obvious that I'm not the first one who discover such problem. -
Django:: AUTH_USER_MODEL refers to model 'accounts.User' that has not been installed
settings.py INSTALLED_APPS = [ 'accounts.apps.AccountsConfig', ] # Auth AUTHENTICATION_BACKENDS = [ 'conf.backends.AuthBackend', ] AUTH_USER_MODEL = 'accounts.User' accounts/models.py class User(AbstractUser): class Meta: db_table = 'accounts_users' email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) provider = models.CharField(max_length=10, null=True) verified_email = models.BooleanField(default=False) group_permission_id = models.IntegerField(null=True) objects = MyUserManager() error log Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 165, in get_model return self.models[model_name.lower()] KeyError: 'user' i suddenly find this error. why get this error? full error log Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1056139d8> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 165, in get_model return self.models[model_name.lower()] KeyError: 'user' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/__init__.py", line 165, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 207, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 168, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'accounts' doesn't have a 'User' model. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File … -
How to fix 'Specifying a namespace in include() without providing an app_name '
I am facing with the problem of setting the app_name attribute in the included module. Despite the fact that I have seen similar answers on how to fix it, I had not found something that works for me. here is my urls.py from django.conf.urls import url,include from django.contrib import admin from intranet import views,forms from django.contrib.auth import views as auth_views from django.conf import settings from rest_framework import routers from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import reverse router = routers.DefaultRouter() router.register(r'pharmakeia', views.PharmakeiaViewSet,base_name='pharmakeia') router.register(r'doctors', views.DoctorsViewSet,base_name='doctors') router.register(r'new-pharmakeia', views.VriskoViewSet,base_name='new-pharmakeia') router.register(r'new-all-pharmakeia', views.VriskoAllViewSet,base_name='new-all-pharmakeia') views.json_data,base_name='test_pharmakeia') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^rest/', include(router.urls, namespace='rest')), url(r'^api-auth/', include(rest_framework.urls, namespace='rest_framework')), I tried to declare an app_name variable app_name="intranet" and then fix the urls containing include function like below url(r'^rest/', include((router.urls,app_name), namespace='rest')), url(r'^api-auth/', include(('rest_framework.urls',app_name), namespace='rest_framework')), I face up a new problem "ModuleNotFoundError: No module named 'router' "despite the fact that I have already defined rooter here is my output from command line self._target(*self._args, **self._kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/www/wwwroot/geolocator/geolocator_venv/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in … -
Heroku build React app before deploying through Django
I successfully deployed my Django project to Heroku. But I want to be able to automatically build React before deploying. The React app is served through Django, so I have the bundled files of React in my templates and static folders of the Django app. The project structure looks something like this: react/ build/ components/ App.js package.json ... django/ templates/ static/ ... Procfile requirements.txt Pipfile I have both the React and Django projects in the same repository and I want to run npm run build automatically before Django is deployed. I set up the build script to move the bundled files from React to Django. From what I've read, I need to add the NodeJS buildpack, but I don't know how to set it up to run before the Python buildpack. Basically, the NodeJS process should just build my React app and then terminate. After that, the Python process should start up and deploy the Django project. One solution to do this would be to use Docker and deploy that image to Heroku. But, is there an easier way? -
Apache kafka producer not sending messages
I am using kafka-python in a django project. Initialised the producer in settings.py file. Calling producer.send is not sending the messages. Earlier my producer was initialised in a function everytime and I was using producer.send().get(timeout=1) to send messages and it worked fine. Now I have changed the initialisation to settings file and removed .get() while calling send and it is not working. Old working code below: In module_x.py: from kafka import KafkaProducer def my_func(): KAFKA_CONNECTION = KafkaProducer(bootstrap_servers=CONFIGS.KAFKA_URL) producer = KAFKA_CONNECTION producer.send(topic, key=key, value=json.dumps(data)).get(timeout=1) Changed code below: Now changed the initialisation to settings file to avoid initialisation everytime my_func is called. In settings.py: KAFKA_CONNECTION = KafkaProducer(bootstrap_servers=CONFIGS.KAFKA_URL) In module_x.py: from django.conf import settings def my_func(): producer = settings.KAFKA_CONNECTION producer.send(topic, key=key, value=json.dumps(data)) Note that I even tried with .get(timeout=1) on send but I was getting Kafka.TiemoutError Do I have to use producer.flush() after producer.send or use linger_ms in send. ? -
Connect with a default admin user in Django 2.0
I am trying to remove the authentication page and allow the connected user to be admin by default. It may be possible to do but because I am new with Django, I cannot find a solution to it... I tried to do something like that in a file called "default_auth.py": class User: is_superuser = True is_active = True is_staff = True id = 1 pk = 1 User.has_module_perms = True User.has_perm = True class Middleware(object): def __init__(self, get_response): self.response = get_response def __call__(self, request): request.user = User() return self.response(request) Then I saw on google that I need to comment this line: 'django.contrib.auth.middleware.AuthenticationMiddleware' and replace it with: 'myProject.default_auth.Middleware' which is causing me an error when running the server. Does anyone faced the same requirements or have an idea to do it ? Thank you for your help -
Is it possible in django models to do like this ? How to make a dropdown list in django models using another fields models
Guys can you help me how to make dropdown in django models but the dropdown list is from another models's field do you have some reference/link tutorial pls comment below thanks ;D! # Create your models here. class Instagram(models.Model): nama_depan = models.CharField(max_length=100) nama_belakang = models.CharField(max_length=100) username = models.CharField(max_length=100) def __str__(self): return self.username class InstagramUsername(models.Model): nama_orang = models.CharField(max_length=20,blank=True) username = models.Instagram.username nama_depan = models.CharField(max_length=30,blank=True) def __str__(self): return self.username -
Error relationship users_user_permissions when i try to add or change user in django admin
I am writing because I can’t understand what’s wrong, recently this code worked ... I have a custom user(Testuser). When I try to add or change it, it says that there is no users_user_permissions table. I tried run a manage.py migrate --run-syncdb and this does not work. How to fix it? All permissions are stored in the default schema public . models.py class CustomUserManager(UserManager): pass class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ("can_see_documents", "documents"), ("can_see_sverka", "sverka"), ("can_see_ways", "ways") ] objects = CustomUserManager() Admin.py class MyUserAdmin(UserAdmin): model = TestUser form = CustomUserChangeForm add_form = CustomUserCreationForm list_display = ('username', 'first_name', 'email', 'phone', 'is_active',) list_filter = (['is_active']) search_fields = () filter_horizontal = (['groups', 'user_permissions']) fieldsets = ( ('Personal info', {'fields': ('first_name', 'email', 'phone', 'password')}), ('permissions', {'fields': ('is_active', 'is_staff','user_permissions')}) ) add_fieldsets = UserAdmin.add_fieldsets + ( ('Personal info', {'fields': ('first_name', 'email', 'phone')}), ('permissions', {'fields': ('is_active', 'is_staff','user_permissions')}), ) admin.site.register(TestUser, MyUserAdmin) form.py class CustomUserCreationForm(UserCreationForm): phone = PhoneNumberField(region='RU', required=True) class Meta(UserCreationForm): model = TestUser fields = ('username', 'first_name', 'email', 'phone') class CustomUserChangeForm(UserChangeForm): phone = PhoneNumberField(region='RU', required=True) class Meta: model = TestUser fields = ('username', 'first_name', 'email', 'phone') settings.py AUTH_USER_MODEL = … -
I created login authentication in Rest Api
I created login authentication in Rest Api it Retrieves token key in postman. Right now I need the username of the person associated with a token key. how to do that ? '''class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] django_login(request, user) token, created = Token.objects.get_or_create(user=user) return Response({"token": token.key }, status=200)''' '''class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get("username", "") password = data.get("password", "") if username and password: user = authenticate(username=username, password=password) if user: if user.is_active: data["user"] = user else: msg = "User is deactivated." raise exceptions.ValidationError(msg) else: msg = "Unable to login with given credentials." raise exceptions.ValidationError(msg) else: msg = "Must provide username and password both." raise exceptions.ValidationError(msg) return data''' -
Django - Need some assistance with Refactoring / Improving my view
Im making an airbnb website as a project, and I have created this monster ( yes, I know ) : def apartment_view(request, apartment_id): reservation = Reservation.objects.filter(apartment__pk=apartment_id) apartment = get_object_or_404(Apartment, pk=apartment_id) context = {} context['apartment'] = apartment unavailable = [] for start, end in apartment.reservations.values_list('start_date', 'end_date'): while start <= end: unavailable.append(start.strftime('%-d-%m-%Y')) start += datetime.timedelta(days=1) form = ReservationForm() context['unavailable_dates'] = json.dumps(unavailable) context['form'] = form if request.method == 'GET': form = ReservationForm() if request.method == "GET": form = ReservationForm(request.GET) if form.is_valid(): context = {} reservation = form.save(commit=False) reservation.apartment = apartment start_date = request.GET.get('start_date', None) end_date = request.GET.get('end_date', None) sdate = datetime.datetime.strptime(start_date, '%Y-%m-%d') #start edate = datetime.datetime.strptime(end_date ,'%Y-%m-%d') #end prices_by_date = apartment.price_by_date(sdate, edate) user_dates = [sdate + datetime.timedelta(days=x) for x in range((edate-sdate).days + 1)] user_date_list = [] for day in user_dates: user_date_list.append(day.strftime('%d,%m,%Y')) context['price_per_day'] = prices_by_date.price context['total_price'] = len(user_date_list) * prices_by_date.price context['unavailable_dates'] = json.dumps(unavailable) context['form'] = form context['apartment'] = apartment context['date_start'] = start_date context['date_end'] = end_date form.save() return render(request, "booking/apartment.html", context) elif request.method == 'POST': form = ReservationForm(request.POST) if form.is_valid(): reservation = form.save(commit=False) reservation.apartment = apartment reservation.save() form.save() HttpResponseRedirect(reverse('booking:apartment', kwargs={"apartment_id": apartment.pk})) return render(request, 'booking/apartment.html', context) To describe what is going on, user first comes to the site and picks the start and end date to … -
X accel redirect not downloading the file
I'm trying to add authentication to allow only valid users to download static files from nginx. This is my Nginx configuration : location ^~ /download-logs { internal; alias media/logs; } And in Django I've added a route to handle the response : url : url(r'^media/', views.protectedMedia, name="protect_media"), views : def protectedMedia(request): response = HttpResponse(status=200) response['Content-Type'] = '' response['X-Accel-Redirect'] = '/download-logs/log.txt' return response When i try to go to the route http://my_ip_address/media/ from the response i can see X accel redirect field, but file is not getting downloaded -
Got widnows error 1120 while trying to install psycopg2/psycopg2-binary
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\link.exe' failed with exit status 1120 I have installed postgresql and added to the global variables path to pg_config. Windows 8, python 3.8 -
Check If one datetime lies between two datetimes python
I am trying to check if one datetime lies between two datetimes, most of the cases return true, but in below case it return false whereas it should return true, how can I check it in proper way. time1=1900-01-01 08:30:00 time2=1900-01-01 00:00:00 inbetween=1900-01-01 20:00:00 if (time1<=inbetween<=time2): # if 12 hour format (8:30AM<8:00PM<12:AM) it should be true print("True") return True else: print("False") return False in above case inbetween lies between time1 and time 2 so it should return True but it return False. How can I check. NOTE: the date will always remain same so I have to check it on the time basis. -
Queryset v/s List Django
I want to know what is the difference in terms of execution in Django queryset and Django list. For eg, List of Objects v/s Queryset of Objects Will there be much difference in the execution part? -
How to cache query results in django and use it?
I have a small request, the data from which is transferred to <select>. I use a paginator and this selector makes a request every page.So I want to cache it and try to update every 10 minutes, for example.How do I save a cache and how do I pass it to a template so that the selector works? views.py contractors = Contractors.objects.values_list('name', flat='True') HTML-code <select name="contractorName" class="form-control" id="id_contractorName"> <option value="" selected=""></option> {% for contractor in contractors %} <option value="{{ contractor }}">{{ contractor }}</option> {% endfor %} </select> -
Comparing non-optional value of type 'JSON' to 'nil' always returns true. Any suggestion to fix this?
if let vendorId = vendor?.id { APIManager.shared.getProducts(vendorId: vendorId, completionHandler: { (json) in if json != nil { <<<<<<<<<Comparing non-optional value of type 'JSON' to 'nil' always returns true self.products = [] if let tempProducts = json["products"].array { for item in tempProducts { let product = Product(json: item) self.products.append(product) } self.tableView.reloadData() Helpers.hideActivityIndicator(self.activityIndicator) } } }) } } In My APIManager.Swift import Foundation import Alamofire import SwiftyJSON import FBSDKLoginKit class APIManager { static let shared = APIManager() let baseURL = NSURL(string: BASE_URL) var accessToken = "" var refreshToken = "" var expired = Date() // Request Server Function func requestServer(method: Alamofire.HTTPMethod , path: String, params: [String: AnyObject]?, encoding: ParameterEncoding, completionHandler: @escaping (JSON?) -> Void ) { let url = baseURL?.appendingPathComponent(path) refreshTokenIfNeed { AF.request(url!, method: method, parameters: params, encoding: encoding, headers: nil).responseJSON{ response in switch response.result { case .success(let value): let jsonData = JSON(value) completionHandler(jsonData) break case .failure: completionHandler(nil) break } } } } // API - Getting the latest order (Customer) func getLatestOrder(completionHandler: @escaping (JSON) -> Void) { let path = "api/customer/order/latest/" let params: [String: Any] = [ "access_token": self.accessToken ] requestServer(method: .get, path: path, params: params as [String : AnyObject], encoding: URLEncoding()) { (json) in print(json!) } } }