Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Defining the place depending on the user django-channels
I'am making a chat app using django-channels. In my front-end chat I want one user on one side and the other user on the other side, I try something like this: {% for chat in object.chatmessage_set.all %} {% if chat.user == user.username %} <div class="msg right-msg" id="side"> <div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name" id="user">{{ chat.user }}</div> <div class="msg-info-time"></div> </div> <div class="msg-text" id="buttom">{{ chat.message }}</div> </div> </div> {% elif chat.user != user.username %} <div class="msg left-msg" id="side"> <div class="msg-img" style="background-image: url(https://image.flaticon.com/icons/svg/145/145867.svg)"></div> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name" id="user">{{ chat.user }}</div> <div class="msg-info-time"></div> </div> <div class="msg-text" id="buttom">{{ chat.message }}</div> </div> </div> {% endif %} {% endfor %} the class msg right-msg tells the right place and the class msg left-msg tells the other place, it seems it works, but not as I expected. At the end it looks like this: chat image does anybody know want can I do to classified the side depending on the user? -
How can I run a DLL inside the Docker Container?
I have a Django project that calls a DLL to make some calculations. However, I have some issues to resolve. My DLL is 32 bits. Linux container doesn't run DLL, because is a Windows creation. I don't have the possibility to convert the .dll to .so, because I don't have the source code. Are there any images to make this connection easier? connection? Thanks a lot! -
Django cors not enable?
Hi currently i'm trying to enable cors so i can allow my project frontend side(from another domain) to call my API(using django) The frontend side using React and axios to call the API(i have no knowledge about those forgive me if i got anything wrong) i also have little knowledge about CORS, i only know that it allow cross site domain resource sharing(like api) I'm using django-cors-headers package in my django i had set installed_app and middleware the same as the guide. After that i set whitelist for my frontend(they using ReactJS localhost to call the api): CORS_ORIGIN_WHITELIST = [ "http://localhost:3000" ] After that i restart my django server, the frontend calling my API and got the following error: Access to XMLHttpRequest at ‘my api url’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. I even set CORS_ORIGIN_ALLOW_ALL=True in the django settings but still got this error I haven't figure out what i'm … -
'AnonymousUser' object is not iterable on django
I have been trying to recreate a social network but in the process I have found that there is one big error when a user logs out which is a TypeError 'AnonymousUser' object is not iterable I have tried different ways of doing this like using if not request.user.is_authenticated(): or '@login_required' but nothing seems to work. I will like to make that if an unregistered user tries to see a page especifically the main view(home) the user should be redirected to the login page. views.py def home(request): following, created = Following.objects.get_or_create(user=request.user) user = Following.objects.get(user=request.user) followed_users = [i for i in user.followed.all()] followed_users.append(request.user) contents = Post.objects.filter(user__in = followed_users) context = { "contents": contents, } print("nice") return render(request, 'home.html', context) def profile(request, username=None): profile, created = Profile.objects.get_or_create(user=request.user) if username: post_owner = get_object_or_404(User, username=username) profile_bio = Profile.objects.filter(user_id=post_owner) user_posts = Post.objects.filter(user_id=post_owner) else: post_owner = request.user user_posts = Post.objects.filter(user=request.user) profile_bio = Profile.objetcs.filter(user=request.user) args1 = { 'post_owner': post_owner, 'user_posts': user_posts, 'profile_bio': profile_bio, } return render(request, 'profile.html', args1) urls.py urlpatterns = [ path('login', views.login, name='login'), path('register', views.register, name='register'), path('logout', views.logout, name='logout'), path('<username>/', views.profile, name='profile'), ] urlpatterns = [ path('', views.home, name='home'), ] If you have any questions or need to see more code please let me know;) -
Django voting system: Determine rank in appropriate way
I am trying to create a simple voting system but the problem is while displaying the rank of participants. For example if there are 20 participants and 10 have same votes then all of them are ranked same. All the participants have date_joined. So i want to re rank the participants having same number of votes based on date_joined. Any suggestions? Below is the model for participants: class participants(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) fullname = models.CharField(max_length =50) email = models.EmailField(max_length =50, default='') display_image = models.ImageField(upload_to=path_and_rename, max_length=500, help_text="Select display image") date_joined = models.DateTimeField(null=True, blank=True) dob = models.DateTimeField(null=True, blank=True) gender =models.CharField(max_length =10) competition_name = models.CharField(max_length =50,null=True, blank=True) featured = models.BooleanField(default=False) total_votes = models.IntegerField(default=0) unique_key = models.CharField(max_length =50, blank = True) Below is the view: def view_participant(request, participant_id): //i want to display the rank of the participant from participant_id. Also the id of next and previous ranked user id. // I have tried the following code: participant_data = participants.objects.get(id=participant_id) rank = participants.objects.filter(total_votes__gt=participant_data.total_votes).count() ranked_data =participants.objects.order_by('-total_votes') next_rank=0 prev_rank=0 if rank == 0: #checks if the participant is there is only one participants if rank ==0 and ranked_data.count() == 1: next_rank=0 prev_rank=0 #checks if the participant is first and there is more than one participants elif … -
how i can exclude a value from a django model?
I'm trying exclude a item from a watchlist but i don't work my code: def watchlist(request, page_id): items = Watchlist.objects.all() item = Auction_listings.objects.get(pk=page_id) if request.method == "POST": if item_id not in items: add = Watchlist(auction=item) add.save() else: remove = Watchlist.objects.get(auction=item) remove.delete() return render(request, "auctions/watchlist.html", { "items": Watchlist.objects.all() }) thank you in advanced -
Django doesn't collect JavaScript cookies
I've implemented a feature on my website, where guest users can add instrumentals they wish to purchase to a cart. I store the cart into cookies using the following code javascript code, where it is then retrieved using the Django framework to build the cart and display it in a template file. In previous implementations, this code has worked successfully, but recently has stopped collecting cookies for this feature and the cart is always empty. I checked, and JavaScript successfully writes the data into cookies. So it appears that the issue is whenever Django attempts to retrieve those cookies and gets nothing. What's even more bewildering is I implemented a similar feature for different services provided on the website, and this method works perfectly fine. views.py def cart(request): """Collect items from cookies and initialize variables""" try: cart = json.loads(request.COOKIES['cart']) price = json.loads(request.COOKIES['priceItems']) total = json.loads(request.COOKIES['total']) except: cart = {} price = {} total = {} cart.js function addCookieItem(beatId, action){ if (action == 'add'){ if (cart[beatId] == undefined){ cart[beatId] = {'beatId': beatId, 'quantity': 1} console.log("running for loop") } else{ alert("Beat already added") } } if(action == 'remove'){ cart[beatId]['quantity'] -= 1 if(cart[beatId]['quantity'] <= 0){ console.log('Item should be deleted') delete cart[beatId]; } console.log("item … -
Creating a pipeline that stores calculations as they happen and shares them across other users of that API?
I am working on my Data Engineering assignment and I'm fairly new to this topic. This is what I'm asked to create: A calculator API which stores calculations as they happen and shares those calculations with all users of that API. For example, user A sends a request to calculate "5 + 5", which returns a response of "10". This is then streamed to all connected users as "5 + 5 = 10". Now, user B calculates "3 4". This calculates to “12” and is streamed as "3 4 = 12" right after the prior calculation. User A sees this update immediately after user B posts it. Results should remain between sessions. Only show the last 10 calculations descending from most recent to oldest. What I know: TBH, I haven't been able to make much progress yet. From what I understand here is what I am gonna try: Create a simple calculator project using Python and Django. Next, somehow integrate Apache Kafka to stream the data across users and show the calculation history. I am not sure if I'm following the correct thought process, if someone has done something like this before then please let me know along with some … -
How to add link to a certain section in the rendered page in Django?
I render a page with additional key parameter added to the URL. For example: <form action="{% url 'Page' %}"> <select name="order"> <option value='up'> Up</option> <option value='down'> Down</option> </select> <button type="submit" >Submit</button> </form> And in the views.py file, I render the template file based on the key parameter appears in the request path_info. return render(request, 'index.html', context) Every time I render this template, the page always starts from the top, however, I want the rendered page to go to a certain section of the template file, like when you do tag in HTML to link between sections. <a href="#section">Link</a> It is possible for me to add different links to different section based on the key parameters in the URL (Like "/page/?order=up" go to id="up" and "/page/?order=down" go to id="down") so that the rendered page doesn't always start at the top? Thank you very much! -
class based view sum used for class based form validation (without forms.py)
I have been working on this one for a few days and have re-worked how i'd like to handle this functionality on my fantasy sports website: Objective: limit the number of players allowed on a fantasy owner's roster. Django out-of-the-box User = Owner # models.py class Player(models.Model): player_full = models.CharField(max_length=50) player_owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) image = models.ImageField(default='default_player.jpg', upload_to='player_pics') player_unit_value = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(1),]) And here is the class on views.py which i suppose is how the form is functioning. There is no forms.py in this area of my project. # views.py class PlayersUpdateView(LoginRequiredMixin, UpdateView, Player): model = Player fields = [] template_name = 'blog/player_form.html' # <app>/<model>_<viewtype>.html context_object_name = 'players' # this def makes sure only the post author can edit the post def test_func(self, **kwargs): # this makes sure it is the exact post we are updating player = self.get_object() if self.request.user == player.player_owner: return True return False def form_valid(self, form): form.instance.player_owner = self.request.user return super().form_valid(form) So I have the functionality working for "adding" a player to your roster where it verifies you're signed in then --when submitted-- the Player.player_owner field updates from None to the User. What I'd like it to do is --when a User tries … -
Using a OneToOneField on two external databases in Django
I'm using two databases in Django. I can easily join them in a SQL query by doing a JOIN ON. I'd like to do the same in my models to display the data in a table using django-tables2. However, when I try to do a OneToOneField relationship, I get this error: Field 'id' expected a number but got 'STEAM_1:0:1800'. Here is my code: **models.py** class Mostactive_awp(models.Model): _DATABASE = "mostactive_awp" playername = models.CharField(max_length=128) steamid = models.OneToOneField(Rank_awp, on_delete=models.DO_NOTHING, primary_key=True) total = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'mostactive' def __str__(self): return str(self.steamid) if self.steamid else '' class Rank_awp(models.Model): _DATABASE = "rank_awp" steam = models.CharField(unique=True, max_length=40, blank=True, null=True) name = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'rankme' def __str__(self): return str(self.steam) if self.steam else '' **views.py** def awp_stats(request, steamid): steamID = steamid user = Rank_awp.objects.get(steam=steamid) try: user_time = Mostactive_awp.objects.get(steamid=steamid) playtime = user_time.total hour = playtime//3600 minute = (playtime - hour*3600)//60 playtime = str(hour)+'h'+str(minute)+'m' except ObjectDoesNotExist: playtime = "Unknown" if user.deaths == 0: KD = str(round(user.kills, 2)) else: KD = str(round(user.kills/user.deaths, 2)) if user.rounds_ct + user.rounds_tr == 0: ADR = str(round(user.damage, 2)) else: ADR = str(round(user.damage/(user.rounds_ct + user.rounds_tr), 2)) if user.kills == 0: HS = str(round(0, 2)*100)+" %" … -
Can I deploy to Heroku without a Virtual Environment?
I followed a Django tutorial and the tutor didn't talk about the need for a Virtual Env. He deployed via Digital Ocean. I am trying to use Heroku but just found out that I ought to have activated a Virtual Env prior to the start of my Django project. Do I have to redo the Django project with a Vir Env or I can just go ahead to activate the Env and still deploy? -
Using manage.py commands on Google App Engine
I have deployed my first web application to google cloud and I have been having a lot of difficulties on my first trip. My main question (and reason for creating this post) is how to execute commands with manage.py like migrations? If that is not possible, how to handle migrations in the database? I'm having trouble working in the cloud, I'm using the Cloud SQL for Postgresql and App Engine Flexible environment, I would appreciate if the more experienced ones could help me. Thanks in advance. -
Django | Query filter returns more results than it should
I'm not sure entaily what I've done here but when I try to filter my database I get more results than I should. I'm trying to get a list of episodes that share the same season ID. Screen shot of Database There is 1 entry with the franchies_item_name_id = 67 which I filter for (Normally I'm getting this from something else but try to solve issue I've just entered the number). 3 entries with franchies_name_id = 2 which I don't care about in this instance. episodes_query = Episides.objects.filter(franchies_item_name_id=67) print(f'tv_item.id {tv_item.id}') print(f'episodes_query {episodes_query}') What is I get back is all the items that have franchies_name_id = 2 tv_item.id 67 episodes_query <QuerySet [<Episides: Episides object (3)>]> -
How to unittest "new style" Django middleware
I am learning how to unittest Django middleware. In the 'old style' Middleware, it was easy enough to load middleware using process_request() to test results. E.g. def test_session(self): request = self.factory.get('/') session_middleware = SessionMiddleware() session_middleware.process_request(request) // Do stuff However, in the 'new style' this does not exist. For example, how would I test the following example Django docs provide? class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) Using TimezoneMiddleware(request) will call the __init__ but not the __call__? -
Django's template `date:'Y-m-d H:i'` filter returns empty
In my template I have this: <td>{{ object.created_datetime|date:'Y-m-d H:i' }}</td> The object is a serialized json from djangorestframework. Without the |date:'Y-m-d H:i' it returns the full object 2020-07-16T21:15:36.608122Z but I'm trying to format the return object. For some reason when I use the filter it suddenly returns an empty string. What am I doing wrong? -
how can i filter eCommerce category and put links in Django navbar
dears. I wanna filter my product buy categories and show them into navbar dynamically. so this is my view in the base application def shop_page(request): context = { 'items': Item.objects.all() } return render(request, 'ecommerce/index_shop.html', context) and this is my base navbar.html <ul class="site-menu js-clone-nav d-none d-lg-block"> <li class="has-children active"> <a href="{% url 'ecommerce:shop_page'%}">Shop</a> <ul class="dropdown"> <!-- {%for item in category.item.all%} <li><a href="{{item.category.all}}">{{item.get_category_display}}</a></li> {%endfor%} --> <li><a href="#">Clothes and Uniforms</a></li> <li><a href="#">Phones & Accessories</a></li> <li><a href="#">Jewelry & Watches</a></li> <li><a href="#">Bags & Shoes</a></li> <li><a href="#">Beauty & Health, Hair</a></li> </ul> I wanna add automatically categories in the navbar and put filtering when user click on a category name so please check my project on github.com -
django admin - You don't have permission to view or edit anything
I have this error "You don't have permission to view or edit anything." when I access the Django admin panel. I am logged in but can not view or edit anything. I suspect it is becaue I added some web pages behind the admin url like so... app/admin.py from django.contrib import admin from django.contrib.admin import AdminSite from django.http import HttpResponse from .views import * from .models import Bot class MyAdminSite(AdminSite): def get_urls(self): from django.urls import path urls = super().get_urls() urls += [ path('admin/', admin.site.urls), path('c2/home/', self.admin_view(homeView.as_view()), name='home'), path('c2/cpanel/', self.admin_view(cpanelView.as_view()), name='cpanel'), path('c2/map/', self.admin_view(mapView.as_view()), name='map'), path('c2/stats/', self.admin_view(statsView.as_view()), name='stats'), ] return urls admin_site = MyAdminSite() admin.site.register(Bot) site/urls.py from django.contrib import admin from django.urls import path, include from api.admin import admin_site urlpatterns = [ path('admin/', admin_site.urls), path('', include('api.urls')), ] and ever since then, it has not been working. What do I need to do!?!? Thanks. -
Unable to set current user as author of post in Django
I'm trying to set the current logged in user as the author of the post of a form for uploading images. I'm following the advice that can be found in several public questions here in StackOverflow which is: storing the object coming from form.save() and then assign author value to it. Unfortunately, it does not seems to work at all for me, and I keep having no author assigned to the post. I've checked my code many times but I can't figure out what is wrong. Can someone please help me with this? my modes.py from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt from django.utils import timezone from django.urls import reverse from taggit.managers import TaggableManager class Image(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null="true", blank="true") name = models.TextField(max_length='20') image = models.ImageField(upload_to="images", verbose_name='Image', null="true") secondImage = models.ImageField(upload_to="detail", verbose_name='multiple-image', null="true") date_posted = models.DateTimeField(default=timezone.now) tags = TaggableManager() @property def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url @property def secondImage_url(self): if self.secondImage and hasattr(self.secondImage, 'url'): return self.secondImage.url def get_image_filename(instance, filename): title = instance.post.title slug = slugify(title) return "post_images/%s-%s" % (slug, filename) form.py from django import forms from .models import Image class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: … -
In Template - Make Value Of One Model Effect The Next Model
I have many modelss being displayed. Each model has a checkbox completed. Over time users will 'check' these checkboxes, and they will always do this sequentially (in order: one first, then two etc..). I want to change the class of the single model which comes after the last checked checkbox. For example, if there are 10 checkboxes and numbers 1, 2 and 3 are 'checked', I want to change the class of the 4th checkbox. model.py class MyModel(models.Model): completed = models.BooleanField(default=False) template.html # this changes the class of 'checked' checkboxes - not what I want {% for model in user.my_model.all %} {% if model.completed == True %} <div class="panel-heading highlight"> {% else %} <div class="panel-heading"> {% endif %} {% endfor %} Thank you. -
How to debug Django in VSCode with autoreload turned on
I set up debugging in VSCode (Django application) and it works great with the default setup. However, when debugging it seems automatic reloading is not possible. This is stated in the VSCode docs: Note that automatic reloading of Django apps is not possible while debugging. I was wondering if there's some way to make debugging (breakpoints etc.) work with reload enabled in Django. -
Python urls is showing an error could you help me to fix it?
Using the URLconf defined in todo.urls, Django tried these URL patterns, in this order: ^admin/ ^todoapp/ The empty path didn't match any of these. 404 error is showing when I run my code which you can find it below: This code is app url: from django.contrib import admin from django.conf.urls import url from todoapp import views urlpatterns = [ #url(r'^admin/', admin.site.urls), url(r'^$',views.index,name='index'), #todoapp/1 url(r'^(?P<task_id>[0-9]+)/$',views.detail, name='detail'), ] And it is the main url.py from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^todoapp/',include('todoapp.urls')), ] views.py is here: from django.shortcuts import render from django.http import HttpResponse from .models import Task from django.template import loader # Create your views here. def index(request): task_list = Task.objects.all() template = loader.get_template('todoapp/index.html') context = { 'task_list': task_list } return render(request, 'todoapp/index.html',context) def detail(request, task_id): task = Task.objects.get(pk=task_id) context = { 'task': task, } return render(request,'todoapp/detail.html',context) Why it is not working could not find a problem please help me to fix it. -
Graphene Django: I want to give multiple query variable in the mutation
I want to insert multiple data in the same mutation. Something like {"input":{"name": "test1", "companyId": "Q29tcGFueU5vZGU6Mg=="}, {"name": "test2", "companyId": "Q29tcGFueU5vZGU6Mg=="}} OR {"input": {["name": "test1", "companyId": "Q29tcGFueU5vZGU6Mg==","name": "test2", "companyId": "Q29tcGFueU5vZGU6Mg=="]} Schema: `class HolidayNameNode(DjangoObjectType): class Meta: model = HolidayNames interfaces = (relay.Node,) filter_fields = { 'name': ['icontains'], 'company_id': ['exact'], } Mutation class HolidayNameMutation(relay.ClientIDMutation): class Input: name = String() company_id = ID() holiday_name = Field(HolidayNameNode) @classmethod def mutate_and_get_payload(cls, root, info, **input): holiday_data = input holiday = HolidayNames(name=holiday_data['name'], company_id=from_global_id( holiday_data['company_id'])[1]) # making an instance of the model holiday.save() return cls(holiday) -
What is the correct way to create a django form?
Could you please advice on the best way to create a view, in the latest version of django? I am creating my views this way: def create_issue(request, chantier_id): issue = get_object_or_404(Issue, pk=issue_id) form = IssueForm(request.POST or None, request.FILES or None) if form.is_valid(): issue = form.save(commit=False) issue.save() return render(request, 'chantiers/detail.html', {'chantier': chantier}) context = { "form": form, } return render(request, 'chantiers/create_issue.html', context) and I know we can also use some View: class EstimateCreateView(AbstractSaleCreateUpdateMixin, generic.CreateView): template_name = "accounts/bill_create_or_update.html" model = Estimate form_class = EstimateForm formset_class = EstimateLineFormSet success_url = reverse_lazy("accounts:estimate-list") Many Thanks, -
How do I translate a PlaceholderField in Django CMS?
I would like to know how to translate text in a PlaceholderField in Django CMS. I have a model with a PlaceholderField. I want the cms user to be able to add images beneath a paragraph (can't do this with HTMLField in the admin). models.py class MyModel(models.Model): name = models.CharField(max_length=50) description = PlaceholderField('description') According to the django cms docs, Out of the box PlaceholderAdminMixin supports multiple languages and will display language tabs. admin.py from cms.admin.placeholderadmin import FrontendEditableAdminMixin, PlaceholderAdminMixin from django.contrib import admin from .models import MyModel class MyModelAdmin(FrontendEditableAdminMixin, PlaceholderAdminMixin, admin.ModelAdmin): pass admin.site.register(MyModel, MyModelAdmin) When I add text via the text plugin, I don't see any language tabs anywhere. The docs say something about overwriting change_form_template but that's after the mention of "and will display language tabs." I added the text in English, but when I switch the view to (in this case) Hebrew, I just see the same text plugin in the placeholder, in English. No language tabs that I can see. Anyone know how to translate text in a PlaceholderField?