Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set cronjobs to run everyday at 6am in django python
I am using Django-Crontabs to execute my function every day in the morning at 6 am. Here is my code for Django-Crontabs. Firstly I install Django-Crontabs with this command. pip3 install Django-crontab Settings.py INSTALLED_APPS = [ 'django_crontab', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp' ] CRONJOBS = [ ('* 6 * * *', 'myapp.cron.cronfunction') ] Here I have set the code to run every day at 6 AM. As per the following template. But it is not working. # Use the hash sign to prefix a comment # +---------------- minute (0 - 59) # | +------------- hour (0 - 23) # | | +---------- day of month (1 - 31) # | | | +------- month (1 - 12) # | | | | +---- day of week (0 - 7) (Sunday=0 or 7) # | | | | | # * * * * * command to be executed cron.py def cronfunction(): logger.warning("========== Run Starts ====") logger.warning("========== Run Ends ======") If I am running this function every 2 or 3 minutes then it works fine. ('*/2 * * * *', 'myapp.cron.cronfunction') How do I set my cronjob to run every day, Can anyone help? please. -
Generate media url from file path in Django
Let's say I have a function that writes a file to MEDIA_ROOT: def write_file(): with open(settings.MEDIA_ROOT / 'myfile.txt') as file: file.write('foobar') Now I want the absolute URL for this file as it is served from MEDIA_URL. Does Django have any utility function to do this for me? Or do I need to build it myself? Note this file is NOT associated with a model's FileField. -
Django ModeuleNotFoundError:
I have a Django project all set up, several apps that work fine but I have a folder with a few python files in it and on top of each file I have: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'My Project.settings') import django django.setup() If I take the file out of the folder then it works fine but if I try to run in while it is in the folder I get ModuleNotFoundError: No module named 'MyProject' The setup looks like this: MyProject MyProject settings.py More Apps Folder .py file that wont work in folder Is there something I need to edit in my import above to get the files to work while in the folder? Thank you for your help. -
How to create seperate login system for user and service provider in django
I have this fully functional user auth system User model: class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] User login view.I'm using JWT tokens stored in cookies. @api_view(['POST']) def LoginView(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.data = { 'jwt': token } return response In my React front-end i use react-auth-kit to check if the user if logged-in, and a userProfile component which is private as shown bellow. App.jsx const PrivateRoute = ({ Component }) => { const isAuthenticated = useIsAuthenticated(); const auth = isAuthenticated(); return auth ? <Component /> : <Navigate to="/login" />; }; <Router> <NavBar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/signup" element={<Signup />} /> <Route path="/profile" element={<PrivateRoute Component={UserProfile} />} /> <Footer /> </Router> The Login.jsx has a simple axios request axios .post( "/api/login", { email: values.email, password: values.password, }, { withCredentials: true, headers: … -
Django - HTMX: Render forms errors on modal and keep user on same page?
may you help me to understand how to use HTMX to render Form's Error messages when form is invalid? Docs says to use an attribute like : hx-post="{% url 'accounts:login' %}" but since I'm already using method=post should I still use it or delete it?I'd like users to stay on current page, however, right now when form is invalid users are redirected here: http://127.0.0.1:8000/accounts/login/ I didn't find a javascript function that opens the modal, so I think it is openened by some javascript implemented by bootstrap itself. this is my form: <form class="row my-4 align-items-center" method="post" action="{% url 'accounts:login' %}"> {% csrf_token %} {{ login_form.as_p }} {% if login_form.errors %} <ul> {% for field_errors in login_form.errors.values %} {% for error in field_errors %} <li>{{ error }}</li> {% endfor %} {% endfor %} </ul> {% endif %} <button type="submit" class="btn btn-primary">Ingresar</button> </form> ``` views: def login_view(request): if request.method == 'POST': login_form = LoginForm(request, data=request.POST) print("### Request is post") if login_form.is_valid(): print("### Request is VALID") username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') print("User name", username, "type: ", type(username)) print("Pass", password, "type: ", type(password)) user = authenticate(request, username=username, password=password) if user is not None: login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect("/") else: print(login_form.errors.as_data()) return JsonResponse({'success': False, … -
I can`t get access token using python sdk
I want to get access token with python. this is my code: def get_access_token(request): with open("path/to/private.key", "r") as f: RAS_PRIVATE_KEY = f.read() RAS_PRIVATE_KEY = RAS_PRIVATE_KEY.encode("ascii").decode("utf-8") api_client = ApiClient() host_name = "account-d.docusign.com" api_client.set_oauth_host_name(oauth_host_name=host_name) api_client.host = "https://account-d.docusign.com" token = api_client.request_jwt_user_token( client_id=settings.CLIENT_ID, user_id=settings.IMPERSONATED_USER_ID, oauth_host_name=host_name, private_key_bytes=RAS_PRIVATE_KEY, expires_in=3600, scopes=['signature', 'impersonation'] ) access_token = token.access_token return access_token But this error will occurre: docusign_esign.client.api_exception.ApiException: (444) Reason: Trace-Token: 2f2837d6-883f-4511-821f-09a8fee568ab Timestamp: Tue, 11 Apr 2023 23:34:09 GMT HTTP response headers: HTTPHeaderDict({'Content-Type': 'text/html', 'X-DocuSign-TraceToken': '2f2837d6-883f-4511-821f-09a8fee568ab', 'X-DocuSign-Node': 'DA2DFE4', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Referrer-Policy': 'no-referrer,strict-origin-when-cross-origin', 'X-Content-Type-Options': 'nosniff', 'Date': 'Tue, 11 Apr 2023 23:34:09 GMT', 'Content-Length': '54', 'Connection': 'close', 'Vary': 'Accept-Encoding'}) HTTP response body: b'The custom error module does not recognize this error.' Then I set oauth_host_name="https://demo.docusign.net/restapi" and another error will occurre: raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //demo.docusign.net/restapi/oauth/token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7ff19117d450>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) I don't know where the problem is.How I can solve it? -
"sudo: apt: command not found" when trying to deploy a django app with aws
I am trying to deploy my first Django app with AWS. I did everything until I reached the step of using sudo in the ec2 environmental setup. when I try to run sudo apt update I get sudo: apt: command not found. What can I do to solve this? -
Django custom AuthenticationForm fields
I want to use email and password fields only to authenticate, but it seems Django forces me to get username field. I tried to use username to login by adding username field to my User model, but it also ended with valid=Unknown I've read Django docs custom AuthenticationForm guide, and it ended without making custom AuthenticationForm ... view from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from .forms import UserLoginForm def login_view(request): if request.method == "POST": print(f"{request.POST=}") form = UserLoginForm(request.POST) print(f"{form=}") if form.is_valid(): print(" form valid") user = login(request, form) print(f" user login {user}") return redirect('home') else: form = UserLoginForm() return render(request, 'login.html', {'form': form}) UserLoginForm class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(AuthenticationForm, self).__init__(*args, **kwargs) class Meta: model = User fields = ('email', 'password', ) _base_attrs = { 'class': 'form-control', 'placeholder': '', } email = forms.EmailField( widget=forms.TextInput( attrs=_base_attrs ) ) password = forms.CharField( widget=forms.PasswordInput( attrs=_base_attrs ) ) User class User(AbstractBaseUser): email = models.EmailField( verbose_name="email", max_length=255, unique=True, ) is_leadership = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) register_date = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('password', ) email_backend class EmailBackend(BaseBackend): def authenticate(self, request, email=None, password=None): UserModel = get_user_model() user = UserModel.objects.get(email=email) if user.check_password(password): return user … -
how to pass context to filter in django
I want to access context in filter: NOT working example (showing what I want to get) {% for phone in person.communicator_set.all|phones %} {{ phone.number }} {% endfor %} templatetags/filters.py @register.filter(takes_context=True) def context_filter(context,queryset): return queryset.filter(validity_range__contains=context['context_date']) But this doesn't work... -
add field with select number of fields in forms
I want to build a reservation site and I'm zero in javascript! in the form I want to when user select number of rooms for counting of his select appear select fields (adult count , child count) and when select child number (child > 0 >0 ) a select filed appear and catch the age of child and do this for all the rooms too if child > 0 I'm using django plz help me for do this ! tnx! -
How do I send anchor tag links in email template in django
I am fairly new to Django and I use Django 4.2. I am trying to send email as rendered templates from views.py. The email sends but in all plain text. The link does not show in the email as a link, it shows as a plain html text. views.py send email function def sendActivationMail(user, request): current_site = get_current_site(request) email_subject = 'Verify your account' # context = { # 'click_action': 'showDomainLink', # } email_body = render_to_string( 'mail_temp/confirm_temp.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generator_token.make_token(user), }, # context ) email = EmailMessage( subject=email_subject, body=email_body, from_email=settings.EMAIL_HOST_USER, to=[user.email] ) email.content_subtype = 'html' email.send() def activate_token(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = Users.objects.get(pk=uid) except (ValueError, Users.DoesNotExist): user = None if user is not None and generator_token.check_token(user, token): user.is_email_verified = True user.save() messages.success(request, 'Successfully verified email') return redirect(reverse('login')) else: messages.error(request, 'Verification link was invalid') return redirect('index') email body template {% autoescape off %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> h1{ color: chocolate; } p{ font-size: 22px; } </style> </head> <body> <h1>Hey there, you are almost there!</h1> <p>Please click link to verify your account</p> <a class="underline" href="http://{{ domain }} {% url 'activate' uidb64=uid token=token%}">token</a> </body> </html> {% endautoescape %} I have … -
Why is my Django database flush command not working?
I've been chasing an error message regarding the python manage.py flush command for several weeks. When I issue the command and confirm the flush....I get... CommandError: Database my_app_db couldn't be flushed. Possible reasons: The database isn't running or isn't configured correctly. At least one of the expected database tables doesn't exist. The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. After chasing...upgrading various components...trying several different avenues....I still can't figure this out. -
Django: How to get tax amount for diffrent countries and multiply it by product price in django?
I am creating an ecommerce system where i would need to calculate taxes for diffrent countries during checkout. I have added a flat rate for the tax, but that is not how tax works, it need to be percentage based which i have done, but how do i know the country a user is about to order a product from and also get the tax amount for that country and do my basic calculation. please if you have done this before i would really appreciate any help as that would help me fix this issue. Right now, this is how i am performing the tax calculation with a fixed percentage for all users from all countries new_tax_amount = 0 tax_amount_by_percentage = 25 / 100 # 25% / 100 = 0.25 new_tax_amount += int(item['qty']) * float(tax_amount_by_percentage ) This works well for me, but i need to know how to get tax percentage based on the country the user is trying to order the product from -
Filter the swagger endpoints using tags when using drf_yasg in Django
When I generate the swagger ui using the default schema provided by documentation, it generates both api, api2 endpoints.I want to get only the api endpoints. I tried overriding the get_schema method as below but didn't work. class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, *args, **kwargs): """Generate a :class:`.Swagger` object with custom tags""" schema = super().get_schema(*args, **kwargs) schema.tags = [ { "name":"api" } ] return schema schema_view = get_schema_view( openapi.Info( title="API docs", default_version='v1', description="REST API", ), generator_class=CustomOpenAPISchemaGenerator, public=True, permission_classes=[permissions.AllowAny], ) Can someone give me a solution to get only the endpoints with tag of api? -
Forbidden (CSRF cookie not set.) - Django & React Web App
Any ideea why I get this error when trying to register an user? # views.py class SignupView(APIView): permission_classes = (permissions.AllowAny,) @method_decorator(csrf_protect) def post(self, request): try: data = request.data username = data.get('username') email = data.get('email') password = data.get('password') confirm_password = data.get('confirmPassword') if password != confirm_password: return Response({'error': 'Passwords do not match'}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response({'error': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create_user(username=username, password=password) user_profile = UserProfile(user=user, email=email) user_profile.save() return Response({'success': 'User created successfully'}, status=status.HTTP_201_CREATED) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) """ # settings.py Django settings for daweb_project project. Generated by 'django-admin startproject' using Django 4.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_i9x#yg#qq9!#&uw3e7$86&#w%g1t)%ft@ebfv3$ai*x+%a137' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'RealEstateApp.apps.RealestateappConfig' ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', … -
Is it possible to configure CSRF_TRUSTED_ORIGINS in Django 4 to allow access from any IP address?
I have found several posts regarding this but did not find what I need. I have upgraded Django from 2.x to 4.x for an Angular/Django web app which will be packaged and distributed to users that will install in different hosts and domains. MOST IMPORTANTLY, they would need to access the app from multiple locations on a serving port via browser (i.e. HTTP://whereAppIsInstalled:PORT). This used to work in Django 2 used to work without CSRF_TRUSTED_ORIGINS and with the settings below: ALLOWED_HOSTS = ['*',] CORS_ORIGIN_ALLOW_ALL = True All the answers say that I need to add those hosts, IPs, or subdomains to the CSRF_TRUSTED_ORIGINS list in settings.py. This works, but impractical in my case since I don't know all the hosts and IPs. I also noticed in Django documentation that we could add "HTTP://..." to CSRF_TRUSTED_ORIGINS, but this does not seem to work. I have to explicitly list all the IPs of the machines I am using to access the app. What should I do in this situation? How do I make sure that my app allows requests from all IPs? -
Djano: how to update order tracker model using Django?
I am trying to build an order tracker using django, to track the delivery status and location of a order made by a buyer. i have a model that look like this class OrderTracker(models.Model): order_item = models.ForeignKey('store.CartOrderItem', on_delete=models.SET_NULL, null=True, related_name="cartorderitem_tracker") status = models.CharField(max_length=5000, null=True, blank=True) location = models.CharField(max_length=5000, null=True, blank=True) activity = models.CharField(max_length=5000, null=True, blank=True) date= models.DateField(auto_now_add=True) def __str__(self): return self.order_item When an order gets placed, the status of the OrderTracker changes to shipping. How do i update the location with the current location where the order is crrently and also the activity (activity is something like: "Left Warehouse") Should this is updated manully by the vendor in the dashboard, or do i need like an API to implement this feature -
How to make an app that Django Rest Framework Filter and Django-Filter with ModelViewSet
When I use generics ListAPIView filter and order departs are working but if I use ModelViewSet it is not working. I added my code examples. How can I fix this problem? Thanks in advance class MovieViewSet(generics.ListAPIView): queryset = Movie.objects.all().order_by('movie_id') serializer_class = serializers.MovieDetailSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] authentication_classes = [authentication.BasicAuthentication] # FILTER AND ORDER: filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter] filterset_fields = ['category', 'director', 'country'] search_fields = ['category__name', 'director__name', 'name'] ordering_fields = ['production_year', 'imdb', 'duration'] It is working! class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all().order_by('movie_id') serializer_class = serializers.MovieDetailSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] authentication_classes = [authentication.BasicAuthentication] # FILTER AND ORDER: filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter] filterset_fields = ['category', 'director', 'country'] search_fields = ['category__name', 'director__name', 'name'] ordering_fields = ['production_year', 'imdb', 'duration'] def list(self, request, **kwargs): queryset = Movie.objects.all().order_by('name') serializer = MovieSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk): queryset = Movie.objects.all() movie = get_object_or_404(queryset, pk=pk) serializer = serializers.MovieDetailSerializer(movie) return Response(serializer.data) def has_permission(self, request, **kwargs): if request.METHOD in permissions.SAFE_METHODS: return True else: return request.user.is_staff() It is not working!! -
How to find duplicates of django model on two fields?
Consider this django model setup: from django.db import models class Foo(models.Model): field_foo = models.CharField(max_length=20, null=False, blank=False, unique=True,) class Bar(models.Model): field_bar = models.CharField(max_length=20, null=False, blank=False, unique=True,) class Foobar(models.Model): field_foo = models.ForeignKey(foo,on_delete=models.CASCADE) field_bar = models.ForeignKey(bar,on_delete=models.CASCADE) I want to look for two rows that have the same field_foo and field_bar values. I can do this manually, but I want to know if there is a feature of django that takes care of that. The way I do this now is: for f in Foo.objects.all(): for b in Bar.objects.all(): fb = Foobar.objects.filter(foo=f, bar=b) if len(fb)>2: something='do' -
Using Pagination with JsonResponse
I'm currently working on CS50W Network project which is basically a social media clone. I want to get different objects via a fetch API request, which is working fine. But after I implemented Pagination I get a 404 not found. When The DOM of the index page is loaded I call the getPosts function passing in 'all' as the username and currentPage document.addEventListener('DOMContentLoaded', function() { // By default, getPosts getPosts('all', currentPage); }); let currentPage = 1; const itemsPerPage = 10; function getPosts(username, page) { // Make a GET request to the API endpoint fetch(`/get_post/${username}/?page=${page}&per_page=${itemsPerPage}`) .then(response => response.json()) .then(data => displayPosts(data.data)) .catch(error => console.error(error)); } the path for the API is: path("get_post/<str:username>", views.get_post, name="all_posts"), My view function to get the requested Posts and handle the Pagination: @login_required def get_post(request, username): # get all posts if username == "all": posts = Post.objects.all() elif username == "following": posts = Post.objects.exclude(user=request.user) else: # get user user = User.objects.get(username=username) posts = Post.objects.filter(user=user) # change button color for post in posts: if post.likes.filter(id=request.user.id).exists(): post.liked = True post.save() else: post.liked = False post.save() # order posts in reverse chronological order posts = posts.order_by("-timestamp").all() # Get the current page number and the number of items per page from … -
Django not submitting and updating form data
I can't seem to figure out why Django is not submitting form data to update the user profile. Profile.html should be reflecting the newly updated input data (i.e., first_name, last_name) from Edit-profile.html. forms.py class EditUserProfile(forms.ModelForm): first_name = forms.CharField(max_length=50, required=False) last_name = forms.CharField(max_length=50, required=False) phone_number = forms.CharField(max_length=20, required=False) email = forms.EmailField(max_length=100, required=False) address = forms.CharField(max_length=150, required=False) city = forms.CharField(max_length=50, required=False) state = forms.CharField(max_length=50, required=False) zip_code = forms.CharField(max_length=10, required=False) username = forms.CharField(max_length=30, required=False) password = forms.CharField(widget=forms.PasswordInput, required=False) credit_card_number = forms.CharField(max_length=16, required=False) expiration_date = forms.DateField(required=False) cvv = forms.CharField(max_length=3, required=False) class Meta: model = User fields = ['first_name', 'last_name', 'phone_number', 'email', 'address', 'city', 'state', 'zip_code', 'username', 'password', 'credit_card_number', 'expiration_date', 'cvv'] def save(self, commit=True): user = super(EditUserProfile, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.city = self.cleaned_data['city'] user.state = self.cleaned_data['state'] user.zip_code = self.cleaned_data['zip_code'] user.username = self.cleaned_data['username'] user.password = self.cleaned_data['password'] user.credit_card_number = self.cleaned_data['credit_card_number'] user.expiration_date = self.cleaned_data['expiration_date'] user.cvv = self.cleaned_data['cvv'] if commit: user.save() return user views.py @login_required def edit_profile_page(request): form = EditUserProfile(initial={ 'first_name': request.user.first_name if hasattr(request.user, 'first_name') else '', 'last_name': request.user.last_name if hasattr(request.user, 'last_name') else '', 'phone_number': request.user.phone_number if hasattr(request.user, 'phone_number') else '', 'email': request.user.email if hasattr(request.user, 'email') else '', 'address': request.user.address if hasattr(request.user, 'address') else '', 'city': request.user.city if hasattr(request.user, 'city') else '', … -
Why does jQuery script behave differently in webpack?
As a learning exercise I'm attempting to reproduce a PHP\Symfony project in Python\Django. While working in Django I rewrote a jQuery script that I think is more effective than what I used in Symfony. Oddly, the identical script (i.e., copied & pasted) does not perform the same as in Django. Here's the script and an outline of what it does. The page on which the script operates contains two versions of the same table. One side is the food that is "assigned" to a meal. The other side has the food items available to be added to the meal. When the page is rendered it receives a JSON array of data attributes of foods already assigned to the meal. The script steps through the assigned table, hiding the table rows of food not assigned. It also hides the table rows of food items available that are assigned. The script: var rArray = JSON.parse($("#rte").text()); $("table#ready_foods tbody tr").each(function () { f = $(this).find('td').data('foodid'); if (rArray.indexOf(f) == -1) { $(this).toggle(); } else { $("table#meal_pantry tbody tr td[data-foodid=" + f + "]").parent().toggle(); // never executed } }); In Symfony, the else statement is never executed. So regardless of the foods already assisgned, that table's … -
How to print actual number when using Aggregate(Max()) in a Django query
I have the following query set: max_latitude = Model.objects.aggregate(Max('latitude')) When I print it, it returns {'latitude__max': 51.6639002} and not 51.6639002. This is causing a problem when I want to add the latitudes together to calculate an average latitude. If I do print(max_latitude.latitude) (field of Model object) I get the following: error:'dict' object has no attribute 'latitude' How can I extract the actual number given from the queryset? -
How to use django channel to create a game lobby and matchmaking
I am using django channels to create a 2-player game like Tic Tac Toe or checkers. My main issue is how I can preserve the state of the players that joined the lobby waiting to be paired. Would this be something I need to do in the connect method in the channel consumer? If not what if the approach here? -
Download an xlrd book as an excel file throught a django view
I need to download an excel file generated in memory using the xlrd library thought a django view as a direct download. I'm trying the following but I don't know how to convert the book object into something I can include in the HttpResponse from django.http import HttpResponse from xlrd import Book def my view: ... book: Book = <CREATED WITH XLRD> response = HttpResponse(book, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="file.xls"' return response