Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template: How to use values/values_list
In template I am trying to do something like this: {{ request.user.profile.following.all.values_list }} and I get <QuerySet [(7, 2, 1)]> , but I want to get <QuerySet [2]> like in Django values_list. For example: Follow.objects.filter(follow_by=self.request.user.profile).values_list('follow_to', flat=True) Can I pass argument like this in template? -
How to make Django 3, channels and uvicorn work together
I have been trying to switch from daphne to uvicorn for production with a project using django 3 and channels. I have been encountering errors while loading the classical asgi file for channels. Either I can't use it due to synchronous call to django.setup or get_application. I tried to tweak this file with the sync_to_async call without success. Has anyone managed to make it work ? Original asgi.py Code import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") django.setup() application = get_default_application() StackTrace Traceback (most recent call last): File "/usr/local/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap self.run() File "/usr/local/lib/python3.8/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/subprocess.py", line 61, in subprocess_started target(sockets=sockets) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 407, in run loop.run_until_complete(self.serve(sockets=sockets)) File "/usr/local/lib/python3.8/asyncio/base_events.py", line 612, in run_until_complete return future.result() File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/main.py", line 414, in serve config.load() File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/config.py", line 300, in load self.loaded_app = import_from_string(self.app) File "/var/www/.cache/pypoetry/virtualenvs/project-4ffvdAoS-py3.8/lib/python3.8/site-packages/uvicorn/importer.py", line 20, in import_from_string module = importlib.import_module(module_str) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line … -
What will Happen if i remove footer credit from colorlib html template(https://colorlib.com/preview/theme/dento/index.html) for django?
I am first time trying to use a readymade template for my website and I have downloaded the 'Dento'(https://colorlib.com/preview/theme/dento/index.html) template from Colorlib(https://colorlib.com/) and in the terms and condition is written that if I am using a free template I am not allowed to remove the footer credit so what will happen if I remove the footer credit ,will they be able to track me or find me or file a lawsuit or what ?? please tell me what can happen if I remove the footer credit and publish my website through heroku -
Django Rest Framework raise Validation Error Message
I am working on bus booking api where BoardingPoints and Location Model having ManytoMany Relations. I tried adding some validation while removing relation between location and boarding point. I want validation error in following format {'point': Boarding point: Manchester is not assigned to Location: London} My code is below class RemoveBoardingPointFromLocationUseCase(BaseUseCase): """ Use this to remove boarding point assigned to list """ def __init__(self, serializer: DeleteBoardingPointToLocationSerializer, location: Location): self._serializer = serializer self._data = serializer.validated_data self._location = location def execute(self): self._is_valid() self._factory() def _factory(self): self._location.point.remove(*self._data.get('point')) def _is_valid(self): boarding_points = self._location.point.all() if not set(self._data.get('point')).issubset(set(boarding_points)): _message = ("{point: Boarding point: %(boarding_point)s is not in %(location)s}" % { 'boarding_point': self._data.get('point')[0], 'location': self._location}) raise ValidationError(_message) I am getting message in following format if I try self._data.get('point')[0:] validation error message as "{point: Boarding point: [<BoardingPoint: Manchester>, <BoardingPoint: Oxford>] is not in London}" what should i do in my validation error message part? -
Django: Identical text not unique on binary level
I have a modal with a field my_field which has to be unique. I´ll check if a task has to be executed later onwards by checking if the entity already exists: class MyModel(models.Model): my_field = models.CharField(max_length=75, unique=True) And later: if MyModel.objects.filter(my_field=my_value).exists(): pass # execute task and save it under the value name in question else: pass The values I need to compare here are received via two different 3rd party apis. Now I have the problem, that the "human readable" same text is not detected as identical, which makes the unique attribute fail (in the sense of it does not let the save fail) and of course also the "does it exist? check". So after a while, I hacked into django shell and converted two of the values into binary code and that way they are not the same. So I read about normalization and came up with this: class MyModel(models.Model): ... def save(self, *args, **kwargs): if self.pk is None: self.my_field = unicodedata.normalize('NFC', self.my_field) ... And before I query the DB, I normalize the received value the same way. Still I get instances with the same "human readable text" but different binary code and the problem persists. How can I … -
Django: How to decide between class-based and function-based custom validators?
This is a beginner question. I'm working on a website that allows users to upload a video to a project model (via ModelForm) and I want to validate this file correctly. I originally declared the field in this way: from django.db import models from django.core.validators import FileExtensionValidator def user_directory_path(instance, filename): """ Code to return the path """ class Project(models.Model): """ """ # ...Some model fields... # Right now I'm only validating and testing with .mp4 files. video_file = models.FileField( upload_to=user_directory_path, validators=[FileExtensionValidator(allowed_extensions=['mp4'])] ) But I read in several places that it was better to use libmagic to check the file's magic numbers and make sure its contents match the extension and the MIME type. I'm very new to this, so I might get some things wrong. I followed the validators reference to write a custom validator that uses magic. The documentation also talks about "a class with a __cal__() method," and the most upvoted answer here uses a class-based validator. The documentation says that this can be done "for more complex or configurable validators," but I haven't understood what would be a specific example of that and if my function-based validator is just enough for what I'm trying to do. I … -
Reaching the fields in the data serialized over the table
With django, a json data comes as below. How can I access the fields in this incoming data? In other words, after serializing the data I query from the table, I need to access all of them one by one. [{ 'model': 'cryptoinfo.cryptoinfo', 'pk': 4, 'fields': {'createdDate': '2020-10-08T20:49:16.622Z', 'user': 2, 'created_userKey': '25301ba6-1ba9-4b46-801e-32fc51cb0bdc', 'customerKey': '61754ecf-39d3-47e0-a089-7109a07aca63', 'status': True, 'side': 'BUY', 'type': '1', 'symbol': 'NEOUSDT', 'quantity': '1', 'reversePosition': '1', 'stopMarketActive': '1', 'shortStopPercentage': '1', 'longStopPercentage': '1', 'takeProfit': '1', 'addPosition': '1', 'takeProfitPercentage': '1', 'longTakeProfitPercentage': '1', 'shortTakeProfitPercentage': '1', 'groupCode': '1453', 'apiKey': 'API_KEY', 'secretKey': 'SECRET_KEY'}}, { 'model': 'cryptoinfo.cryptoinfo', 'pk': 7, 'fields': {'createdDate': '2020-10-08T20:51:16.860Z', 'user': 1, 'created_userKey': '2f35f875-7ef6-4f17-b41e-9c192ff8d5df', 'customerKey': 'b1c8cee3-c703-4d27-ae74-ad61854f3539', 'status': True, 'side': 'BUY', 'type': '1', 'symbol': 'NEOUSDT', 'quantity': '1', 'reversePosition': '1', 'stopMarketActive': '1', 'shortStopPercentage': '1', 'longStopPercentage': '1', 'takeProfit': '1', 'addPosition': '1', 'takeProfitPercentage': '1', 'longTakeProfitPercentage': '1', 'shortTakeProfitPercentage': '1', 'groupCode': '1453', 'apiKey': '', 'secretKey': ''}} ] def webhook(request): queryset = CryptoInfo.objects.filter(status=True, symbol='NEOUSDT', side='BUY') data = serializers.serialize('json', queryset) for sym in data: print(sym.get('created_userKey')) sleep(1) return HttpResponse(data, content_type='text/json-comment-filtered') -
DjangoLoop through an app urls in template
I'm django beginner working on my third project, but running into small issue. Basically, i have an app called 'projects' which contains html templates that the CBV needs for CreaeView, UpdateView, DeleteView and ListView. My base templates inherits from a menus file which contains all the navigation menus needed for the website. Now my issue is i wanted to make projects menu active (css) for all the crud operations of project app. i did this and it's working as intended: {% url 'projects-list' as url %} {% url 'project-detail' project.pk as url1 %} {% url 'project-create' as url2 %} {% url 'project-update' project.pk as url2 %} <a href="{{ url }}" {% if request.path == url or request.path == url1 or request.path == url2 or request.path == url3 %} class="item active" {% endif %}><span class="icon"><i class="fa fa-folder-o"></i></span><span class="name">Projects</span></a> But i don't like it this way as it's too repetitive and i want to add a lot of menus like this in future. What is the easiest way to loop through all links of app? Thanks in advance. Best regards. -
sql query to python django query
I'm new to Django and SQL. I have this following SQL query. How to implement the same in the Django query? "SELECT DISTINCT C1.CLASSDESC AS CLASS,C2.CLASSCODE AS CODE, C1.CARDCATEGORY AS CATEGORY, C2.CLASSBENEFITS BENEFITS FROM CARDCLASSMAPPING C1,CARDCLASSMASTER C2 WHERE C1.ISACTIVE = 1 AND C2.ISACTIVE = 1 AND C1.CLASSDESC = C2.CLASSDESC AND C1.SCHEMETYPE = ? AND C1.SCHEMECODE = ? AND C1.GLCODE = ? AND C1.ACCOUNTCATEGORY = ? ORDER BY CLASS"; -
Developing filtering api for the fields of two models which has many to one relationship (ie one model has a foriegn key field) using djangofilterset
Its not a problem for making a filterset for a single model. But I have two models and I have to make an endpoint http://127.0.0.1:8000/api/activities/?destination=Dubai&title=Surfing like this. Here destination is the foreign key field. I can only filter by using primary key, but I want to put the actual name of destination. What should I do? class Destination(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) discount = models.CharField(max_length=255, default="5% OFF") image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) def __str__(self): return self.name class TopActivities(models.Model): destination = models.ForeignKey(Destination, on_delete=models.CASCADE) image = models.ImageField(blank=True) thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) title = models.CharField(max_length=64) description = models.TextField(blank=True) def __str__(self): return self.title class TopActivitiesSerializer(serializers.ModelSerializer): destination= serializers.StringRelatedField() class Meta: model = TopActivities fields = '__all__' class TopActivitiesListAPIView(ListAPIView): queryset = TopActivities.objects.all() serializer_class = TopActivitiesSerializer filter_backends = [DjangoFilterBackend] filterset_fields = [ 'destination', 'title', ] Here, If I put pk or id of the destination field in the query parameter, then I can see the result, but I need to be able to search by using destination name itself. -
Reverse for 'edit' with arguments '(12,)' not found. 1 pattern(s) tried: ['edit$']
In views.py def index(request): if request.method == "GET": posts = Post.objects.all().order_by('-id') allpost = True paginator = Paginator(posts, 5) # Show 5 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/index.html",{ "AllPost" : allpost, "page_obj" : page_obj, }) def edit(request,post_id): if request.method == "POST": post = Post.objects.get(id=post_id) content = request.POST["textarea"] post.content = content post.save() return redirect("index") In urls.py path("", views.index, name="index"), path("edit",views.edit,name="edit"), Index.html <form method="POST" action="{% url 'edit' post.id %}" id="edit-form{{post.id}}" style="display:none;"> {% csrf_token %} {{post.date}} <textarea rows="5" class="form-control" name="textarea">{{post.content}}</textarea> <button type="submit" class="btn btn-outline-primary" style="float: right;">Save</button> </form> Trying to edit some post but getting an error of Reverse for 'edit' with arguments '(12,)' not found. 1 pattern(s) tried: ['edit$'] -
How to set virtualenv to stay active on a host server
I created a website that uses vuejs as the frontend and django as the backend with another service running behind everything that im making api calls to. So django is setup in a way to look at the dist folder of Vuejs and serve it if you run manage.py runserver. but the problem is that my service that I created is in python and it needs to run in a virtualenv in order to work (It uses tensorflow 1.15.2 and this can only run in a contained environment) I'm sitting here and wondering how I can deploy the django application and keep the virtualenv active and Im coming up with nothing, I've tried doing some research on this but everything I found was not relevant to my problem. I've deployed it and when I close the ssh connection the virtualenv stops. If there is anyone that can enlighten my ways I would appreciate it. -
How to show all data in USERS Model in my profile page
views.py Here i have made logic where i have passed user data in my profile file but still it shows not output there #Authenciation APIs def handleSignup(request): if request.method=='POST': #Get the post parameters username=request.POST['username'] fname=request.POST['fname'] lname=request.POST['lname'] email=request.POST['email'] pass1=request.POST['pass1'] pass2=request.POST['pass2'] #checks for errorneous input #username should be <10 # username shouldbe alphanumeric if len(username)>10: messages.error(request,"username must be less than 10 characters") return redirect('/') if not username.isalnum(): messages.error(request,"username should only contain letters and numbers") return redirect('/') if pass1!=pass2: messages.error(request,"Password do not match") return redirect('/') #Create the user myuser=User.objects.create_user(username,email,pass1) myuser.first_name=fname myuser.last_name=lname myuser.save() messages.success(request,"your Musify account has been created succesfully Now go enter your credentials into the login form") return redirect('/') else: return HttpResponse('404 - Not Found') def handleLogin(request): if request.method=='POST': #Get the post parameters loginusername=request.POST['loginusername'] loginpassword=request.POST['loginpassword'] user=authenticate(username=loginusername,password=loginpassword) if user is not None: login(request,user) messages.success(request,"succesfully Logged In") return redirect('/') else: messages.error(request,"Invalid credentials Please try again") return redirect('/') return HttpResponse('404 - Not Found') def profile(request): user=User.objects.get(id=request.user.id) d={'user':user} return render(request,'profile.html',d) profile.html I have made sign up form where i have username,firstname,lastname,email fields in it. and i want to display this field on my profile page But its not working,not showing any output on my profile page. profile here {% for i in d %} {{i.email}} {{i.firstname}} … -
Resize uploaded images does not work correctly Django
I have model upload_path = 'images' upload_path_to_resize = 'resized' class Images(models.Model): image = models.ImageField(upload_to=upload_path, blank=True, null=True) image_url = models.URLField(blank=True, null=True) image_resized = models.ImageField(upload_to=upload_path_to_resize,blank=True) width = models.PositiveIntegerField(null=True) heigth = models.PositiveIntegerField(null=True) def clean(self): if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ): raise ValidationError('Empty or both blanked') def get_absolute_url(self): return reverse('image_edit', args=[str(self.id)]) def save(self): if self.image_url and not self.image: name = str(self.image_url).split('/')[-1] img = NamedTemporaryFile(delete=True) img.write(urlopen(self.image_url).read()) img.flush() self.image.save(name, File(img)) self.image_url = None super(Images, self).save() def resize(self): if (self.width != None) or (self.heigth != None): img = Image.open(self.image.path) output_size = (self.width, self.heigth) img.thumbnail(output_size) img.save(self.image_resized.path) super(Images, self).save() The resize method should take the existing file from the "ImageField" field, resize and load into the "image_resized" field, but for some reason the FormResize form passes the height and width arguments to the model, but nothing happens from django.forms import ModelForm from .models import Images class ImageForm(ModelForm): class Meta: model = Images fields = ['image', 'image_url'] class ResizedForm(ModelForm): class Meta: model = Images fields = ['width', 'heigth'] What do I need to do to make the resize work correctly? -
django redirect test - AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
I can't get my test to accept the redirect works... I keep getting this error "AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)" but the redirect working logs web_1 | [11/Oct/2020 12:41:33] "GET /calendar/5d8b6a0a-66b8-4909-bf8f-8616593d2663/update/ HTTP/1.1" 302 0 web_1 | [11/Oct/2020 12:41:33] "GET /calendar/list/ HTTP/1.1" 200 4076 Please can some advise where I am going wrong. I have tried using assertRedirects but this still doesn't pass test.py class EventTests(TestCase): def setUp(self): self.eventbooked = Event.objects.create( manage=self.user, availability='Booked', start_time='2020-09-30 08:00:00+00:00', end_time='2020-09-30 17:00:00+00:00', ) def test_event_update_redirect_if_booked_view(self): self.client.login(email='test_username@example.com', password='da_password') response = self.client.get(self.eventbooked.get_absolute_url_edit()) self.assertEqual(response.status_code, 302) self.assertContains(response, 'Update Availability') view.py - this is where the redirect happens, this the object is excluded. class CalendarEventUpdate(LoginRequiredMixin, UpdateView): model= Event form_class = EventForm template_name='calendar_update_event_form.html' def get_queryset(self): return Event.objects.filter(manage=self.request.user).exclude(availability='Booked') def get(self, request, *args, **kwargs): try: return super(CalendarEventUpdate, self).get(request, *args, **kwargs) except Http404: return redirect(reverse('calendar_list')) models.py def get_absolute_url_edit(self): return reverse('calendar_event_detail_update', args=[str(self.id)]) -
Django 3 How To Join Without Where?
I have a question about joining table on Django, here is my models # Create your models here. class Customer(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=13, null=True) email = models.CharField(max_length=50, null=True) region = models.CharField(max_length=100, default='1') date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "customers" def __str__(self): return self.name class Product(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=False) price = models.IntegerField(default=0) category = models.CharField(max_length=500, null=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: db_table = "products" def __str__(self): return self.name class Order(models.Model): id = models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False) customer = models.ForeignKey(Customer, null=True,on_delete=models.SET_NULL, related_name='cus_orders') product = models.ForeignKey(Product, null=True,on_delete=models.SET_NULL) class Meta: db_table = 'orders' Here is my queryset customer = Customer.objects.get(id='9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c') order = Order.objects.filter(product__name='', customer=customer.id) And here is the query result SELECT "orders"."id", "orders"."customer_id", "orders"."product_id" FROM "orders" INNER JOIN "products" ON ("orders"."product_id" = "products"."id") WHERE ("orders"."customer_id" = 9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c AND "products"."name" = ) But how can I make the query without where on the products ? so like this SELECT "orders"."id", "orders"."customer_id", "orders"."product_id" FROM "orders" INNER JOIN "products" ON ("orders"."product_id" = "products"."id") WHERE "orders"."customer_id" = 9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c But when I try tu use select_related customer = Customer.objects.get(id='9c2ed1c9-9dee-417c-bee6-1fd5ec3a500c') order = Order.objects.filter(customer__id=customer.id).select_related('product') The result of query become a left … -
Django & Python 3.7: ModuleNotFoundError: No module named '_ctypes'
I am busy with the Django Project Tutorial. I was by the part you get the write tests: https://docs.djangoproject.com/en/3.1/intro/tutorial05/#writing-our-first-test . But when I got by running the test, the fOllowing error came a long: 'ModuleNotFoundError: no module named '_ctypes''. I have tried to solve this error by trying the solutions who were brought in the following StackOverflow questions: Python3: ImportError: No module named '_ctypes' when using Value from module multiprocessing linux ModuleNotFoundError: No module named '_ctypes ModuleNotFoundError: No module named '_ctypes' when installing pip But it didn't work! Does someone know how to solve this error? -
No module found in Django Test
I have a Django app and I am writing tests. Since it's deployed on heroku with a PostgreSQL db, I created another db to run my tests. I did change my settings this way: if 'test' in sys.argv: #Configuration for test database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xx', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxx66667297357aca0e412f06891aed646', 'HOST': 'xx-xx-137-124-19.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'xx', } } } else: #Default configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd751emj1l26su7', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxxfdd17531f544d0c2805726d12a1b230cf9a0e', 'HOST': 'xxx-xx-137-124-19.eu-west-1.compute.amazonaws.com', 'PORT': 5432, 'TEST': { 'NAME': 'xx', } } } This is my application tree: To execute my tests I run: heroku run python trusty_monkey/manage.py test trusty_monkey/users/tests My test is running but I get this error: ModuleNotFoundError: No module named 'trusty_monkey/users/tests' What am I doing wrong? -
Django form creating new record instead of updating
I'm creating a user update form in my app. but every time when the form is submitted , it creates a new record and if you try submitting again will return Integrity Error(duplicate username that both are null). ERROR message: django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username forms.py: class UserChangeForm(forms.ModelForm): class Meta: model = User fields = ['email', 'first_name', 'last_name'] def __init__(self, username, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) self.username = username views.py: def profile(request): user = request.user if request.method == 'POST': user_form = UserChangeForm(user, request.POST) if user_form.is_valid(): user_form.save() messages.success(request, f'Your account has been updated!') return redirect('users:profile') else: email = request.user.email first_name = request.user.first_name last_name = request.user.last_name user_form = UserChangeForm(user, initial={ 'email': email, 'first_name': first_name, 'last_name': last_name }) context = { 'user_form': user_form, } return render(request, 'users/profile.html', context) -
What happens when Django Session timesout?
In my scenario the function which does some backend updates is called when request is submitted takes a lot of time to return the value and as a result the session times out. So my doubt is What happens in backend when session times out? Does the function that was running stops running immediately as session timesout? Will the data from django session table be removed? I don't know much about django sessions and reading online didn't gave much clarity on doubts. -
cannot connect django web application to sql server 2016
i am writing a django web application using mssql database. and i used 'DIRS': [os.path.join(BASE_DIR, 'templates')], in setting.py file. but after runserver i got this error that:NameError: name 'os' is not defined. so i tried to install os-sys. but it didn't work. heres part of error i get. i also use visual studio 2019 and Python 3.8.6rc1 and django 3.1.2 any idea how can i fix my code?? Getting requirements to build wheel ... done Installing backend dependencies ... error ERROR: Command errored out with exit status 1: command: 'c:\users\marie\appdata\local\programs\python\python38\python.exe' 'c:\users\marie\appdata\local\programs\python\python38\lib\site-packages\pip' install --ignore-installed --no-user --prefix 'C:\Users\Marie\AppData\Local\Temp\pip-build-env-15qobm6i\normal' --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'cymem<2.1.0,>=2.0.2' 'murmurhash<1.1.0,>=0.28.0' 'cython>=0.25' 'preshed<3.1.0,>=3.0.2' wheel 'thinc<7.2.0,>=7.1.1' cwd: None Complete output (215 lines): Collecting cymem<2.1.0,>=2.0.2 Using cached cymem-2.0.3-cp38-cp38-win_amd64.whl (33 kB) Collecting murmurhash<1.1.0,>=0.28.0 Using cached murmurhash-1.0.2-cp38-cp38-win_amd64.whl (20 kB) Collecting cython>=0.25 Using cached Cython-0.29.21-cp38-cp38-win_amd64.whl (1.7 MB) Collecting preshed<3.1.0,>=3.0.2 Using cached preshed-3.0.2-cp38-cp38-win_amd64.whl (115 kB) Collecting wheel Using cached wheel-0.35.1-py2.py3-none-any.whl (33 kB) Collecting thinc<7.2.0,>=7.1.1 Using cached thinc-7.1.1.tar.gz (1.9 MB) Collecting blis<0.5.0,>=0.4.0 Using cached blis-0.4.1-cp38-cp38-win_amd64.whl (5.0 MB) Collecting wasabi<1.1.0,>=0.0.9 Using cached wasabi-0.8.0-py3-none-any.whl (23 kB) Collecting srsly<1.1.0,>=0.0.6 Using cached srsly-1.0.2-cp38-cp38-win_amd64.whl (181 kB) Collecting numpy>=1.7.0 Using cached numpy-1.19.2-cp38-cp38-win_amd64.whl (13.0 MB) Collecting plac<1.0.0,>=0.9.6 Using cached plac-0.9.6-py2.py3-none-any.whl (20 kB) Collecting tqdm<5.0.0,>=4.10.0 Using cached tqdm-4.50.2-py2.py3-none-any.whl (70 kB) … -
How to use temp table count values into into the where query in Django Raw Sql?
I need to use raw sql in my django project. I'm using count command and then I associated it with as command like "the_count" but i got an error. The error like this, the_count does not exist. And my my code here, query = 'SELECT "auth_user"."id", (SELECT COUNT(*) FROM "my_app" WHERE (something)) AS "the_count" FROM "auth_user" WHERE ( "the_count" = 0)' User.objects.raw(query) Thank you for yours helps... -
Django Rest Framework media files fetching HTTP instead of HTTPS in production
Django rest framework is fetching "pp": "http://xyz/media/IMG_9579_CBgxVGX.JPG", instead of "pp": "https://xyz/media/IMG_9579_CBgxVGX.JPG", even after configuring nginx here is my nginx configuration server { listen 80; #listen 443 ssl default_server; #listen 443 ; #listen [::]:443 ; listen 443 ; server_name xyz 13.232.17.9; #proxy_set_header X-Forwarded-Proto https; #return 301 https://$host$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/ubuntu/ss42; } location /media { root /home/ubuntu/ss42; } location / { include proxy_params; proxy_set_header X-Forwarded-Proto https; proxy_pass http://unix/run/gunicorn.sock; #proxy_pass http://unix/run/gunicorn.sock; #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; #proxy_set_header Host $http_host; #proxy_redirect off; } } and my django settings where i have enabled ssl header SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True media MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") I have tried several possibilities added SECURE_SSL_REDIRECT=True but that gave 500 error while access server #return 301 https://$host$request_uri; added this line in nginx but that gave "to many redirects error " removed listen 80; and added just listen 443 ; this is actually gave 404 not found error in nginx i have no idea what exactly is wrong from my side i have tried all the possible ways as mentioned in the official documentation and various stackoverflow threads -
Facebook Messengerbot python ( The Callback URL or Verify Token couldn't be validated. Please verify the provided information or try again later.)
Am trying to implement facebook messenger chatbot in python. Am created One API in python below @api_view(['GET']) def verify(request): form_data = request.query_params mode = form_data.get('hub.mode') token = form_data.get('hub.verify_token') challenge = form_data.get('hub.challenge') if mode and token: if mode == 'subscribe' and token == "mytestingtoken": print("WEBHOOK_VERIFIED") return JsonResponse({"code":200,'message':challenge}) else: return JsonResponse({"code":403}) return JsonResponse({"code":200,'message':'test'}) am mapping the API URL into ngrok URL(https://55d71a8248be.ngrok.io) then am created a Facebook App and configured a webhook. here callback URL and Verify Token also setup. but finally I got Error Message The Callback URL or Verify Token couldn't be validated. Please verify the provided information or try again later. Am referred facebook document https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup -
qr url parameters using django
How to pass url parameters to function to generate qr code for current page? And this's my generate function: from django.shortcuts import render from qrcode import * data = None def home(request): global data if request.method == 'POST': data = request.POST['data'] img = make(data) img.save("static/image/test.png") else: pass return render(request,"home.html",{'data':data})