Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework how do I get the id I use in the URL
I have this serializer and I use it to get post detail of a post belonging to a user. The owner of the post is not the user that is currently logged in. I want to check if the post is bookmarked by the currently logged in user. The currently logged in user's id is passed in the request but I cannot find it in this context. Here is the serializer: class UserPostSerializer(serializers.ModelSerializer): images = PostImageSerializer(many=True, read_only=True, required=False) profile = serializers.SerializerMethodField() bookmarked = serializers.SerializerMethodField() class Meta: model = Post fields = [ "id", "category", "body", "images", "video", "profile", "published", "bookmarked", "created_at", "updated_at", ] depth=1 def get_profile(self, obj): profile_obj = Profile.objects.get(id=obj.user.profile.id) profile = ShortProfileSerializer(profile_obj) return profile.data def get_bookmarked(self, obj): breakpoint() bookmark = Bookmark.objects.filter(owner=obj.user.id, post=obj.id,marktype='post') if bookmark: return True else: return False The problem is obj.user.id is the owner of the post. I need the logged in user whose id is passed in the url. Here is the model for the bookmark: class Bookmark(models.Model): marktype = models.CharField(max_length=50) post = models.OneToOneField(Post, on_delete=models.CASCADE, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "bookmark" verbose_name_plural = "bookmarks" ordering = ["created_at"] db_table = "bookmarks" def … -
Why does this test keep failing?
I'm trying to write a simple test for some endpoints but the second one keeps failing. Here's the test.py from rest_framework.test import APITestCase, APIRequestFactory from rest_framework import status from django.urls import reverse from .views import PostViewSet from django.contrib.auth import get_user_model User = get_user_model() class PostListCreateTestCase(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.view = PostViewSet.as_view({"get": "list", "post": "create"}) self.url = reverse("post_list") self.user = User.objects.create( email="testuser@gmail.com", name="testuser", password="pass" ) def test_list_posts(self): request = self.factory.get(self.url) response = self.view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_create_post(self): sample_post = { "title": "sample title", "body": "sample body", } request = self.factory.post(self.url, sample_post) request.user = self.user response = self.view(request) self.assertEqual(response.status_code, status.HTTP_201_CREATED) And here's the view: from rest_framework import viewsets, status from rest_framework.response import Response from django.shortcuts import get_object_or_404 from .serializers import PostSerializer, LikeSerializer from .models import Post, Like class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() def get_queryset(self): posts = Post.objects.all() return posts def get_object(self): post = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) self.check_object_permissions(self.request, post) return post def create(self, request, *args, **kwargs): try: post = Post.objects.create( title=request.data.get("title"), body=request.data.get("body"), author=request.user, ) post = PostSerializer(post) return Response(post.data, status=status.HTTP_201_CREATED) except Exception as ex: return Response(str(ex), status=status.HTTP_400_BAD_REQUEST) def list(self, request, *args, **kwargs): posts = self.get_queryset() serializer = self.get_serializer(posts, many=True) return Response( data=dict(posts=serializer.data, total=len(serializer.data)), status=status.HTTP_200_OK, ) That's what I get: … -
Way to show latest 4 blog posts on my page
I want to be able to show the latest 4 blog posts only. I can't seem to get them to show. Any help would be greatly appreciated. Here is my code: Models.py class BlogPost(models.Model): blog_title = models.CharField(max_length=48) blog_article = RichTextUploadingField(null=True, blank=True, default="ici") blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png") blog_date = models.DateField(auto_now_add=True) blog_published = models.BooleanField(default=False) blog_featured = models.BooleanField(default=False) def publish(self): self.blog_date = timezone.now() self.save() def __str__(self): return self.blog_title Views.py def blogTest(request): posts = BlogPost.objects.filter(blog_date__lte=timezone.now()).order_by('blog_date') context_blog = {'posts': posts} return render(request, 'blogtest.html', context_blog) def latestPosts(request): latest = BlogPost.objects.filter(blog_date__lte=timezone.now()).reverse()[:3] return render(request, 'blogtest.html', {'latest': latest}) Template <div class="blog-post-container"> <div class="row"> <h1 id="lastest-blogs-title" style="text-align: center;">Latest Blogs</h1> {% for latestpost in latest %} {% if latestpost.blog_published is True %} <div class="col-md-4" id="bloggrid1"> <hr> <div class="blog-post"> <div class="blog-content"> <img class="blog-img"src="{{latestpost.blog_image.url}}"alt="My image"/> <h2 class="blog-title">{{latestpost.blog_title}}</h2> <hr id="blog-hr" style="width: 90%" /> <article class="blog-article"> <p>{{latestpost.blog_article|truncatechars_html:265|safe}}</p> </article> <a href="{% url 'viewblog' post.id %}"class="btn btn-secondary"type="button"class="blog-button">Read More...</a> <p class="blog-date">Posted on: {{latestpost.blog_date}}</p> </div> </div> </div> {% endif %} {% empty %} <h3>No Blog Uploads</h3> {% endfor %} </div> </div> </div> I have followed many other tutorials but I can't seem to see what I'm doing wrong here. -
Rollup Not Tree Shaking D3.js Correctly, Even With sideEffects Flag Set To False?
When using rollup v3 to bundle my npm project that uses the D3.js v7 library to an es6 module for use on the browser, I am ending up with a lot of extra unnecessary code from D3.js in the produced bundle. This happens even with the sideEffects flag set to false in package.json, which seemed to be the solution to this issue when it was discussed a couple of years ago on this github issue: https://github.com/d3/d3/issues/3076 . While treeshaking is definitely occuring, I'm still ending up with almost 1000 lines of code in my bundle from just importing one function (select from d3-selection). Besides setting the sideEffects flag to false in package.json, is there anything else I need to do? I also tried setting moduleSideEffects to false in rollup.config, but this didn't seem to have any additional effect. I have created a very simple example npm project that reproduces the issue. It is on github here: https://github.com/SpechtacularDave/rollupd3treeshake , or you can view the the example input index.js, package.json, and rollup.config.js below (but see the repo if you want to take a look at the output bundle since it's almost 1000 lines long). // index.js import {select} from "d3-selection"; select('#someid'); // … -
How are environment variables processed from ".env" file if Django project deployed to AWS from Github?
I have a Django project deployed on AWS EBS from a Github repo. My secret key is kept on a .env file. I've included the following: settings.py from decouple import config "SECRET_KEY" = config.("MY_SECRET_KEY") requirements.txt python-decouple==3.7 .env MY_SECRET_KEY = "THISISMYSECRETKEY-THISISMYSECRETKEY-THISISMYSECRETKEY" Since I've include .env inside my .gitignore file, the .env is not being pushed to Github. When I try to deploy my project I keep getting an error: "web: decouple.UndefinedValueError: SECRET_KEY not found". The project runs fine on a local server. Any advice would be appreciated. -
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
I have an issue with my container. I tried to Dockerize my django project and now i get some errors that i cannot resolve this is my Dockerfile FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN apt-get update && apt-get install -y libpq-dev RUN apt-get update && apt-get install -y python3-psycopg2 RUN pip3 install Psycopg2-binary RUN pip install --upgrade pip && pip install -r requirements.txt COPY . /code/` this is my 'docker-compose.yml' version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - localhost localhost: image: postgres:10 environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=Dimitri98! - POSTGRES_DB=test_DB_IS volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" volumes: postgres_data: But my command 'docker-compose up --build' with this output : mbakop_polls-web-1 | connection = Database.connect(**conn_params) mbakop_polls-web-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect mbakop_polls-web-1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) mbakop_polls-web-1 | django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP connections? mbakop_polls-web-1 | connection to server at "localhost" (::1), port 5432 failed: Cannot assign requested address mbakop_polls-web-1 | Is the server running on that host and accepting TCP/IP … -
How could I configure it so that the user who is logging in is a user of a PostgreSQL database manager?
I am developing a web application, I would like to know how I can configure it so that the user who is logging in is a user of the PostgreSQL database manager, generally there is a superuser who has permissions to freely manage all the databases, but other users with a lower hierarchy can be added, so I would like it to be possible to access as such with those users created in the DBMS. I use python as programming language and django as framework. I really have no idea how to achieve this functionality, I'm starting my studies, I want to surprise my database teacher with something different from the rest of the students, and I would like someone to help me with this, I don't expect a complete solution, just a guide and references to be able to achieve what is proposed -
How to insert data in specific category if it is not defined in Django model's field?
I have a Django project where I created two models: Category and Shop. Each shop might have only one category. If I didn't define a shop's category I want it to be in Without category section at template. How do I set a default value? My models: class Category(models.Model): name = models.CharField(max_length=100) position = models.IntegerField(unique=True) def __str__(self): return f'{self.name}' class DemoShop(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='Cat') def __str__(self): return f"{self.title}" When I write: category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='Cat', default='Without category') It has no effect in my database and It doesn't show in Without category section at my template. If I haven't put a shop in a certain category I want it to be shown in Without category at the page, like: Products: -lorem; -testshop; Watch: -keram; -pollop; Without category: (All shop what I haven't define a category in DB) -
Why is Django check_password=True but authenticate=None
I'm trying to write a unit test for a login endpoint in Django using as much of the built in functionality as possible. There are existing tests that confirm that the account create endpoint is functioning properly. In the login view, however, the check_password() function will return True for this test, but the authenticate() function returns None. Is it safe to use the check_password() function instead? Otherwise, how do I update this code to use the authenticate() function? accounts.py class Account(AbstractUser): username = models.CharField(max_length=150, unique=True, null=False, default='') password = models.CharField(max_length=100) ... REQUIRED_FIELDS = ['email', 'password'] class Meta: app_label = 'accounts' db_table = 'accounts_account' objects = models.Manager() test_login.py def test_login(self): # Create account request_create = self.factory.post('/accounts/account', self.request_data, content_type='application/json') view = AccountView.as_view() response_create = view(request_create) # Login account request_login = self.factory.post('/accounts/login', self.request_data, content_type='application/json') view = LoginView.as_view() response = view(request_login) views.py class LoginView(View): def post(self, request): r = json.loads(request.body) email = r.get('email') password = r.get('password') cp = check_password(password, Account.objects.get(email=email).password) user = authenticate(username=email, password=password) P.S. I've checked this thread and is_active is set to true. -
NOT NULL constraint failed: tickets_ticket.name
I am creating a ticket app in my django project. When I try to create a ticket the NOT NULL constraint failed: tickets_ticket.name error shows up. I'm not sure why the value for ticket.name field won't pass correctly. How do I proceed? any help is much appreciated. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name views.py view for creating a ticket def createTicket(request): form = TicketForm() categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category, created = Category.objects.get_or_create(name=category_name) ticket = Ticket.objects.create( host = request.user, category=category, name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) … -
Django ORM Cast() returning double quoted string from JSON field
I need to annotate a value that is saved in a json field in the same model. (Not the smartest but it is what it is). I am annotating the value as such: Model.queryset.annotate( reference=Cast( F("reference_numbers__some_id"), output_field=models.CharField(), ) ) I need it to be cast to text/char in the query because a subsequent search will only work on text/char (trigram similarity). It works, sort of, but the result adds an extra quote to my string. Like so: queryset[0].reference -> '"666999"' Any ideas on how to get the correct string from the query? I've also tried using just an ExpressionWrapper with the output field but since it doesnt cast the type in the SQL the code breaks afterwards when trying to execute the search because it uses the jsonb field still. -
Obtaining values from a foreign key Python model
Let's say I have these models/classes: class User(models.Model): id = models.AutoField. . . group = models.ForeignKey( Group, . . . ) . . . class Group(models.Model): id = models.AutoField. . . name = models.CharField. . . . . . In a custom logging function called when there is a change being made, I do this: obj = # object/model being updated; in this case: User old_values = {} new_values = {} for i in range(len(form.changed_data)): vname = obj._meta.get_field(form.changed_data[i]).verbose_name old_values.update( { vname: form[form.changed_data[i]].initial } ) new_values.update( { vname: form.cleaned_data[form.changed_data[i]] } ) That leads to this output: old_values = {'Group': 2} new_values = {'Group': <Group: New Group Name>} Looks like form.initial uses the id while form.cleaned_data uses some kind of unsightly object name format. Neither are desired. I want the output to look like this: old_values = {'Group': 'Old Group Name'} new_values = {'Group': 'New Group Name'} How do I do this? I cannot explicitly import the model name and use it. User and Group are merely two of dozens of models that must be treated non-explicitly in this generic logging function. I've tried apps.get_model(), get_object_or_404(), and other methods, but nothing has been working for me so far. -
Annotate performance Django
I've got the following models: class Match(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True, null=False) competition:Competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name='matches') season:Season = models.ForeignKey(Season, on_delete=models.CASCADE, related_name='season_matches', null=True, default=None) home:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_matches') away:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_matches') minute = models.IntegerField(default=None, null=True) period = models.CharField(max_length=25, default=None, null=True) datetime = models.DateTimeField() status = models.IntegerField() opta_match = models.OneToOneField(OptaMatch, on_delete=models.CASCADE, related_name='match', default=None, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Season(models.Model): id = models.AutoField(primary_key=True) competition:Competition = models.ForeignKey(to=Competition, on_delete=models.CASCADE, null=False, blank=False, related_name='seasons') start_date = models.DateTimeField(blank=False, null=False) end_date = models.DateTimeField(blank=False, null=False) name = models.CharField(max_length=255, null=True, default=None) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Event(models.Model): objects = BulkUpdateOrCreateQuerySet.as_manager() id = models.AutoField(primary_key=True) betsapi_id = models.IntegerField(unique=True) name = models.CharField(max_length=255) minute = models.IntegerField() player_name = models.CharField(max_length=255, null=True, default=None) extra_player_name = models.CharField(max_length=255, null=True, default=None) period = models.CharField(max_length=255) team:Team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='events') match:Match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name='events') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) And I wrote the following annotations to a Match object: all_matches_qs = (Match .objects .filter(status=1) .select_related('home', 'away', 'competition', 'competition__country', 'season', 'opta_match') .prefetch_related( Prefetch("season", queryset=Season.objects.prefetch_related( Prefetch("season_matches", queryset=Match.objects.prefetch_related( Prefetch('statistics'))) )), Prefetch('events', queryset=Event.objects.select_related("team", "match").filter(name__in=["Corner", "Goal", "Substitution", "Yellow Card", "Red Card"])), ) .annotate(season_statistics_count=Count('season__season_matches__statistics')) .annotate(goals=Count('events', distinct=True, filter=(Q(events__name='Goal') & Q(events__team=F('home'))))) ) Executing this on about 25 records takes me about 3.75 seconds … -
Override a template of a Django package
How can I override a change_list.html template of a Django package e.g Django import export, in an existing Django app. E.g I want to override this package template, this is what I did in my project. path to the file : app/templates/import_export/change_list.html {% extends 'import_export/change_list_export.html' %} {% block object-tools-items %} <div> Hello there </div> {% endblock %} I get this error : -
How to render differently a django model object field on a html page?
My model object have a IntegerField but I want to be able to render it differently on my html page, like lets say the object IntegerField is 500000 I want to render it as 500 000$ on my html page. So Add a space before the last 3 number and add a $ at the end. I have a models with a IntegerField that look like this class Listing(models.Model): listing_price = models.IntegerField(max_length=100) In my view I extract the models like this def home(request): listing_object = Listing.objects.all() context = { "listing_object": listing_object, } return render(request, "main/index.html", context) I render the data like this {% for listing in listing_new_object %} {{listing.listing_price}} {% endfor %} -
I get TypeError: Response.__init__() got an unexpected keyword argument 'errors' when trying to send POST request
I have this view that creates a post when sending a POST request to the endpoint. class PostViewSet(viewsets.ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [IsAuthorOrReadOnly] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) user = request.user if serializer.is_valid(): serializer.save(author=user) return Response(data=serializer.data, status=status.HTTP_201_CREATED) return Response(errors=serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
add regex in url in django
I have a url link in my template django like this http://localhost/ville/selectville/name/?&name=Paris+-+75002 I need to remove all characters that are before the character "+" to have a url like this http://localhost/ville/selectville/name/?&name=Paris this regex do the job myurl = "http://localhost/city/selectville/name/?&name=Paris+-+75002" re.sub(r'\+.*', '', myurl ) but how to integrate it in my urls.py file with this path path('selectville/<str:name>/', VilleSelect.as_view(), name='ville_select'), thank you -
'project.Account' has no ForeignKey to 'project.Object': How to link an account model to the objects of a project?
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address... So I modified admin.py: from django.contrib import admin from .models import Todo, Account from django.contrib.auth.models import User class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class TodoAdmin(admin.ModelAdmin): readonly_fields = ('created',) inlines = (AccountInline, ) admin.site.unregister(User) admin.site.register(Todo, TodoAdmin) But got back: <class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'. So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE): from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.CharField(max_length=100) firstname = models.CharField(max_length=30) lastname = models.CharField(max_length=50) company = models.CharField(max_length=5) def __str__(self): return self.user.username class Todo(models.Model): title = models.CharField(max_length=100) datetime = models.DateTimeField() memo = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) important = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) account = models.ForeignKey(Account, on_delete=models.CASCADE) def __str__(self): return self.title But I still have the error. -
Django AccountActivationTokenGenerator login link works multiple times
I have been using AccountActivationTokenGenerator with Django SingIn and SignUp mechanism. class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.email_verified) ) account_activation_token = AccountActivationTokenGenerator() class PasswordResetTokenGenerator: ... def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with if not constant_time_compare(self._make_token_with_timestamp(user, ts), token): # RemovedInDjango40Warning: when the deprecation ends, replace # with: # return False if not constant_time_compare( self._make_token_with_timestamp(user, ts, legacy=True), token, ): return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True I can successfully generate the link and email to user, and the user can use the link to login to the system. However the link works everytime the user clicks it. I just what the link to be valid only once, and when it is used, it should be invalidated for the next attempts. @api_view(['GET']) @renderer_classes((TemplateHTMLRenderer, JSONRenderer)) def activate(request, uidb64, token, project_uuid='None', backend='videoo.registration.views.EmailBackend'): try: uid = force_text(urlsafe_base64_decode(uidb64)) User = … -
Store very little Integer in DB( PostgreSQL )
How to store very little Integer (4 bite) integer in my database? Hi.🙌 In my model I want to store a very little integer in my DB and I don't want to use SmallIntegerField. Because Django will store 16 Byte data in DB and it is too much for my need. How can I store 4 bite integer or even less in PostgreSQL? Thanks for your help.🙏 -
Django not recognized in virtual environment altough already installed when inside virtual environment
I've created a virtual environment in my PC(Windows). I've pushed the project to my git repository and now cloned it into my Mac. I activated the virtual environment, and tried running : python3 manage.py runserver This error is raised : ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I understand that the message sent from above is defined inside the manage.py if an ImportError is raised. What I'm trying to understand is how to make the virtual environment to include the python packages inside my project. I will explain what I've tried doing below. AFTER cloning the project, I've changed line in my pyvenv.cfg ... include-system-site-packages = true //previously = false ... I'm not sure what I did wrong while setting up the virtual environment and installing the packages while being IN the virtual environment. -
Event tracking on Django
I want to implement the function of recording people for a certain event. By type: The registered user sees the desired publication -> the "mark" button on the publication -> the data is saved in the database. I can't imagine how to do it, I didn't really find a solution. I would be glad to explain how this can be done on Django I didn't find a solution :( -
Django Azure rest framework call 500 server error
I have an django app that is running fine locally, but deployed to azure app service I am getting a 500 error when when it requests data. The app is being deployed in a docker container on an azure app service: URLs.py path('primaryexams/', TemplateView.as_view(template_name='xxxDB/primaryexams.html'), name='primaryExams'), path('primaryexamsdata/', views.PrimaryExamsView.as_view(), name='primaryexam_data'), views.py class PrimaryExamsView(generics.ListAPIView): serializer_class = PrimaryExamSerializer template_name='xxxDB/primaryexams.html' def get_queryset(self): return xxxPrimaryExamData.objects.all() def filter_for_datatable(self, queryset): # filtering search_query = self.request.query_params.get('search[value]') if search_query: lookups = Q(xxxid__first_name__icontains=search_query)|Q(xxxid__last_name__icontains=search_query)|Q(xxxid__xx_id__icontains=search_query) queryset = xxxPrimaryExamData.objects.filter(lookups) return queryset def list(self, request, *args, **kwargs): draw = request.query_params.get('draw') queryset = self.filter_queryset(self.get_queryset()) recordsTotal = queryset.count() filtered_queryset = self.filter_for_datatable(queryset) try: start = int(request.query_params.get('start')) except (ValueError, TypeError): start = 0 try: length = int(request.query_params.get('length')) except (ValueError, TypeError): length = 25 end = length + start serializer = self.get_serializer(filtered_queryset[start:end], many=True) response = { 'draw': draw, 'recordsTotal': recordsTotal, 'recordsFiltered': filtered_queryset.count(), 'data': serializer.data, } return Response(response) serializers.py class PrimaryExamSerializer(serializers.ModelSerializer): xxx_id = serializers.ReadOnlyField(source='xxxid.xxx_id') last_name = serializers.ReadOnlyField(source='xxxid.last_name') first_name = serializers.ReadOnlyField(source='xxxid.first_name') program_institution = serializers.ReadOnlyField(source='program_institution.institution_id') program_institution_name = serializers.ReadOnlyField(source='program_institution.institution_name') test_center_institution = serializers.ReadOnlyField(source='test_center_institution.institution_id', default='none') class Meta: model = AbnsPrimaryExamData fields = ( 'id','xxx_id','last_name','first_name','medical_school','program_institution','program_institution_name','graduation_year','test_center_institution' ) When I try to load the data I get an ajax error, and when I look at the request its getting a 500 server error: https://xxxinternal.azurewebsites.net/xxxDB/primaryexamsdata/?draw=1&columns%5B0%5D%...blah...blahh I have other views set … -
add a menu at draw marker in Folium?
I just add a menu onche you clic on the draw maker in draw.py toolbar I modified the html of the map using this code {{ this._parent.get_name() }}.on('draw:drawstart', function(e){ var type = e.layerType, layer = e.layer; if (type === 'marker') { console.log('drawing starting... ' + e.layer) // Do marker specific actions var html = "<br><li class=''><a class='' title='Ubicacion de mujeres'>Ubicacion de mujeres</a></li><br>" + "<li class=''><a class='' title='Zona de Violencia'>Zona de Violencia</a></li><br>" + "<li class=''><a class='' title='Poblaciones diversas'>Poblaciones diversas</a></li><br>"; document.querySelector(".leaflet-draw-actions").innerHTML += html; } }); What i'm trying to do is to add a menu so the user can create a marker depending on what type of layer you choose previously my idea es in this image here When i do this, the "cancel operation" does not work anymore and also i dont know how to change the color of the marker draggable that it is displayed. Any idea will be so helpful Thank you and regards! -
Django yfinance historical data
I'm running a private Django project, that might be summarized as an html page with a form composed of an input search, and a submit button. I want to be able to write any stock ticker ('AAPL') in the input, and to generate a chart following the request. However, I made all my tests outside the django framework. Here comes the tricky part. My code related to the data scrapping designed previously, does not work when executed in the Django framework. from yahoo_finance import Share def checkview(request): yahoo = Share('YHOO') stock = yahoo.get_open() return HttpResponse(room) Here is the error code. enter image description here Also, I tried a different approach with this code: import yfinance as yf tsla = yf.Ticker("TSLA") hist = tsla.history(period='1y') import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=hist.index,y=hist.Close, mode='lines')) fig.show() Can someone explain me, how can I solve the error ? And, how to install properly packages in the Django Framework. As an example, I will want to use Plotly going further in this project. Thanks !