Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
javascript isn't reading correctly a static json file
I have been working on a project, where I have to get data from a database with its own server. For that I have used Django as a tool to combine both backend and frontend. Also I created a function that connect python to odbc so I can get the information from the database. My logic was that I want to convert all the information into JSON file, so that javascript (frontend) would have acccess to it to convert it into graphs. To make myself more clear, here are the main components: views.py def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = TextForm(request.POST) # check whether it's valid: if form.is_valid(): # From this we get the result of POST method date = form.cleaned_data['date'] splitdate = date.split(sep='-') # Here we call the class created in Functions.py x = GetData(int(splitdate[2]), int(splitdate[1]), int(splitdate[0])) x.getInfo() context = { 'text': date, 'form': form, } return render(request, 'index.html', context) # if a GET (or any other method) we'll create a blank form else: form = TextForm() return render(request, 'index.html', {'form': … -
Users are not added to the database in Django [closed]
I am trying to create an extend User model but when I register a new account, it is not displayed in the admin panel and the users table itself is not. How to fix it? Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users … -
Unable to start server due Templates issues
hi all, I tried to build Django page using this post: djangocentral.com/building-a-blog-application-with-django/ Seems I completed all steps but I am getting this error when running server. Do you know what can be reason for error message I am getting? TemplateDoesNotExist at / index.html, blog/post_list.html Request Method: GET Request URL: http://127.0.0.1:8080/ Django Version: 3.2.9 Exception Type: TemplateDoesNotExist Exception Value: index.html, blog/post_list.html Exception Location: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\template\loader.py, line 47, in select_template Python Executable: C:\Download\Development\NowaStrona_Django\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Download\\Development\\NowaStrona_Django\\mysite\\my_site', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts\\python37.zip', 'C:\\Download\\Development\\NowaStrona_Django\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django\\lib', 'C:\\Download\\Development\\NowaStrona_Django\\Scripts', 'c:\\program files (x86)\\python37-32\\Lib', 'c:\\program files (x86)\\python37-32\\DLLs', 'C:\\Download\\Development\\NowaStrona_Django', 'C:\\Download\\Development\\NowaStrona_Django\\lib\\site-packages'] Server time: Wed, 15 Dec 2021 10:54:46 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\T\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\E\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\M\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\P\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\L\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\A\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\T\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\E\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\S\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\_\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\D\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\I\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\R\index.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\Download\Development\NowaStrona_Django\mysite\my_site\S\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Download\Development\NowaStrona_Django\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) django.template.loaders.app_directories.Loader: … -
How do I dynamically filter fields returned in django rest api get request based on the user making the request?
I have a photoshoot api that allows photographers to post shoot photos from which preview and watermarded versions are derived. Editors and clients can both select which photos will be edited, but the editor should only see the preview without watermark and the clients should only see the watermarked versions. I was wondering how these different distincitons can be made in the DRF queryset. My model: class Unedited(models.Model): shoot = models.ForeignKey( Shoot, on_delete=models.CASCADE, null=True, related_name="shoot_photo" ) original = models.ImageField(null=True, blank=False, upload_to=shoot_upload_to) preview = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to) watermarked = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to) upload_time = models.DateTimeField(auto_now_add=True) My Serializer: class UneditedSerializer(serializers.ModelSerializer): class Meta: model = Unedited fields = "__all__" def create(self, validated_data): validated_data["preview"] = reduce_resolution(validated_data["original"]) validated_data["watermarked"] = add_watermark(validated_data["preview"]) img_obj = Unedited.objects.create(**validated_data) img_obj.save() return img_obj My view: class UneditedViewSet(viewsets.ModelViewSet): if not TESTING: permission_classes = (PhotosPermission,) serializer_class = UneditedSerializer def get_queryset(self): return Unedited.objects.filter(**self.request.query_params) -
Unable to run vscode's debugger with dockerized django project
Every time when I run a debugger there happen many things but not what I expect. I'm running a project with docker-compose up Checking the localhost if backend backend is okay. It's down. What's funny the container is running because I'm attached to this with vscode's remote containers. The debugpy library is installed. The first approach to run a debugger end with such info in debug console: Attached! System check identified some issues: WARNINGS: workflow.State.additional_values: (fields.W904) django.contrib.postgres.fields.JSONField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use django.db.models.JSONField instead. Operations to perform: Apply all migrations: accounts, auth, contenttypes, files, mambu, otp_totp, sessions, token_blacklist, workflow, zoho Running migrations: No migrations to apply. and it's down. Backend is also down. Second try: Attached! System check identified some issues: WARNINGS: workflow.State.additional_values: (fields.W904) django.contrib.postgres.fields.JSONField is deprecated. Support for it (except in historical migrations) will be removed in Django 4.0. HINT: Use django.db.models.JSONField instead. Zoho Configuration failed, check that you have all variables ZOHO_TOKEN_URL, ZOHO_REST_API_KEY, ZOHO_CURRENT_USER_EMAIL and it's down but backend is up - I'm able to login etc. The third try ends with such an error connect ECONNREFUSED 127.0.0.1:5678. Any tips? Code: manage.py #!/usr/bin/env python """Django's command-line … -
how can i search in django for multiple values like the ( werkstoffbezeichnung and the werkstoffnummer )
This cod I made only works for one values, when I try to add other one it stops working. how can i fix it? def search_post(request): if request.method == "POST": searched = request.POST.get('searched') posts = Post.objects.filter(werkstoffnummer=searched) posts = Post.objects.filter(werkstoffbezeichnung=searched) return render(request, 'Blog/search_post.html', {'searched': searched, 'posts': posts}) else: return render(request, 'Blog/search_post.html', {}) -
Django - How can I restrict a url access basing on the environment where the app is running
I have the local and staging environment which I set using DJANGO_SETTINGS_MODULE. I want this URL to only be accessible in the staging environment. How can I know that the current environment is staging and restrict the URL to it. Here is my url path("testing_page/", views.testing_page_view, name="testing_page"), The staging base url is https://myapp-staging.domain.com/ The view is def testing_page_view(request): if request.method == "GET": return render(request, "testing_page.html") else: values = request.POST.dict() return HttpResponseRedirect(login_link) -
Django: Performance issues with query sets using m2m
I have about 1,400,000 rows of Video and Tag through models. There are about 300,000 Videos and 5,000 Tags. Issuing a query set like the one below takes about 500-700ms. #models.py class Tag(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(unique=True, max_length=30) class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField( max_length=300) #queryset Tag.objects.annotate(count=Count("video")).order_by("-count")[:100] Queries issued SELECT "videos_tag"."id", "videos_tag"."name", COUNT("videos_video_tags"."video_id") AS "count" FROM "videos_tag" LEFT OUTER JOIN "videos_video_tags" ON ("videos_tag"."id" = "videos_video_tags"."tag_id") GROUP BY "videos_tag"."id" ORDER BY "count" DESC LIMIT 100 QUERY PLAN ---------------------------------------------------------------------------------------------------- Limit (cost=35140.11..35140.36 rows=100 width=37) -> Sort (cost=35140.11..35153.96 rows=5539 width=37) Sort Key: (count(videos_video_tags.video_id)) DESC -> HashAggregate (cost=34873.02..34928.41 rows=5539 width=37) Group Key: videos_tag.id -> Hash Right Join (cost=173.63..28189.98 rows=1336608 width=45) Hash Cond: (videos_video_tags.tag_id = videos_tag.id) -> Seq Scan on videos_video_tags (cost=0.00..24505.08 rows=1336608 width=32) -> Hash (cost=104.39..104.39 rows=5539 width=29) -> Seq Scan on videos_tag (cost=0.00..104.39 rows=5539 width=29) As far as the execution plan is concerned, I think the cause is that index is not used. How can I improve this? -
Work around for handling CPU Intensive task in aws ec2?
I have created a django application (running on aws ec2) which convert media file from one format to another format ,but during this process it consume CPU resource due to which I have to pay charges to aws. I am trying to find a work around where my local pc (ubuntu) takes care of CPU intensive task and final result is uploaded to s3 bucket which I can share with user. Please note :- I have decent internet connection and computer which can handle backend very well but i not in state to pay throttle charges to aws. Solution :- One possible solution is that when user upload media file (html upload form) it goes to s3 bucket and at the same time via socket connection the s3 bucket file link is send to my ubuntu where it download file, process it and upload back to s3 bucket. Please suggest me better solution as it seems to be not efficient. -
How to use a single axis for labels in chart.js and djang?
How to use a single axis for labels in chart.js and django. I have data from several models that I want to present by ordering them by date on the same canvas chart.js. The X axis represents the number of data by name for each model and the Y axis represents the year of each data for each model. Here is the method I used for tow models but it doesn't work. Models.py class Even1(models.Model): name = models.CharField(max_length=20) description = models.TextField(max_length=250, null=True) date = models.DateField() time=models.TimeField() def __str__(self): return self.name class Even2(models.Model): name = models.CharField(max_length=20) description = models.TextField(max_length=250, null=True) date = models.DateField() time=models.TimeField() def __str__(self): return self.name views.py def even_area_chart(request): labels1 = [] labels2 = [] data1 = [] data2 = [] q1 = Even1.objects.values('date').annotate(date_name=Count('name')).order_by('- date') q2 = Even2.objects.values('date').annotate(date_name=Count('name')).order_by('-date') for rm in q1: labels1.append(rm['date']) data1.append(rm['date_name']) for rm in q2: labels2.append(rm['date']) data2.append(rm['date_name']) return JsonResponse(data={ 'labels1': labels1, 'labels2': labels2, 'data1': data1, 'data2': data2, }) #script <script type="text/javascript"> $(document).ready(function(){ $.ajax({ url: "{% url 'even_area_chart' %}", dataType:"json", type:"GET", contentType:"application/json", success: function(response){ if(response){ var config = { type: 'line', data: { datasets: [{ data: response['data1'], lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", borderColor: "rgb(196,88,80)", pointRadius: 3, pointBackgroundColor: "rgba(78, 115, 223, 1)", pointBorderColor: "rgba(78, 115, 223, … -
Django cant find static(css) folder
My Django template cant seem to find my css file in my static folder which is structured at the root dir. Here is my settings.py 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j@g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'maintenance', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nitrofleet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'nitrofleet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # … -
django-treebeard Materialized Path tree depth ended up being zero
I found a problematic node with id 633. tree.find_problems() ([], [], [], [633], [35, 9, 50, 291, 464]) After running tree.fix_tree() It does not find any problems. tree.find_problems() ([], [], [], [], []) But actually 633 is still in some wierd state. >>> node633.depth 0 >>> node633.path '' Problem: node633.depth is 0 which means its not root but it does not have parent as well. Path is empty too. This means my code will try to find parent from a node that does not have a parent. Running fix_tree again does not fix it. Moving node633 is not an option too because: treebeard.exceptions.InvalidMoveToDescendant: Can't move node to a descendant. Question: How can i fix this broken node66? -
Mat-icon display based on condition in for loop
I have an angular-django app which makes an aPI call to a third-party application and returns json response. I am looping through the response and displaying the data in a table. <tr *ngFor="let item of job_list"> <td style="text-align:center">{{item?.ReleaseName}}</td> <td style="text-align:center">{{item?.Source}}</td> <td style="text-align:center"><mat-icon *ngIf="Successful" style="color:green;">check circle icon</mat-icon> <mat-icon *ngIf="Faulted" style="color: red;">error icon</mat-icon> <mat-icon *ngIf="Stopped" style="color: grey;">cancel icon</mat-icon> {{item?.State}} </td> <td style="text-align:center">{{item?.StartTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> <td style="text-align:center">{{item?.EndTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> </tr> Here, I want to display mat-icon based on {{item?.State}} value. For example if the value is Successful, I want to display the "check circle icon", if it's "Faulted", I want to display "error icon" etc. Is this possible? Thank you -
How to show that the lesson is done from related model?
I have list of lessons and i need to highlight the done ones by current person. I tried my version below, but it's showing only done lessons. I have 2 models: lessons and donelessons related with user and lessons with foreignkey. models class Lessons(models.Model): theory = models.TextField(blank=True) words = models.TextField(blank=True) question1 = models.CharField(max_length=255) answer1 = models.CharField(max_length=255) class DoneLessonsModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) lessons = models.ForeignKey(Lessons, on_delete=models.CASCADE, null=True, related_name="releases") done = models.BooleanField(default=False) views class News(ListView): model = Lessons template_name = 'static/news.html' context_object_name = 'posts' def get_queryset(self): return Lessons.objects.all().prefetch_related( Prefetch('releases', queryset=DoneLessonsModel.objects.filter(user=self.request.user))).all() html ... {% for p in posts %} {% for release in p.releases.all %} <div class="col-md-3 mt-3"> <div class="card mb-4 box-shadow {% if release.done == True %} bg-success text-white btn-outline-light {% else %} border-dark {% endif %} "> <div class="card-body"> <p class="card-text">Lesson №{{ p.pk }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a href="{% url 'theory' p.pk %}" > <button type="button" class="btn btn-sm {% if release.done == True %} btn-outline-light {% else %} btn-outline-dark {% endif %} ">Start</button> </a> </div> </div> </div> </div> </div> {% endfor %} {% endfor %} ... -
Cannot resolve file 'signup'
I am newbie to Django and i need help to solve this problem. It states that cannot resolve file'signup'. <h3>Create your account!</h3> <form method="post" action="/signup"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Create A Username (use only letters and numbers)" Required> </div> -
Django: How to log user in right after they had registered with somewhat default UserCreationForm?
I'm trying to log the user in right after they had registered with the app, so that they don't have to manually log in right after. I have created RegisterForm from django's UserCreationForm and it works as it should - it creates an User object if the form is valid, but I don't know how to access that created User object to log it it using the login function, which requires, aside from request, also an user object. Note: I have edited the default User in models.py. This is my code: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','id':'username', 'aria-describedby':'usernameHelp'}) self.fields['password1'].widget.attrs.update({'class':'form-control','id':'password1', 'aria-describedby':'password1Help'}) self.fields['password2'].widget.attrs.update({'class':'form-control','id':'password2','aria-describedby':'password2Help'}) class Meta: model = User fields = ['username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'photo', 'amazon', 'twitter', 'facebook', 'instagram', 'youtube'] widgets = { 'email':EmailInput(attrs={'class':'form-control', 'id':'email', 'aria-describedby':'emailHelp'}), 'first_name':TextInput(attrs={'class':'form-control', 'id':'first_name',}), 'last_name':TextInput(attrs={'class':'form-control','id':'last_name', 'aria-describedby':'nameHelp'}), 'photo':ClearableFileInput(attrs={'class':'form-control','id':'photo', 'aria-describedby':'photoHelp'}), 'amazon':URLInput(attrs={'class':'form-control', 'id':'amazon', 'aria-describedby':'amazonHelp'}), 'twitter':URLInput(attrs={'class':'form-control', 'id':'twitter', 'aria-describedby':'twitterHelp'}), 'facebook':URLInput(attrs={'class':'form-control', 'id':'facebook', 'aria-describedby':'facebookHelp'}), 'instagram':URLInput(attrs={'class':'form-control', 'id':'instagram', 'aria-describedby':'instagramHelp'}), 'youtube':URLInput(attrs={'class':'form-control', 'id':'youtube', 'aria-describedby':'youtubeHelp'}) } And here is the view: def register(request): # POST if request.method == "POST": # In addition to our form we must make sure to get the files too, if photo is uploaded form = RegisterForm(request.POST, request.FILES or None) if form.is_valid(): form.save() #user = User.objects.get() ??? #login(request, user) return HttpResponseRedirect(reverse('index')) else: … -
Can't mock a third party api call
I have a view that perform a third party API call: from .atoca_api_calls import atoca_api_call def atoca_api_call_view(request): # some code data = atoca_api_call(**params) # the actual API call happens in this func # some code My intention is to mock just the atoca_api_call() func and not the whole view. class AtocaTestCase(TestCase): def setUp(self): # some code @patch('crm.atoca_api_calls.atoca_api_call') def test_atoca_call(self, mock_atoca_api_call): mock_atoca_api_call.return_value = MagicMock( status_code=200, response=some_json # just returns some json ) url = reverse('crm:atoca-api-call') # url related to `atoca_api_call_view` response = self.client.post(url, some_others_params) # various asserts The test works fine but atoca_api_call() is not mocked. I'm aware of where to patch: @patch('crm.views.atoca_api_call', autospec=True) Raises a ValueError: ValueError: Failed to insert expression "<MagicMock name='mock.__getitem__().__getitem__().__getitem__()().resolve_expression()' id='140048216397424'>" on crm.Company.atoca_id. F() expressions can only be used to update, not to insert. It's probably a simple issue I don't catch for inexperience, any help is really appreciated. -
Use npm library for django on runserver environment
I made static folder in my root project. in settins.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Install npm library under static directory. myproject/static$ npm -i js-cookie then There comes the files like this myproject/static/node_modules/js.cookie/dist/js.cookie.min.js then run server myproject$ python manage.py runserver then use in template.html However this shows the error GET http://localhost:8000/static/node_modules/js.cookie/dist/js.cookie.min.js net::ERR_ABORTED 404 (Not Found) I have two quesitons. Is it good practice to use npm library under django project?? Maybe runserver doesn't use mypoject/static? -
Django ORM for loop to get queryset
I am trying to use for loop to get list of author with the number of books writing and author with the title of book wrote. Here is my models.py class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title I have tried to loop through like this: for a in Author.all(): books = a.book_set.order_by('author') print(books) I get the authors as they are in DB. Also, for book in book_set.iterator(): ... print(book.title) I got the list of all books. I use author_list = Author.objects.order_by("book").count() which gave the number of author. How can I loop through the DB and get the Author with number of books, and Authors with book title wrote. -
Image and CSS pre loading in Django
I am developping a website with Django, hosted on Heroku, and still fairly new to it. I published my application, and notice a problem when navigating on the hosted website : Whenever you load a new page, it looks like images and css are reloading completely. For a short time (less than 1 second), It creates some king of glith on my menu bar because buttons are moving (because the image is missing) and changing color (because css is missing). What would be a proper way to handle this ? Is it possible to store those image and css in somme kind of cookie on the user browser ? Also, when i run the website on my localhost, i don't experiment the problem. Thanks for your help !! -
Django Drf: generate an 8 digit unique number in the user serializer
I have a field in my users model that will only be utilized for a Certain type of user student_id = models.CharField(_("student id"), validators=[ MinValueValidator(10_000_000_000), MaxValueValidator(99_999_999_999) ],unique=True, max_length=8, blank=True, null=True) when creating a user in the serializers.py file i tried the below code but didn't work def create(self, validated_data): def create_new_ref_number(): not_unique = True while not_unique: unique_id = randint(10000000, 99999999) if not User.objects.filter(student_id=unique_id): not_unique = False instance = User.objects.create( student_id=create_new_ref_number, firstname=validated_data['firstname'], middlename=validated_data['middlename'], lastname=validated_data['lastname'], age=validated_data['age'], phone=validated_data['phone'], ) after saving the user the student_id field is populated with the following string <function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950> -
Django gives Secret key must not be empty error
I am having this issue when I try to run the server in Pycharm. I am new to Django and downloaded this project as a backend for my react application. I have generated a Secret Key using: from django.core.management.utils import get_random_secret_key print(get_random_secret_key()) exit() I added this Secret key to settings.py file as well. Error Log which I get: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
How to block rows on read and write operations?
I have a model that counts how many operations were done by a user. (It's simplified for an example) User = get_user_model() class UserOperationCounter(models.Model): count = models.IntegerField(default=0) user = models.OneToOne(User) I have a context manager that is fetching a counter object for a user and increments the counter param after the exit @atomic() class IncrementCounterContextManager: def __init__(user_id): self.operation_counter = UserOperationCounter.objects.filter(user_id=user_id).select_for_update().get() def __enter__(): print(f"Fetch counter={operation_counter.counter} for user={operation_counter.user.id}") return self.operation_counter def __exit__(): self.operation_counter.count = F("count") + 1 self.operation_counter.save(update_fields=["count"]) self.operation_counter.refresh_from_db() print(f"Set counter={operation_counter.counter} for user={operation_counter.user.id}") Let's assume I want to use the context manager each time the user does some specific action on a platform and then I want to send him a notification with the message: "You have done <counter> hidden actions on our platform". select_for_update() works perfectly in scenarios when I want to update a Counter object at the same time, but the row is not locked for reading. Here is an example: def send_notification(counter, user_id): print(f"Send notification with counter={counter} to user={user_id}") user_id = 1 with atomic(): with IncrementCounterContextManager(user_id=1) as usr_counter1: send_notification(usr_counter1.counter, usr_counter1.user.id) with IncrementCounterContextManager(user_id=1) as usr_counter2: send_notification(usr_counter2.counter, usr_counter2.user.id) When I check logs I will see something like: Fetch counter=0 for user=1 Fetch counter=0 for user=1 Send notification with counter=0 to user=1 … -
Pivot table in django admin
good day There is a user and a task model, combined with a ForeignKey The task model has a type field - the type of the task, in which several variants of types are written, let it be 1, 2, 3 And actually further the question, I need to create a table with the number of tasks, that is, how many tasks of type 1, type 2 and type 3, filters are also needed by the start and end time of the task, and then export to Excel Here's how best to solve this problem, create a new model, or is it better to do something differently? With the creation of the model, there are questions about the constant updating of the database, it seems to me that this is not very good, now it is done so that there is a model field of the model Type 1, Type 2, Type 3 and then with the help of filters, tasks are obtained through the user and filtered, and then count () is calculated, but it can be done more correctly, so to speak, without unnecessary database operations. I use django, django-jet for the admin area -
Saving dictionary data to django model problem, error message = AttributeError("'dict' object has no attribute '_meta'")
I have a problem, saving a dictionary data to django model. Did I need to input sqlite3 query somewhere? Please teach me how can I solution this problem. received dictionary data {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Error message {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Unexpected e=AttributeError("'dict' object has no attribute '_meta'"), type(e)=<class 'AttributeError'> modles.py class Data(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) temp = models.FloatField(default=0.0) humidity = models.FloatField(default=0.0) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class DataSerializer(serializers.ModelSerializer): id = serializers.IntegerField(write_only=False) class Meta: model = Data fields = '__all__' snd_clienet.py data = Data( id = 20, author = User.objects.get(username='labovming'), title = 'random data', temp = random.random()*300, humidity = random.random()*12, created_date = timezone.now() ) serializer = DataSerializer(data) msg = JSONRenderer().render(serializer.data) rcv_server.py while msg: stream = io.BytesIO(msg) data = JSONParser().parse(stream) serializer = DataSerializer(data=data) # create new instance serializer = DataSerializer(data, data=data) # update 'data' # serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data serializer.is_valid() **<<< Validation fail ** serializer.errors serializer.validated_data **<<< Empty ** try: serializer.save() **<<< Error occur here ** print(f'data added : {serializer}') if self.DBman.messageHandler(Name, msg.decode()) == -1: self.request.close() break msg = self.request.recv(1024) except Exception as e: print(f"Unexpected {e=}, {type(e)=}") break