Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UserProfile add Post to Wishlist? error FoodListUser didn't return an HttpResponse object. It returned None instead
I got two related issue I guess. I tried to create a wishlist: When I clic the link to add Post (belongs to the main nutri app) to UserProfile whishlist. I got this : The view user.views.FoodListUser didn't return an HttpResponse object. It returned None instead user/models.py class UserProfile(models.Model): wishlist = models.ManyToManyField(Post, related_name='user_wishlist') ... user/views.py def FoodListUser(request, post_id): post = get_object_or_404(Post, pk=post_id) userprofile = get_object_or_404(UserProfile, user=request.user) if request.method == "POST": userprofile.wishlist.add(post) #request.user.userprofile.follow.add(pk) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_wishlist(self): return self.wishlist.count() user/urls.py path('wishlist/<int:post_id>/', FoodListUser, name="foodlist_user"), -
Django + Uvicorn + Gunicorn: object HttpResponse can't be used in 'await' expression
I'm getting this when running django + uvicorn + gunicorn on every request. It's my first time setting this up and it's not clear where things are going wrong, because runserver works fine. Traceback (most recent call last): File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/whitenoise/middleware.py", line 59, in __call__ response = self.get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 139, in __call__ return call_result.result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 204, in main_wrap result = await self.awaitable(*args, **kwargs) TypeError: object HttpResponse can't be used in 'await' expression -
Django doesn't render images
WebSite Admin Panel First of all sorry for bad english. But i cant see my images on my website. I can see titles descriptions. Can you help me. I checked page resources it links my images and there is no problem. thats exactly where my photos are page resources settings.py STATIC_URL = '/static/' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') template <ul class="slides-container"> {% for rs in sliderdata %} <li class="text-center"> <img src="{{ rs.image.url }}" alt=""> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="m-b-20"><strong>Hoşgeldiniz <br> Site İsmi</strong></h1> <p class="m-b-40">{{ rs.title}} <br> {{ rs.description }}</p> <p><a class="btn hvr-hover" href="#">İncele</a></p> </div> </div> </div> </li> {% endfor %} views.py def index(request): setting = Setting.objects.get(pk=1) sliderdata = Slider.objects.all()[:3] category = Category.objects.all() context={'setting':setting, 'page': 'home','category':category,'sliderdata':sliderdata} models.py class Slider(models.Model): Status = ( ('True', 'Evet'), ('False', 'Hayır'), ) title = models.CharField(max_length=150) description=models.CharField(max_length=255) image = models.ImageField(upload_to='images/', blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Django creates another media folder inside media folder
I'm a beginner with Django and that's exactly what it does. I do just as it was in the documentation but anyway maybe something went wrong? From admin-page I adding\setting-up a product and choosing the 'image', then when I'm saving it creating a thumbnail and trying to save in '/media/uploads/' but instead it's creating another 'media' folder and the image stored in '/media/media/uploads/img.png' when path on site is '/media/uploads/img.png'. Here is the code: /shop/settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # or even 'media/' /shop/urls.py: urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after that's added, then in my Product model I do: /apps/store/models.py: class Product(models.Model): ... image = models.ImageField(upload_to='media/uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='media/uploads/', blank=True, null=True) ... def save(self, *args, **kwargs): self.thumbnail = self.make_thumbnail(self.image) super().save(*args, **kwargs) @staticmethod def make_thumbnail(image, size=(512, 512)): if not image: return img = Image.open(image) if img.mode in ('RGBA',): # converting image to RGB if it's RGBA img.load() rgb_convert = Image.new('RGB', img.size, 0) rgb_convert.paste(img, mask=img.split()[3]) img = rgb_convert img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'PNG', quality=80) thumb = File(thumb_io, name=image.name) return thumb I tried to change 'upload_to' to 'uploads/' and then it stores files in the right direction but path to it on-site also changes to … -
Implementing a following system and fetching posts of people a user follows in django
I am designing a social media site and have a model of follower/following system that when a following relationship is made the feed will get all the posts by the followers of the user, I have tried to make the model for my user class and the post class as following: Class User(AbstractBaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=30) email = models.EmailField(max_length=30, unique=True) contact_no = models.CharField(max_length=15) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Post(models.Model): posted_by=models.ForeignKey(User,on_delete=models.CASCADE) date= models.DateField(auto_now=True) time=models.TimeField(auto_now=True) content=models.CharField(max_length=2000) media=models.ImageField(blank=True) and this is the model that establishes the relationship between two users. class Following(models.Model): user_id = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user_id= models.ForeignKey(User,related_name='followers',on_delete=models.CASCADE) class Meta: unique_together = ("user_id", "following_user_id") But when I try to combine things while calling upon the posts of the concerned user through this code class Feed(): def __init__(self,User): self.following=Following.objects.filter(user_id=User).values('following_user_id') def GetPosts(self): self.post=Post.objects.filter(posted_by__in=self.following) But this returns me an empty list even after creating the objects, If any of you guys could help me with it in anyway, I would really appreciate it. -
Django API: Revoke tokens after a certain amount of request
I am trying to code an API that would receive a string or a list of strings and return my model's predictions. I use token authentication for the ease of use, however, I don't understand/can't imagine how I can limit the amount of requests a user can make on a per month basis. Or give a limited amount of requests to an anonymous user. Should I create a custom permission class ? ### settings.py ## INSTALLED_APPS = [ # basics 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # API 'rest_framework', 'rest_framework.authtoken', # auth 'rest_framework_tracking', # logging ] ## views.py ## class MyAPIView(APIView, LoggingMixin): logging_methods = ['POST', 'PUT'] authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] renderer_classes = [BrowsableAPIRenderer, JSONRenderer, CSVRenderer] parser_classes = [JSONParser, MultiPartParser] def post(self, request, proba=False): query = request.POST.get('q') content = { 'result': "Model predictions." } return Response(content, status=status.HTTP_200_OK) -
How to convert an object in django rest framework to a hyperlink
Here is the result of my serializer model "saved_homes": [ { "id": 23, "saved_home": { "home_id": 1, "home_price": 120000, "home_type": "Flat", "virtual_tour_url": "https://www.youtube.com/watch?v=LnsIJcx6fqY", "hoa_dues": 1000, "address": "112 Salleydeen Street, Tema Community 25", "number_bedrooms": 4, "number_bathrooms": 3, "lot_size": 2400, "year_built": 2010, "describe_home": "A home full of the latest technology", "related_website": "https://www.youtube.com/watch?v=tkuqpsyktvA", "love_about_home": "The amount latest technology built in this house" } } ] so I am wondering, is they a way in django rest framework that I can make a reference to another api endpoint using saved_home id(home_id); So I want saved_homes to be something like this; "saved_homes": [ { "id": 23, "saved_home": { "http://localhost:8000/api/homes/1/" } } ], -
Unexpected format when passing a DateField straight to a template
I have a DateField on my model. And I'm passing the fields value straight into a DocxTemplate, where it comes out as "YYYY-mm-dd" format. I was wondering if there is a way of letting Django format the date so that it comes out in a localised format? In "models.py": class Bar(models.Model): date_fld = models.DateField() Generating the "docx": from app.models import Bar from django.shortcuts import get_object_or_404 from docxtpl import DocxTemplate ... bar = get_object_or_404(Bar, pk=1) tpl = DocxTemplate("tpl.docx") context = { 'foo': bar.date_fld, } tpl.render(context) tpl.save("result.docx") I know that I could use a function to convert the date to a string, but it doesn't seem like a Django way of doing things: def getDateString(date): return date.strftime('%d/%m/%Y') And then: context = { 'foo': getDateString(bar.date_fld), } -
Django Rest Framerowk setting user/owner to a ModelSerializer (Tweet)
I am new to DRF. While creating the twitter app I faced a problem with serializers. Since the user is required - I need somehow to pass the actual user to the TweetSerializer class. I have tried different methods that did not work. This is giving me an error owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) error image error image continued also i have tried to se the user by passing it tot he serializer constructor serializer = TweetSerializer(owner=request.user) also did not work class TweetSerializer(serializers.ModelSerializer): try: owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) except Exception as exception: print(exception) class Meta: model = Tweet fields = '__all__' read_only_fields = ['owner'] def validate(self, attrs): if len(attrs['content']) > MAX_TWEET_LENGTH: raise serializers.ValidationError("This tweet is too long") return attrs class Tweet(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey('auth.User', related_name='tweets', on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) class Meta: ordering = ['-id'] @api_view(['POST']) def tweet_create_view(request, *args, **kwargs): serializer = TweetSerializer(data=request.POST) user = request.user if serializer.is_valid(): serializer.save() else: print(serializer.errors) return JsonResponse({}, status=400) try: pass except Exception as e: print(str(e)) return JsonResponse({}, status=400, safe=False) return JsonResponse({}, status=201) -
Wishlist / Favourite list - django what's the best way to build it?
I was wondering what is the best way to build a favorite list (from Post) and display it on the User Profile? I got a UserProfile and a Post model. First solution create a new model: class favoriteList(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='user_favorite') favorite = models.ManyToManyField(Post,related_name='post_favorite') def __str__(self): return self.user.username Second solution build it from UserProfile model: class UserProfile(models.Model): favorite = models.ManyToManyField(Post, related_name='user_favorite') -
How to communicate from a webserver to a local device using UDP?
Here's the scenario: I have a webserver(django) hosted on the cloud, which needs to send some data to an android application (also developed by me) when some event occurs. I don't want to use polling using Http or other protocols from the android. What i want is the webserver to send the data via UDP (socket programming on both android and django). I have tested this by hosting the webserver on my local computer and providing the local IP of the android devices. It works perfectly. The scenario changes when the same server is hosted on the cloud as now, I don't know the public IP of the Android devices. WhatismyIp on google simply shows the public IP of the router which is not enough to route the packets to my local devices. Using a VPN and its managed IP works ofcourse, but is there a way to do this without a VPN? Any help will be appreciated. -
How to work with multiple server and databases in Django?
So I few data collection tasks that involves saving data on multiple servers. Could have saved data on a master server but I use Docker and background tasks to collect data and for some reason background tasks stops while saving data on master server. I have changed settings in postgres file and it can be accessed from different server. I gave up on master server eventually. Now I am accessing the second server using multiple database functionality in Django but it is kind of slow to fetch data from second server and then do operations on it. Is there any solution for faster operation Or a master server kind on thing? -
How can i add an image my homepage with django
First of all i gotta tell that sorry for bad english. Now i am explaining my problem. I ve been working on django for a while. In fact it is first time i used django. I want to get some images by using admin panel. As an example I got some products and i upload its title descriptions images etc on my admin panel. I used {if rs in products} to make it happened. All works right. Titles descriptions all are in my website. But i cant see any image. So i checked my page resources. And images are linked and all is true. (image src="uploads/images/x.jpg") thats where my images are but it doesnt render on my homepage. Thank you all -
Bokeh slider update on Django
I am able to display GeoJson data on a choropleth map using Bokeh on Django but unable to update the source dataframe based on slider input. Using CustomJS callbacks it seems to be possible to modify simple dataframe from within JS but how do we query a dataframe got from django models? Below is my code, any help would be greatly appreciated. #this is the view def dataviz(request): #load the shapefile for world map gdf = geopandas.read_file('/home/naveed/ne_50m_admin_0_countries/ne_50m_admin_0_countries.shp')[['ADMIN', 'ADM0_A3', 'geometry']] #Rename columns. gdf.columns = ['country', 'country_code', 'geometry'] #function to return geojson data based on date def geojson_data(day): if day == 10: day = datetime.date(2020,8,10) df = pandas.DataFrame.from_records(OxCases.objects.filter(count_date=day).values_list()) df = df[[1,4]] df.columns = ['confirmed_cases','country_code'] merged_df = gdf.merge(df,left_on='country_code', right_on='country_code') geojson_data = json.dumps(json.loads(merged_df.to_json())) return geojson_data p = figure(title='My geo map', plot_width=1150, plot_height=500, tools="wheel_zoom,pan", background_fill_color='#FFFFFF') p.toolbar.active_scroll = p.select_one(WheelZoomTool) p.toolbar_location = None p.xgrid.visible = False p.ygrid.visible = False hover = HoverTool(tooltips = [('','@country_code'),('','@confirmed_cases')], # callback = CustomJS(code = code_hover) ) p.add_tools(hover) palette = d3['Category20c'][12] # palette = brewer['BuGn'][9] #Reverse color order so that dark blue is highest obesity. palette = palette[::-1] #Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. color_mapper = LinearColorMapper(palette = palette) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=10,width = 20, … -
CKEditor deleting <span> in Django
I'm having a problem with CKeditor (with ckeditor_uploader) in Django, I looked everywhere, found a lot of answers but none of those worked. The solutions I found was inserting one of those to the config.js: CKEDITOR.editorConfig = function (config) { config.allowedContent = true; config.autoParagraph = false; config.extraAllowedContent = 'span(*)'; }; CKEDITOR.dtd.$removeEmpty.span = 0; CKEDITOR.dtd.$removeEmpty['span'] = false; Everytime I click out of source and go back, or save and go back, the span tag is gone: Also, this is what I have in my settings.py: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': [ 'Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': [ 'Styles', 'Format', … -
Facebook Link Sharing Issue
I have a single "share to facebook" link on my site using Django Social Share. The issue is that the link being posted to Facebook isn't being scraped - the image, the description, and the title are not populating. All OG meta tags are present and correct, so I checked the Facebook Sharing Debugger and it shows the following error: SSL Error Can't validate SSL Certificate. Either it is self-signed (which will cause browser warnings) or it is invalid. Curl Error Curl error: 60 (SSL_CACERT) The site's SSL cert is perfectly valid - no errors or warnings at all. I'm using LetsEncrypt on Apache with a Django app behind it through WSGI. No issues with any other social networks. An example of one of the links giving this error: https://www.netizen.net/news/post/2643/netizen-ranks-184-on-the-2020-inc-5000-list As you can see if you visit the page, there are no SSL errors. The same link is scraped just as expected on LinkedIn, Twitter, and elsewhere but FB seems to have this issue. -
Why do i keep getting this error even though there seems to not be anything wrong?
I keep getting an error that login.html cant be find in the folder that its supposed to be while it is literally there . directory error -
Unable to create a new object for many to many field in Django
I have 2 models (Order and order items)with many to many relation. However, the order item unable to create a new objects even I create a new Order. I will really appreciate for your help. models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.product_name}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user views.py def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.item_code = gen_item_code() order_item.save() messages.success(request, 'added to cart') return redirect('product_detail', slug=slug) else: order.items.add(order_item) messages.success(request, 'added to cart') return redirect('product_detail', slug=slug) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.success(request, 'added to cart') return redirect('product_detail', slug=slug) -
drf_yasg AttributeError: 'function' object has no attribute 'with_ui'
Trying to documenting API using drf_yasg according to their documentation but I got this error "AttributeError: 'function' object has no attribute 'with_ui'" here is my code in urls.py schema_view = get_schema_view( openapi.Info( title="Blog API", default_version='v1', description="A sample API for learning DRF", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="riajulkashem@gmail.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] -
My django smtp g-suite settings don't seem to be working
I am having issues connecting Django to google g-suite account: The settings are currently as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'noreply@mydomain.com' EMAIL_HOST_PASSWORD = '16CharacterAppPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER Setting I have tried: Note, comma separated the different settings I have tried in all possible combination EMAIL_HOST = 'smtp.gmail.com', 'smtp-relay.gmail.com', 'mail.mydomain.com' EMAIL_USE_TLS = True, False EMAIL_USE_SSL = False, True EMAIL_PORT = 587, 25, 465 EMAIL_HOST_USER = 'noreply@mydomain.com' EMAIL_HOST_PASSWORD = '16CharacterAppPassword', 'mynormalpassword' Other things I have tried: LessSecure settings: On/Off App Password: Tried 2 two different ones just incase the first one messed up Contact G-Suite support: They had a look at the settings and everything is fine from their end Tried CaptchaLink Tried verifying last login attempt as 'it was me' so it won't block the IP Tried the following tutorial: G-Suite Smtp More details if it might help: Server: Pythonanywhere Domain: Google registered domain Python: 3.8 Django: 3.1.1 django-allauth: 0.42.0 Error msg I get when trying to send an email: SMTPAuthenticationError: Username and Password not accepted learn more at ... Follow the link provided and tried all the trouble shoot methods. -
Django, How to repeat a single field multiple time
Imagine i have a class = SkillModel in model.py where can specify their skills, so a user can have multiple skills but i have single field in table ,,,so how can i repeat this to gain multiple values(skills) from user. here is have preference factors where user will put there preference such as hark working or any xyz so how can i made a model where can take multiple values ...like multiple skills SO HOW CAN I MODIFY THIS -
Django FormModel Validation
Background: Using the Django Admin framework, I'd like to run validation to make sure a record doesn't exist with the same values before saving. Using a form, I added a check in the "clean" method. That validation works exactly as I expect. I am successfully able to add NEW records and catch duplicates. THE PROBLEM: The form is also validating the TabularInlines. Since the "parent page" isn't changed/updated it's not being sent and it's not showing up in the "cleaned_data." Thus, when it's not checking to see if the parent record exists, it throws a KeyError. IE, "hey, you said to check these parent variables and they aren't in here, wth?" Question: Using forms, is there an elegant way to check the ModelAdmin (parent page) and the TabularInLines (child page) separately to avoid the key error? OR do I just hard code checks for the different chunks if they exist? Different forms for different inlines? I'm providing some PSEUDO CODE below that should help outline the issue. DISCLAIMER: The actual structure is more complicated. Yes, I realize in this EXAMPLE, there is a better way to handle this. However, I'm looking to solve the form validation issue. ########## # Models … -
2 POST query in same template Django and form does not show up in html file
I don t understand where is my 2 issues... first issue is that when I want to create a new entry on clicking on submit, it launches a search (q) variable (which is in layout.html below). so I have this error: MultiValueDictKeyError at /new 'q' on line 32 which is on views.py (in def search : title = request.POST['q']): from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.urls import reverse from . import util class NewEntryForm(forms.Form): title = forms.CharField(label="Entry title", widget=forms.TextInput(attrs={'class' : 'form-control col-md-8 col-lg-8'})) content = forms.CharField(widget=forms.Textarea(attrs={'class' : 'form-control col-md-8 col-lg-8', 'rows' : 10})) edit = forms.BooleanField(initial=False, widget=forms.HiddenInput(), required=False) def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def greet(request, title): if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) return render(request, "encyclopedia/404.html", { "entry": title}) def search(request): value = request.GET.get('q', '') if request.method == "POST": title = request.POST['q'] if util.get_entry(title): return render(request, "encyclopedia/wiki.html", { "entry": util.get_entry(title), "title": title}) if util.get_partial_entry(title): return render(request, "encyclopedia/search.html", { "entries": util.get_partial_entry(title) }) return render(request, "encyclopedia/404.html", { "entry": title}) return render(request,"encyclopedia/new.html") def new(request): if request.method == "POST": form1 = NewEntryForm(request.POST) if form1.is_valid(): title = form1.cleaned_data["title"] content = form1.cleaned_data["content"] if (util.get_entry(title) is None or form1.cleaned_data["edit"] is True): util.save_entry(title, … -
How to do a get request inside a Django Channels consumer connect method?
I'm trying to do a get request for a seperate django CRUD API app inside a Django Channels app connect method So inside the consumers.py I'm doing this class AssistantConsumer(AsyncWebsocketConsumer): async def connect(self): self.commands = requests.get('http://localhost:8000/api/commands') print(self.commands) Doing this results in the websocket getting stuck on WebSocket HANDSHAKING /ws/assistant/user/ [127.0.0.1:64374] Can anyone tell me why? The API is working on it's own, I'm posting to it from React, which also connects to the websocket. All that is working - I just need to fetch some data from the database in the consumer. Couldn't find anything anywhere about this situation. -
Sorting by Value of Object in Many to Many Field Django
I need some sorting help with django querysets that involve many to many relationships. I'm making a language-based conversation app and I've just finished writing a query that returns a queryset named possibleMatches containing the users someone might want to chat with. However, now I want to sort those users by the level of a specific language they have in their user languages table. I believe the solution lies in using Django's annotate() function for sorting querysets, but I've been having trouble finding the exact syntax to do it. I've also tried using filtered relations, but when running it, I got an error saying that filtered relations don't support nested conditions. Each user has an id and a list of user languages represented by a many to many field. Each user language corresponds to one user, one language, and one level. For clarity, here are my models: class CustomUser(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Language(models.Model): id = models.IntegerField(primary_key=True, choices=SUPPORTED_LANGUAGES) class UserLanguage(models.Model): language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='languages', on_delete=models.DO_NOTHING) level = models.IntegerField(choices=LANGUAGE_PROFICIENCIES, null=False, blank=False) Anyway, I want to sort the users in possibleMatches in ascending order based on their level of language 1. This is the code and …