Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Populate parent field from url kwarg in a nested serializer in Django REST Framework
I have 2 models, Catalog and Epic: class Catalog(models.Model): created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(null=False, default=False) class Epic(models.Model): name = models.CharField(max_length=128, null=False) slug = models.SlugField(null=False) catalog = models.ForeignKey(Catalog, null=False, on_delete=models.CASCADE) I have created CRUD viewset and serializer for Catalog, using DRF. Now I want to create CRUD viewset and serializer for Epic, to be used like /catalogs/<int:catalog_pk>/epics/<int:pk>. I am using DRF-nested-router: router = routers.SimpleRouter() router.register("catalog", CatalogViewSet) catalog_router = routers.NestedSimpleRouter(router, "catalog", lookup="catalog") catalog_router.register("epics", EpicsViewSet, basename="epics") urlpatterns = router.urls + catalog_router.urls And these are my viewset and serializer for Epic: class EpicsViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): serializer_class = EpicSerializer permission_classes = (IsAuthenticated, CatalogPermissions) def get_queryset(self): return Epic.objects.filter(catalog=self.kwargs["catalog_pk"]) class EpicSerializer(serializers.ModelSerializer): class Meta: model = Epic fields = "__all__" I am trying to run the creation endpoint like this: POST /catalog/1/epics/ with epic data, but I get the error that catalog field is missing in the payload. I want this to be done automatically from URL kwargs. I want it to take the catalog_id from kwargs and set the catalog instance to the newly created Epic instance in the serializer. The starightforward way would be to override the create function in the serializer, but I am hesitant to do that and was wondering if there is a … -
How to check If the translation of a sql query to Django ORM is equivalent?
I have these models: class Messages(models.Model): channel = models.TextField(blank=True, null=True) message = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) publisher = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=5) class Meta: managed = False db_table = 'messages' class ReadMessages(models.Model): user_id = models.IntegerField(blank=True, null=True) message_id = models.ForeignKey(Messages, db_column='message_id', blank=True, null=True, on_delete=models.CASCADE) class Meta: managed = False db_table = 'read_messages' and I also have a legacy system who is using the same database, but this system is doing the following query in pure sql: SELECT messages1.id, messages1.channel FROM (SELECT * FROM messages WHERE channel IN ('U560')) messages1 LEFT JOIN read_messages ON messages1.id = read_messages.message_id WHERE read_messages.id IS NULL; I tried to do the same in Django ORM using the following code: Messages.objects.filter(channel__in=['U560'],readmessages__id__isnull=True).values('id', 'channel') with the few tests i've done they returned the same result, but I still not sure if they are equivalents and if there will be a case where the two queries will return differents results. -
Highlight words in markdown content according to search result using Reactjs
I am building React/Django app that is using markdown content I want to put a search bar at which the user can search in the blog content and the words that are matching the search results are highlighted. I have used react-highlight-words library but I found that It isn't compatible with markdown content so I am trying using react-string-replace library but there is a problem that faced me in the test react-string-replace returns array not string so I tried to use a hook (useState) which is an empty string and map each word in the array and append it to the hook then put the Hook inside ReactMarkdown element. import React from 'react' import ReactMarkdown from 'react-markdown' import reactStringReplace from 'react-string-replace'; export default function Mark(){ const [stringData, setStringData] = React.useState(""); const content = 'Hey my number is 555-555-5555.'; const replacearray= reactStringReplace(content, 's', (match, i) => ( `===${match}===` )); console.log(replacearray) replacearray.map(word =>{ console.log(word) setStringData(stringData + `${word}`) }) console.log(stringData) return( <ReactMarkdown>{stringData}</ReactMarkdown> ) } The result of console.log(replacearray) is: Array(3) [ "Hey my number i", "===s===", " 555-555-5555." ] The result of console.log(word) is: Hey my number i mark.js:116:13 ===s=== mark.js:116:13 555-555-5555 mark.js:116:13 The result of console.log(stringData) is: 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. 555-555-5555. … -
building user-based collaborative filtering system in Django
I'm trying to build a simple user based collaborative filtering in Django for an E-commerce using just the purchase history. Here are the steps I use, I know it needs more improvements but I've no idea what's the next move. here's the product model class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() here's the purcashe model class Purchase(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) purchase_date = models.DateTimeField(auto_now_add=True) Now to get similar users def find_similar_users(user, k=5): all_users = User.objects.exclude(id=user.id) similarities = [(other_user, jaccard_similarity(user, other_user)) for other_user in all_users] similarities.sort(key=lambda x: x[1], reverse=True) return [user_similarity[0] for user_similarity in similarities[:k]] and to calculate similarity between each: def jaccard_similarity(user1, user2): user1_purchases = set(Purchase.objects.filter(user=user1).values_list('product_id', flat=True)) user2_purchases = set(Purchase.objects.filter(user=user2).values_list('product_id', flat=True)) intersection = user1_purchases.intersection(user2_purchases) union = user1_purchases.union(user2_purchases) return len(intersection) / len(union) if len(union) > 0 else 0 now here's my entry function: def recommend_products(user, k=5): similar_users = find_similar_users(user, k) recommended_products = set() for similar_user in similar_users: purchases = Purchase.objects.filter(user=similar_user).exclude(product__in=recommended_products) for purchase in purchases: recommended_products.add(purchase.product) return recommended_products Now, obviously that'd be really slow, I was thinking of using a copy of the data in another no-sql database. Now if user A purchase something, I copy the data to the other database, do the calculation and store … -
Django and Huey task issue, record in DB doesn't exist when the task is ran
I am testing Huey with Django and found one issue, tasks can't find the record in DB. Here is the code: # settings.py USE_HUEY = env.bool("USE_HUEY", False) HUEY = { "huey_class": "huey.RedisHuey", "name": "huey", "immediate": not USE_HUEY, "connection": {"url": REDIS_URL}, } # app/signals.py @receiver(post_save, sender=Post) def post_signal(sender, instance, **kwargs): from app.tasks import create_or_update_related_objects create_or_update_related_objects(instance.pk) # app/tasks.py @db_task() def create_or_update_related_objects(object_pk): post = Post.objects.get(pk=object_pk) ... This is running an async task but I am getting the error: app.models.Post.DoesNotExist: Post matching query does not exist. This is not correct, there is a post, and this task is running on a post_save signal. What is weird, is if I do something like this, it works fine: @db_task() def create_or_update_related_objects(object_pk): import time time.sleep(3) post = Post.objects.get(pk=object_pk) ... What am I doing wrong here? -
PYTHON AND DJANGO
How can I create a balance with Django and python connect it with the the user Python print("Django") -
How to create a form choiceField with selection a models TextChoices?
I have a custom User Model with some TextChoices, How can I get that Selection "continents" into a Form? so that i Render the html page with {{ form }} and the Choices appear? I have tried both Forms1.py & Forms2.py None of them Work. Models.py class CustomUser(AbstractUser): #USER MODEL # CHOICES FOR USER CONTINENT class Continents(models.TextChoices): EUROPE = 'EUROPE' , 'EUROPE' AFRICA = 'AFRICA' , 'AFRICA' SOUTH_AMERICA = 'SOUTH AMERICA' , 'SOUTH AMERICA' NORTH_AMERICA = 'NORTH AMERICA' , 'NORTH AMERICA' OCEANIA = 'OCEANIA' , 'OCEANIA' ASIA = 'ASIA' , 'ASIA' username=None nickname = models.CharField(max_length= 50, default = 'Not Set', blank=True) bio = models.TextField(max_length = 500 , blank=True , null= True , default= "Not Set") email = models.EmailField(max_length= 256 , unique=True) #USERS EMAIL ADDRESS USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() Forms1.py class CompleteProfileForm(forms.Form): bio = forms.CharField( label='Bio: ', widget = forms.Textarea( attrs = { 'class':'bioInput' } ) ) class Meta: model = CustomUser fields = ['bio', 'continent'] exclude = ['username'] continents = forms.ChoiceField(label='Continents', choices= CustomUser.Continents) Forms2.py class CompleteProfileForm(forms.Form): bio = forms.CharField( label='Bio: ', widget = forms.Textarea( attrs = { 'class':'bioInput' } ) ) continents = forms.ChoiceField( choices=CustomUser.Continents, widget = forms.Select( attrs = { 'class':'continent', 'selected':'Continent', 'id':'continent', } … -
Dokcer - issue with creating an image for Django project
i am trying to use Docker for an Django project but i got an issue when i try to build a image. the Dockerfile : # pull the official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt /usr/src/app RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]` the requirements.txt file :here the problem at the terminal is anyone had the same issue ? maybe i should not have a requirements.txt file ? -
Running Cron in Django on AWS Elastic Beanstalk without .ebextensions
I'm trying to run a function to count daily active users within a Django application using cron. All guides I can find seem to be many years old and they all reference using a .config file located within .ebextentions folder. My app has been running fine for a while but I haven't actually got a .ebextensions folder so wondering if there's a bad config or if I'm just doing something obvious wrong. Problem: Trying to run cron jobs within Django application running on Elastic Beanstalk in AWS environment. Ideally all set up within code and pushed with "eb deploy" but happy for a more manual solution using command line on the linux instance itself. Attempted Solution Reading through AWS documentation and various online sources I have created a "my_cron.config" file inside a ".ebextensions" folder with the following content: files: /usr/local/bin/my_cron_script.sh: mode: "000755" owner: root group: root content: | #!/bin/bash export $(cat /opt/elasticbeanstalk/deployment/env | xargs) source $PYTHONPATH/activate python3 /var/app/current/manage.py dailyCounts /etc/cron.d/my_cron: mode: "000644" owner: root group: root content: | 0 6 00 * * root /usr/local/bin/my_cron_script.sh >> /var/log/my_cron.log 2>&1 commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true When running "eb deploy" I get the following error: 2023-03-18 14:27:56 ERROR Updating Auto … -
Weird Django error when adding annotations annotations
I am trying to add comments to my django forum, but am running into an issue with annotate. whenever I add instructions to add comments com=Comment.objects.order_by("-published_date") it gives me an issue with a compleatly unrelated part of my template that checks the username. here is my view: def index(request): # check if there is any incomming data (comments) and make sure the user is authenticated POST = request.POST if POST != {} and request.user.is_authenticated: # a comment has been recived, time to move forward with creating it # figure out if the post even exists get_object_or_404(Post, id = POST['post_id']) # grab the user object user_active = User.objects.get(id = POST['user']) # grab the post object post_active = Post.objects.get(id = POST['post_id']) # make and save the comment n_comment = Comment(user = user_active, comment = POST['comment'], post = post_active) n_comment.save() posts = Post.objects.order_by("-published_date").annotate(num_likes=Count("likes"),com=Comment.objects.order_by("-published_date")) return render(request, 'home.html', {'posts': posts}) here is my model: class Comment(models.Model): comment = models.CharField(max_length=500) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') published_date = models.DateTimeField('date_published') and here is the error: Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.18 Python Version: 3.6.9 Installed Applications: ['core', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
Logout Django Rest does not Log user out
I am making my first app, I managed to make the login/register process however the logout function does not work. Despite sending back status code of 200, when I then try to log-in with a different user there is an error saying that a username key is already present. Here is my code views.py: from django.http import JsonResponse from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .models import Task, DailyTask from .serializers import TaskSerializer, DailyTaskSerializer, UserSerializer # Returns all possible routes for the API @api_view(['GET']) def getRoutes(request, format=None): routes= [ '/tasks', '/dailytasks', '/tasks/id', '/dailytasks/id', ] return Response(routes) # Registration/login and refresh tokens # Register function will handle registration @api_view(['POST']) def register(request, format=None): # POST requests will allow to create new users if request.method == "POST": serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Login function will handle logins @api_view(['POST']) def login_view(request, format=None): # Else if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username, password) # If user exists login if user is not None: login(request, user) # Otherwise return error else: return … -
How to get a value from number input in django?
I need to get a value from input with type number in django. When I tried to get that value, I got empty string. I expected getting a integer or number in string. HTML CODE: <form method="GET" action="" > <input type="number" name="ordered_amount" placeholder="amount" min="1" max="{{amount}}" value="1" /> <a href="/home/product/add/{{id}}/?q={{amount}}">Add to cart</a> </form> views.py: ordered_amount = int(request.GET.get('ordered_amount')) if request.GET.get('ordered_amount') != None else '' -
How do i pack a django module which has other django modules as dependencies?
I am developing a django module which is able to create UI interfaces to query a data repository. The module has an administration interface to configure the access to the data repository. For that it uses several other django modules such as crispy_forms. Following the tutorial at https://docs.djangoproject.com/en/4.1/intro/reusable-apps/, I created a module and uploaded it to test.pypi.org. I can add the module dependencies and upon installing my module, crispy_forms and all other dependencies are installed. This all works fine. But: in order to use my module, the user needs to make a lot of changes to the settings.py and urls.py files. Not only must my module be in INSTALLED_APPS but also my dependencies. Furthermore, to use crispy_forms, I need to specify a CRISPY_TEMPLATE_PACK setting. I always want this setting to be 'bootstrap4' and the user doesn't have to be aware of this setting. So my question is: Is there a way that the inclusion of my module can take care of these dependencies? What I need to have in settings.py: INSTALLED_APPS = [ 'my_module', 'django_tables2', 'crispy_forms', [...] ] CRISPY_TEMPLATE_PACK = 'bootstrap4' DJANGO_TABLES2_TEMPLATE = "django_tables2/bootstrap4.html" What I would like in settings.py: INSTALLED_APPS = [ 'my_module', [...] ] Is there a way … -
Could not build wheels for lxml, psycopg2, which is required to install pyproject.toml-based projects
I need to run this server on Django and React https://github.com/ozoneplatform/ozone/releases/tag/v8.0.0.0-GA I cloned it to myself, went to the "ozone-framework-python-server" folder, created a virtual environment and tried to install the libraries "pip install -r requirements.txt", but I got such errors I work for Windows Building wheels for collected packages: lxml, psycopg2-binary Building wheel for lxml (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [97 lines of output] - - - error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.35.32215\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for lxml Running setup.py clean for lxml Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 - - - It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try … -
TypeError: Field 'id' expected a number but got <QuerySet [<Store: X-Clusive Store>, <Store: GenFliX Exception Store>]>
Helo dev, can someone help me with this small but big problem. it returns this field id erro when a user create two store and try to add items to that store. if it is a single store, everything goes well and no erro will show but when the user create a store and try to add item to it, that is when this occurs. def itemupload(request): user = request.user items = Items.objects.filter(user_id = request.user) try: # store = Store.objects.get(author= user) store = Store.objects.filter(author= user) except Store.DoesNotExist: store = None if request.method =='POST': itemsforms =ItemsForm(request.POST, request.FILES) imageforms = ImageForm(request.POST, request.FILES) file= request.FILES.getlist('image') if all([itemsforms.is_valid(), imageforms.is_valid()]): item = itemsforms.save(commit = False) item.user = request.user item.save() item.store.add(store) for i in file: Images.objects.create(item = item, image =i) return redirect('index') return redirect('itemupload') imageforms =ImageForm() itemsforms = ItemsForm() context = { 'imageforms': imageforms, 'itemsform':itemsforms, 'items':items, } return render(request, 'jijiapp/itemform.html', context) this is model.py class Store(models.Model): name = models.SlugField(unique =True, max_length=50) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) create_date = models.DateTimeField(auto_now_add=True, null=True) discription=models.CharField(max_length=5000, null=True, blank=True) location =models.CharField(max_length=5000, null=True, blank=True) logo =models.ImageField(upload_to='logos/', default = '') def __str__(self): return '%s' % (self.name) class Meta: ordering = ['-name'] verbose_name_plural = 'Store' class Items(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null=True, blank=True) … -
Django model, how to auto-increment an object's value
So I have this Django model.py: class Product(models.Model): name = models.CharField(max_length=128) views = models.IntegerField(default=0, blank=True) I would like the views attribute, to have an auto randomly generated number. So something like this: class Product(models.Model): name = models.CharField(max_length=128) views = models.IntegerField(default=0, blank=True) def auto_views(self): return randint(0,200) and the views attribute will automatically take the value of the auto_views() function when creating a new product. In the same way as an auto-slug would work. -
Django Not Found: /media/ , GET /media/ HTTP/1.1" 404 2679
I am currently building a project which i have to use media. Since i have used media before i copy pasted everyting from my other project and altough the original is working my current project is not. I can upload and select fotos thru admin page but it does not show up in html My view: def index(request): dergi = Dergi.objects.all() kitap = Kitap.objects.all() yazar = Yazar.objects.all() siir = Siir.objects.all() template = loader.get_template("index.html") context={ "DERGI":dergi, "KITAP":kitap, "YAZAR":yazar, "SIIR":siir, } return HttpResponse(template.render(context, request)) My model: class Kitap(models.Model): isim = models.CharField(max_length=255) yazar = models.CharField(max_length=255) foto = models.ImageField(upload_to="foto", null=True) My url: urlpatterns = [ path('admin/', admin.site.urls), path("", include("index.urls")) ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' And my html: <img src="/media/{{ KITAP.foto }}" alt="" class="rounded-t-lg"> <img src="/media/{{ KITAP.foto.url }}" alt="" class="rounded-t-lg"> <img src="{{ KITAP.foto.url }}" alt="" class="rounded-t-lg"> i have tried all but it just gives me error: GET /media/ HTTP/1.1" 404 2679 or: Not Found: /foto/ -
Partial Problem from configuration settings in `$DJANGO_SETTINGS_MODULE`
Tree Directory: . ├── Pipfile ├── Pipfile.lock ├── README.md ├── Strawberry │ ├── init.py │ ├── pycache │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── catalog │ ├── init.py │ ├── pycache │ ├── admin.py │ ├── apps.py │ ├── migrations │ ├── models.py │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── foo.py ├── manage.py └── requirements.txt 7 directories, 19 files Dudes, it's Ok when I use: $manage.py check And I get the result without any problems, Errors and Exceptions. But when I write the same with django-admin: $ django-admin check I get Error: ModuleNotFoundError: No module named 'Strawberry' From this result we can now know that Django finds/see environment variable — $DJANGO_SETTINGS_MODULE but don't see directory with settings. But if I import `models` from `catalog.models` into `foo.py` then on run by python3 pipenv interpretator (Note: virtual environment is activated): $ python3 foo.py I get: ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings In this case Django not see $DJANGO_SETTINGS_MODULE, but $DJANGO_SETTINGS_MODULE has been created (in virtual environment) and its value is: $DJANGO_SETTINGS_MODULE=Strawberry.settings Summing up, I want to … -
Extending a base class ins django
I want to create base model for my questions named Question and extend it by any other question types: `class Question(models.Model): questionnaire = models.ForeignKey(to='Questionnaire', on_delete=models.CASCADE, related_name='questions') question = models.TextField() description = models.TextField(null=True, blank=True) media = models.FileField(upload_to='medias', blank=True, null=True) is_required = models.BooleanField(default=False) def __str__(self): return f'{self.questionnaire.name} - {self.question}'` and I want to extend it like this: `class OptionalQuestion(Question): multiple_choice = models.BooleanField(default=False) additional_options = models.BooleanField(default=False) # If multiple_choice is True, then max_selected_options and min_selected_options will be used max_selected_options = models.IntegerField(null=True, blank=True) min_selected_options = models.IntegerField(null=True, blank=True) # If additional_options is True, then all_options and nothing_selected will be used all_options = models.BooleanField(default=False, null=True, blank=True) nothing_selected = models.BooleanField(default=False, null=True, blank=True) def save(self, *args, **kwargs): if not self.multiple_choice: self.max_selected_options = None self.min_selected_options = None if not self.additional_options: self.all_options = None self.nothing_selected = None if self.nothing_selected or self.all_options: self.all_options = False self.multiple_choice = False super().save(*args, **kwargs)` It's all good in the first creation of migrations But the next time the Django wants me to provide a default value for 'question_ptr' field I don't even know what is this field I tryed making base class abstract and when making migrations Django shows me so many errors like this: question_app.TextAnswerQuestion.questionnaire: (fields.E305) Reverse query name for 'question_app.TextAnswerQuestion.questionnaire' clashes with reverse … -
Django and Nginx with Docker
I am trying to use Nginx with Django and Docker in my project. On my computer, I can run the app with docker-compose but I cannot figure out how to use docker-compose to deploy to the docker hub with GitHub actions. What I have done instead is use WhiteNoise and not Nginx to be able to manage my static and media files. Here is the repo of what is working and any guidance will be greatly appreciated. If using WhiteNoise is also acceptable and has no drawbacks that would be good to hear as I have seen different views in that regard. -
How to make every subsequent page retain the slug in the URL and append URI
I'm making a Django website and I have 2 apps within it. Once the user is logged in and navigates to the dashboard area of the site I would like them to select a tenant to manage and for every subsequent menu button clicked to be in the context of that tenant. For example a user logs in with access to a 'tenant1'. I would like to the urls to all follow the format http://mywebsite/tenant1/. So far I've managed to create a tenant selector page successfully and navigate to the dashboard from there by adding the slug. The issue is every subsequent page no longer contains the slug, and I'm not sure how to access the slug from the previous page to be able to access it in the href. Even so I can see a solution that relies on the previous pages slug to be troublesome as some navigation options don't require the slug, just the user info. Here is my URLs.py urlpatterns = [ path('', tenant_selector.as_view(), name='tenant_selector'), path('<slug:slug>/dashboard', Dashboard.as_view(), name='Dashboard'), path('<slug:slug>/config/', config_view.as_view()), path('<slug:slug>/run_func/', loading_view.as_view()), path('profile/', user_update_view.as_view(), name='Profile'), path('success', Success.as_view()), ] Below is the Views.py class Dashboard(TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['total'] = staff_sync_model.objects.count() … -
How to run django runserver in a background thread?
I need to run django runserver in the background to enable tests with selenium and pytest. A similar functionality is provided by pytest-django's live_server. But using live_server flushes the database after each test which implies recreation of tables and migrations on each test which is redundant and unacceptably slow. My main objective is to create a database and test user, login with selenium once and run all tests which is clearly impossible using pytest-django's live_server. As per the docs: you need to repopulate your database every time a test starts, because the database is cleared between tests and there is no way around it. So the solution is to run a django server in the background and use it instead. Here's a couple of approaches: Using a thread: import os from pathlib import Path from threading import Thread from django.core.management import call_command from django.core.wsgi import get_wsgi_application def start_server(src): os.chdir(src) os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'{Path(src).name}.settings') os.environ['DB_NAME'] = 'test_db.sqlite3' get_wsgi_application() call_command('migrate') call_command('runserver') def run_server(src): process = Thread(target=start_server, args=[src], daemon=True) process.start() if __name__ == '__main__': run_server('/path/to/myproject-root') which results in an error: Traceback (most recent call last): File "/usr/local/Cellar/python@3.11/3.11.2_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Users/user/Library/Application Support/JetBrains/PyCharm2022.3/scratches/scratch_3.py", line 15, in start_server call_command('runserver') File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 198, … -
accessing django admin using angular frontend
I want to access django admin using angular frontend. I am not sure if its even possible. I am using angular as my frontend (angular ver:8.0) and django as my backend. I have also added admin in my urls.py file as given below from django.urls import path, re_path from django.contrib import admin from django.views.debug import default_urlconf router = routers.DefaultRouter() urlpatterns = [ url(r'^', include(router.urls)), re_path(r'^superadmin/', admin.site.urls), re_path(r'^$', default_urlconf),] but when open http://localhost:4203/admin/ it doesnt open django admin panel. (http://localhost:4203/ is my local angular server) How can I achieve this? Is it even possible to use django admin panel with angular frontend? Please help. -
How can I get my AJAX button press request to work in my Django environment?
So basically I want to use a javascript string variable in a python function, and then return it back to a javascript variable. To start, I have a html element where a string is placed in it. <h2 id="output"></h2> My plan is to pull that value from the HTML (shown in the AJAX statement below): var word = $("#output").val(); and use AJAX to send it to the backend for a python script that checks whether or not the word is a real English word (returning true/false). With the AJAX code I have, I keep getting returned an undefined variable. Here is the AJAX code: $(document).ready(function() { $('#submit_word').click(function() { var word = $("#output").val(); $.ajax({ url: '{% url 'wordgame' %}', //not sure type: 'POST', dataType: 'json', data: {word:word, csrfmiddlewaretoken: "{{ csrf_token }}",}, success: function(response) { var word_result = JSON.parse(response.result); console.log(response.result); $("#check-word").text(word_result); }, error: function(response) { console.log(response.result); } }); }); }); As well as my views function: def fetch_word(request): word = request.POST.get('word') result = check_if_word_in_dictionary(word) return JsonResponse({'result': result}) Whenever I click the button, it executes the 'error' part of my ajax statement: error: function(response) { console.log(response.result); } Which prints 'undefined' in the console. -
get_absolute_url is NOT working on the combined queryset, How can l do it?
I want to use get_absolute_url but it shows nothing on the combined queryset It returns an error that: Page not found Below are my codes #Action/models.py class Action(models.Model): ...... def get_absolute_url(self): return reverse('act',args=[self.slug]) #adventure/models.py class Adventure(models.Model): ...... def get_absolute_url(self): return reverse('adves',args=[self.slug]) #racing/models.py class Racing(models.Model): ...... def get_absolute_url(self): return reverse('act',args=[self.slug]) #puzzle/models.py class Puzzle(models.Model): ...... def get_absolute_url(self): return reverse('puz',args=[self.slug]) Then view of my combined queryset #Others/views.py from itertools import chain def games(request): ... ..... act_games=Action.objects.all() adv_games=Adventure.objects.all() puz_games=Puzzle.objects.all() rac_games=Racing.objects.all() games= list(chain(act_games,adv_games,puz_games,rac_games)) context={ 'games':games, } return render(request,'combined.html', context) #combined.html ....... {% for game in games %} <div class="col"> <a href="{{ game.get_absolute_url }}"> {{ game.game_name }} </a> {% endfor %} ..... My Expections When I refleshed the page l found no error. But when I tried clicking on the link, It returned an error that Page not found Now l would like to know how make it pass successfully and take me to the slug link added when creating the object. E.g When clicking on the action game on the combined page when it was created in the Action models it must redirect me to the slug link page but just returns me 404 Page not found