Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django orm , django models and F
I have models Class Invoice(): Class Entry(): Class InternalEntry(): invoice = models.ForeignKey(InternalInvoice) entry = models.ForeignKey(Entry) I need queryset to find entries which are not recorded as internal entry -
Django render page with context does not work
I like to re-render my page, after a document was uploaded using Djanog. I like to change context['FileName'] = 'Test' to context['FileName'] = 'Test2' in the HTML page. But it does not work and I am at a loss as to what I am doing wrong here. views.py def UploadView (request): context = {} #Generate Language Selection **context['FileName'] = 'Test'** if request.method == "POST": if not(request.FILES=={}): date_time = datetime.datetime.now() date_time = date_time.strftime('%Y%m%d_%H_%M') #uploaded_file = request.FILES["uploaded_file"] uploaded_file = request.FILES.get('file') document = Document( file_title = request.user.user_unique_key, uploaded_file = uploaded_file, date_time = date_time, ) document.save() file_path = document.uploaded_file.file.name file_name = uploaded_file.name **context['FileName']='Test2';** return render(request,"UPLOAD.html",context) return render(request, "UPLOAD.html", context) HTML <h6><font color="red">{{FileName}}</font></h6> -
Not able to construct innnerhtml in django html templates using ( for loop ) from file static/javascript/main.js
This HTML template I had code in Django templates and linked javascript from static files I am not able to use (for loop) of javascript to insert innerhtml in django html templates to add table i had written. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Split Webapp</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"> </head> <body> <div class="mb-3 row"> <label for="pass1" class="col-sm-2 col-form-label">SPLIT IN:</label> <div class="col-sm-2"> <input id="payees" type="number" min=0 max=100> <button type="button" class="btn btn-info" onclick="myfunction()" id="payeesbtn">ADD</button> <div class="container my-3" id="addpayees"> </div> </div> </div> <script src="{% static 'javascript/main.js' %}" type="text/javascript"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"> </script> </body> </html> **This is javascript in static folder ** console.log("javascript is working"); function myfunction() { let add_payee = document.getElementById("payees").value; let add_payee_column = document.getElementById("addpayees"); for (let i = 0; i < add_payee; i++) { console.log("working"); add_payee_column.innerHTML += ` <div class="container my-3"> <h5>payee ${add_payee} </h5> <table> <tr> <th>Name:</th> <td><input type="text"></td> </tr> <tr> <th>Mobile:</th> <td><input type="text"></td> </tr> </table> </div>`; }; }; -
foreign key error While submitting the forms
I had created a model and it contain foreign key fields also , but while I try to submit it shows error by saying like number cannot assign to the field where foriegn key is assigned. How can I upload as name . Error picture like below picture model.py class UserReg(models.Model): username=models.ForeignKey(settings.AUTH_USER_MODEL,default=1,null=True,on_delete=models.CASCADE) Name=models.CharField(max_length=200) Date_of_Birth=models.DateField() Age=models.IntegerField() Gender=models.CharField(max_length=200, choices=GenderChoice) Phone_no=models.IntegerField() Mail=models.EmailField(unique=True) Address=models.TextField(max_length=700) District=models.ForeignKey(District,on_delete=models.CASCADE) Branch=models.ForeignKey(Branch,on_delete=models.CASCADE) Account_Type=models.CharField(max_length=200,choices=AccType) Materials=models.ManyToManyField(Materials) class District(models.Model): name=models.CharField(max_length=200) Views.py def reg(request): form = Userform(request.POST or None) if request.method == 'POST': username=request.POST.get('username') Name=request.POST.get('Name') Date_of_Birth = request.POST.get('Date_of_Birth') Age = request.POST.get('Age') Gender = request.POST.get('Gender') Phone_no = request.POST.get('Phone_no') Mail = request.POST.get('Mail') Address = request.POST.get('Address') District = request.POST.get('District') Branch = request.POST.get('Branch') Account_Type = request.POST.get('Account_Type') Materials = request.POST.get('Materials') obj=UserReg(username=username,Name=Name,Date_of_Birth=Date_of_Birth,Age=Age,Gender=Gender, Phone_no=Phone_no,Mail=Mail,Address=Address,District=District,Branch=Branch,Account_Type=Account_Type,Materials=Materials) obj.save() return redirect('/') return render(request,'registration.html',{'form':form}) -
Python Websockets handles one time use only
I want to make a python code that browsers can connect to get a video stream. Problem is that my python code handles only one time use, meaning if you open the browser it will connect to that websocket correctly, but if you refresh the page, or another client want to access a stream from in parallel it won't happen saying the port is being used (this error is server side) My code: import asyncio import websockets import cv2 import os import signal async def time1(websocket, path): while True: vid = cv2.VideoCapture('V_DRONE_097.mp4') vid.set(cv2.CAP_PROP_FPS,24) try: #v = VideoStreamWidget() #v.ops() while(vid.isOpened()): img, frame = vid.read() #frame = cv2.resize(frame, (640, 480)) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 65] man = cv2.imencode('.jpg', frame, encode_param)[1] #sender(man) #print(len(man.tobytes())) #cv2.imshow('img',man) await websocket.send(man.tobytes()) except : pass async def main(): loop = asyncio.get_running_loop() stop = loop.create_future() #loop.add_signal_handler(signal.SIGTERM, stop.set_result, None) port = int(os.environ.get("PORT", "8585")) global stop1 async with websockets.serve(time1, "", port): await stop stop1 = False ''' async def main(): async with websockets.serve(time1, "localhost", 8585): await asyncio.Future() # run forever asyncio.run(main()) ''' if __name__ == "__main__": while True: asyncio.run(main()) I want the server to keep working even if the client (browser) refreshes the page or close it and comeback later. This is the … -
Django create user Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead
I am using the Django default User model to do user registration. When I was trying to create a user I got this error message. Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead. # views.py from django.contrib.auth.models import User from rest_framework import viewsets from app.serializers import UserSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' extra_kwargs = {'password': {'write_only': True, 'required': False}} def create(self, validated_data): print(validated_data) user = User.objects.create_user(**validated_data) return user # urls.py from django.urls import path, include from rest_framework import routers from app import views from rest_framework.authtoken.views import obtain_auth_token router = routers.SimpleRouter() router.register(r'users', views.UserViewSet) urlpatterns = [ path('auth/', obtain_auth_token), ] urlpatterns += router.urls I only insert the user record, there is no foreign table or many-to-many relationship. Not sure why the system throws this error. Attached with the postman screenshot. -
Cross-database relationships in Django with MySQL
Is there a primer on how to develop systems that segregate auth information from other information across multiple databases using Django without foregoing FK to User in another db? Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database. Django - Cross-database relations -
Merging Django-CMS Edit and Publish Mode created two different Database entries with the same values
My CTO asked me to fix an "issue." Apparently, whenever I add any plugin in the locally run DRF-based Django CMS project, it creates two database entries. One for edit mode, and the other when I hit publish. My CTO asked to find if there were any way to dynamically merge the edit mode entry with the merge mode and vice versa when switching between those modes. Our website is very heavy. But is doing this even necessary for Django-CMS? Here is the model.py code for an example plugin. Models.py: class TechnologyVideo(ck_CMSPlugin): Video_thumb = models.ImageField(upload_to="technology_video", null=True, blank=True) video_url = models.URLField(help_text='Please enter your video url', validators=[URLValidator], null=True) # video_title = models.CharField(max_length=100, blank=True, null=True, ) # video_description = HTMLField(null=True, blank=True, configuration="VIDEO_POST_TEXT_CKEDITOR") class Meta: verbose_name = "Technology Video Model" def __unicode__(self): return f'{self.Video_thumb}' cms_plugins.py: class TechnologyVideoPlugin(CMSPluginBase): model = TechnologyVideo name = 'Technology Video Plugin' render_template = 'technology_video.html' def render(self, context, instance, placeholder): context.update({ 'Video_thumb': instance.Video_thumb, 'video_url': instance.video_url, }) context = super(TechnologyVideoPlugin, self).render(context, instance, placeholder) return context plugin_pool.register_plugin(TechnologyVideoPlugin) -
How to solve the problem of widgets.py on Heroku?
I just tried to push my django project to heroku but failed. When I tried to run "git push heroku master", it's rejected. And then I followed the instruction that asked me to set the variable "DISABLE_COLLECTSTATIC" to 1. After that I tried to push again and succeed. But when I run "heroku run python manage.py migrate", I got this: File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/app/.heroku/python/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 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 4, in <module> from django.contrib.admin.filters import ( File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/filters.py", line 10, in <module> from django.contrib.admin.options import IncorrectLookupParameters File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/options.py", line 12, in <module> from django.contrib.admin import helpers, widgets File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/widgets.py", line 151 '%s=%s' % (k, v) for k, v … -
Calling Channels AsyncWebCoscketConsumer function from Signals Receiver doesn't work
Firstly, here's the code. I have checked it now I don't know how many times for any errors, and debugged step by step to find out why the function isn't called. # signals.py @receiver(post_save, sender=Ticket) def new_ticket(sender, instance, created, **kwargs): print("in receiver") if created: print("in created") channel_layer = get_channel_layer() print(channel_layer) async_to_sync(channel_layer.group_send( 'tickets_updates_group', { 'type': 'new_ticket', 'subject': "from receiver" })) print("after async_to_sync") All the print statements are always being called. # consumers.py class Tickets(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('tickets_updates_group', self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard('tickets_updates_group', self.channel_name) await self.close() async def new_ticket(self, event): print('in consumer.new_ticket') subject = event['subject'] print("subject: " + subject) await self.send(text_data=json.dumps({ 'subject': subject })) print("after send") Here, the new_ticket function is never being called, none of the print statements are being executed and my webpage isn't updated (as opposed to putting the group_send code in the connect funciton of the consumer class. I know that the problem isn't syntax, because if I add receiver's code to the consumers connect function, the new_ticket function is always being called without a problem (after replacing async_to_sync with await. I have seen all the possible working examples out there and I cannot seem to figure out why for the life … -
Product matching query does not exist
need help with following Error: DoesNotExist at /sales_data/sales_data_import Product matching query does not exist. I have two models below, SalesData gets product name from Product. And I am trying to import csv with sales data to SalesData module through function, but it does not work. And I am sure that all the products names in imported csv are included in model Product, so do not understand whey there is DoesNotExists Error. Models.py: class Product(models.Model): name = models.CharField("Product", max_length=150) def __str__(self): return f"{self.name}" class SalesData(models.Model): date = models.DateField("Date", null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True) quantity = models.IntegerField("Quantity", null=True, blank=True) @classmethod def create_from_csv_line(cls, line): sd = SalesData() entry1 = line["Date"] entry2 = datetime.strptime(entry1,'%d.%m.%Y %H:%M') date = entry2.strftime('%Y-%m-%d') sd.date = date status = str(line["State"]) sd.status = status curr = str(line["Currency"]) sd.product = Product.objects.get(name=str(line["Items"])) sd.quantity = int(line["Item quantity"]) sales = float(line["Subtotal"]) if curr == "CZK": sd.sales = sales * 100/(100+VAT) else: sd.sales = c.convert(curr, "CZK", sales, entry2) * 100/(100+VAT) if status == "fulfilled": sd.save() Views.py: class SalesDataImportView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "sales_data/sales_data_import.html" form_class = SalesDataForm def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: SalesDataForm = SalesDataForm(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file … -
Model property data with many-to-many relationship type is not displayed. Where is the mistake?
When using this code, it gives the following error: genres = GamesGenres.objects.annotate(Count('games')) Cannot resolve keyword 'games' into field. Choices are: games_genres, id, name, slug If you use the options above, then the "genre" property of the "Games" model is not displayed in the browser in the sidebar area, as intended. I want the sitebar to display a list of game genres by which you can filter and select the genre of interest. models.py class Games(models.Model): name = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique=True, db_index=True) content = models.TextField() photo = models.ImageField(upload_to="games/%Y/%m/%d/") release_date = models.DateField() developer = models.CharField(max_length=255) publisher = models.CharField(max_length=255) trailer = models.URLField() genre = models.ManyToManyField("GamesGenres", related_name="games_genres") def __str__(self): return self.name def get_absolute_url(self): return reverse("show_games", kwargs={"games_slug": self.slug}) class GamesGenres(models.Model): name = models.CharField(max_length=80) slug = models.CharField(max_length=255, unique=True, db_index=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("genres", kwargs={"genre_slug": self.slug}) views.py class GamesList(GamesMixin, ListView): model = Games template_name = "main_app/games.html" context_object_name = "games" def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title="Games") return dict(list(context.items()) + list(c_def.items())) class ShowGamesGenres(GamesMixin, ListView): model = GamesGenres template_name = "main_app/games.html" context_object_name = "games" allow_empty = False def get_queryset(self): return Games.objects.filter(genre__slug=self.kwargs["genre_slug"]).select_related('genre') def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title=str(context["games"][0].genre), genre_selected=context["games"][0].genre_id) return dict(list(context.items()) + list(c_def.items())) utils.py class … -
Django alias for static file path
I have a Django 4.1 project and want to make an alias to the directory with static files. So, in settings.py I have STATIC_URL = "static/" All my static files are in the example.com/static/.... I want to make a shortcut to one of directories of static files. For example example.com/magic/... should be the same as example.com/static/physics/.... That shoudn't be a redirect, because if it is a redirect, I won't be able to download file using curl without any special options. How can I do this? Maybe with some special paths in urls.py? -
POST Method missing in 'Allowed' Django rest framework
This is what is showing when I go the rest framework page in my web browser Allow: GET, HEAD, OPTIONS My model.py is as follows: class Note(models.Model): title = models.CharField(max_length=120) description = models.CharField(max_length=600) def __str__(self): return self.title These are my serializers.py : class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note fields = '__all__' Lastly these are my views class NotesViewset(viewsets.ModelViewSet): serializer_class = NoteSerializer queryset = Note.objects.all() -
How are the names of model items not showing up in DJango Admin?
I'm building a website using python and Django, but when I looked in the admin, the names of the model items aren't showing up. So, the objects that I am building in the admin aren't showing their names. admin.py: from .models import Article, Author # Register your models here. @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['title', 'main_txt', 'date_of_publication'] list_display_links = None list_editable = ['title', 'main_txt'] def __str__(self): return self.title @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'join_date', 'email', 'phone_num'] list_display_links = ['join_date'] list_editable = ['email', 'phone_num', ] def __str__(self): return f"{self.first_name} {self.last_name[0]}" models.py: # Create your models here. class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField() email = models.CharField(max_length=300) phone_num = models.CharField(max_length=15) join_date = models.DateField() participated_art = models.ManyToManyField('Article', blank=True) class Article(models.Model): title = models.CharField(max_length=500) date_of_publication = models.DateField() creaters = models.ManyToManyField('Author', blank=False) main_txt = models.TextField() notes = models.TextField() -
ValueError: The 'main_image' attribute has no file associated with it. on Django tests
I'm doing a test and I don't understand why this error is raised The test: def test_show_one_blog(self): blog0 = Blog.objects.create(name="American persuit", content="I don't know") url = self.client.get(reverse(viewname="blogs:blog_view", kwargs={"pk": 1})) self.assertEqual(url.status_code, 200) self.assertContains(url, text="American persuit") self.assertContains(url, "I don't know") self.assertContains(url, '2022-8-20') The model: class Blog(models.Model): name = models.CharField(max_length=140, blank=False, null=False) content = models.TextField(max_length=700, blank=False, null=False) pub_date = models.DateField(default=timezone.now(), blank=False, null=False) main_image = models.ImageField(null=True, blank=True) def __str__(self) -> str: return self.name the error: the error -
Fetch API does not fire at its position, though async await method is used
I am stuck on a problem for last few day. Let me explain the problem. I am just learning the react and Django rest framework. So as a first project, I have chosen todo application with JWT authentication. On the frontend part of the project, on of my function is not working properly. I made a function call getTokenFromRefreshToken to fetch the access when it is expires token through the saved refresh token as a cookie. The function is something like this : const getTokenFromRefreshToken = async (token) => { console.log("getTokenFromRefreshToken starts."); console.log("the token to refetch is : " + token); console.log("refetch the token"); const options = { method: 'POST', body: `{"refresh":"${token}"}`, headers: { 'Content-Type': 'application/json' }, }; await fetch('http://127.0.0.1:8000/api/token/refresh/', options) .then(response => response.json()) .then(response => { console.log("We get the response from getTokenFromRefreshToken"); console.log("Set the token variable"); setToken(response.access); console.log("Set the refreshToken variable"); setRefreshToken(response.refresh); console.log("Set the token cookie"); setCookie('token', response.access); console.log("Set the refreshToken variable"); setCookie('refreshToken', response.refresh); }) .catch(err => console.error(err)); console.log("getTokenFromRefreshToken ends."); } Now when I call the function it does not complete itself after console.log("refetch the token"); this line and finally it is completed after all the other process completed and all the components are rendered. That's why my token … -
Django Class Media js Refused to execute script from because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
when importing a local js file to add javascript functionalities to admin, you may face this error: Refused to execute script from 'http://localhost:8080/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. -
Django - form making one parent object and multiple child objects
I'm trying to make a Django model based form which will allow to create two models which one will be passed as a foreign key to second one. models.py class Recipe(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=200) quantity = models.CharField(max_length=200) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return self.name forms class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name'] and views.py ---- here is the problem def new_recipe_create_view(request, *args, **kwargs): context = {} created_recipe = None form = RecipeForm() if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): print("recipe successfully created") form.save() name = form.data['name'] created_recipe = Recipe.objects.filter(name=name).last() #new recipe is being made correctly IngredientFormSet = inlineformset_factory(Recipe, Ingredient, fields=('name', 'quantity'), extra=3, max_num=10, labels = { 'name': (''), 'quantity': (''), }) if request.method == 'POST': formset = IngredientFormSet(request.POST, instance=created_recipe) if formset.is_valid(): formset.save() else: print("formset is not valid") # <------------------------------------------ else: formset = IngredientFormSet( instance=created_recipe) if form.is_valid() and formset.is_valid(): return redirect('index') context['formset'] = formset context['form'] = form return render(request, 'recipes/create_recipe.html', context) part with inlineformset_factory, I made following docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets chapter: Using an inline formset in a view but it does not work --> formset.is_valid() is … -
KeyError when importing config.ini file into Management Command folder and running manage.py (Django)
I have the follow structure. members ├── management │ │── __init__.py │ │── commands │ │── active.py │── whatsapp.py │── config.ini I am trying to run a whatsapp api and I have all my authentication data stored in a config.ini file. However, when I run python manage.py active I get the following error message. C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym>python manage.py active Traceback (most recent call last): File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\manage.py", line 22, in <module> main() File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\members\management\commands\active.py", line 20, in handle msg = WhatsApp(name, phone, date) File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\members\management\commands\whatsapp.py", line 14, in __init__ self.authorization = self.config['Auth']['Authorization'] File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\configparser.py", line 964, in __getitem__ raise KeyError(key) KeyError: 'Auth' The code works fine if I move it to a separate folder and run the whatsapp.py file directly. active.py file from turtle import update from django.core.management.base import BaseCommand, CommandError from members.models import ActiveMember from datetime import datetime, timedelta from .whatsapp import WhatsApp class Command(BaseCommand): help = 'Deactivate expired memberships!' def handle(self, *args, … -
in _validate_username AttributeError: 'Manager' object has no attribute 'get_by_natural_key' error
model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import UserAccountManager class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=255, unique=True, # null=False, # blank=False, verbose_name="email", ) name = models.CharField(max_length=255) is_active=models.BooleanField( default=True, ) is_staff=models.BooleanField( default=False, ) is_admin=models.BooleanField( default=False, ) created_at=models.DateTimeField(auto_now_add=True) objects: UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email managers.py ''' from django.contrib.auth.models import BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('Users must have an email address') email=self.normalize_email(email) email = email.lower() user = self.model( email=email, name=name ) user.set_password(password) user.save(using=self._db) return user def create_admin(self, email, name, password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user(email, name, password) user.is_admin = True user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user(email, name, password) user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user ''' -
I want to group an entity based on one foreign key relation in rest django
I have two model here and records are related to employee class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) site = models.CharField(max_length=100) wage = models.DecimalField(max_digits=4, decimal_places=0, default=0) class Record(models.Model): employee = models.ForeignKey(Employee, related_name='employee', on_delete=models.DO_NOTHING) date = models.DateField() cash = models.DecimalField(max_digits=4, decimal_places=0, default=0) I would like to generate a which list all records of each employees Something like below { "id": 1, "name": "John Doe", "position": "manager", "Records": [ { "date": "2020-12-09T18:30:00.000Z", "cash": 888 }, { "date": "2020-10-10T18:30:00.000Z", "cash": 999 } ] } Please help me to write the serialiser and view set for my above requirement. -
I'm Unable to setup all the configuration for using django-smart-selects
i'm unable to setup all the things require for using ChainedForeignKey from smart_selects like what to add in urls.py and in settings.py and in models.py and etc ... please anyone who can help me in this .. -
Django suddenly raises `OSError: [Errno 22] Invalid argument` and dev server doesn't work anymore
I made some changes to a html file and suddenly my django app stopped loading with the dev server returning OSError: [Errno 22] Invalid argument. I never had such situation in years of Django coding and don't know how to further investigate / fix this? I shut all sessions/tabs etc. and restarted the dev server without success. This is what I get when starting dev server: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 20, 2022 - 18:25:13 Django version 4.1, using settings 'cherry.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [20/Aug/2022 18:25:25] "GET / HTTP/1.1" 200 10645 [20/Aug/2022 18:25:25] "GET /static/css/dist/styles.css HTTP/1.1" 304 0 This is the traceback Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 138, in run self.finish_response() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 184, in finish_response self.write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 293, in write self._write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 467, in _write result = self.stdout.write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 826, in write self._sock.sendall(b) OSError: [Errno 22] Invalid argument [20/Aug/2022 18:34:49,657] - Broken pipe from ('127.0.0.1', 63773) -
Reverse resolution of URLs in Django with multiple url parameters
In my blog app I need to show articles based on the url: app_name = 'blog_app' urlpatterns = [ path('<int:user_id>/<int:year>/<int:month>', views.IndexView.as_view(), name='index'), path('<int:user_id>/<int:year>/<int:month>/<int:article_id>', views.DetailView.as_view(), name='detail'), ] The structure of the project is: myblog points to portal (for login); after login portal points to blog_app (which contains the articles list). So the steps to show articles are: mysite_index --> portal_login --> blog_app_index In portal app, after login, using a button I want to go to the index view of blog_app. So I need to specify all url parameters, and I'm trying to do it in this way: {% if user.is_authenticated %} <a href=" {% url 'blog_app:index' user_id = user.id year = {% now "Y" %} month = {% now "m" %} %} "> <button class="btn btn-secondary" type="button">Go</button> </a> {% endif %} I don't know why the URL becomes: http://127.0.0.1:8000/portal/%7B%25%20url%20'blog_app:index'%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20user_id%20%3D%20user.id%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20year%20%3D%202022%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20month%20%3D%2008%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%25%7D What I'm doing wrong? How I should do this type of reversing?