Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
logout give me error in django --- maximum recursion depth exceeded [closed]
in views from django.contrib.auth import logout def logout(request): logout(request) return redirect('login/') in url path('logout/', views.logout, name="logout"), in html <a href="{% url 'logout' %}">logout</a> error RecursionError at /logout/ maximum recursion depth exceeded RecursionError at /logout/ maximum recursion depth exceeded -
django annotate qs by objects using object_id field
Got user and role. How could i get annotated roles qs by users? from django.db import models, F, Q class User(models.Model): pass class Role(models.Model): ... user_id = models.PositiveIntegerField( verbose_name='Related object ID' ) I want to do something like this: roles = Role.objects.all() roles = roles.annotate(user=Q(User.objects.get(id=F('user_id')))) for role in roles: print(role.user.id) => 123 Traceback: FieldError: Cannot resolve keyword 'user_id' into field PS: Please, don't ask me to do FK or MtM, I need exactly this relation. -
If i have a my cordinate , i want to get every cordinated in the radius of 5 km
i have the database of many events ,i want filter out the events happening within 5 kms of radius from my location.Currently i am doing it using haversine running every event in a for loop,which is very time consuming can anyone suggest an alternative for this method The method i am currently using is haversine in a for loop for comparing every event and thats not a proper way -
How do I solve Installation of PyDictionary error?
I am trying to build a simple word search dictionary using django and when I install pyDictinary which is a django package I get this error: 'python setup.py egg_info did not run successfully.'. How can I solve this, or how other way can I get to use the package? I am made to know that pip has no problem. I run "pip install pyDictionary" on vscode terminal -
djongo RunPython in database migration
There's a django app with djongo as database driver. I want to add custom migration using RunPython. But I can't understand how to reach pymongo client. Here's the code: from django.db import migrations def _custom_migration(apps, schema_editor): db = ... # what to put here? db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}]) class Migration(migrations.Migration): operations = [ migrations.RunPython(_custom_migration), ] -
How to make sef image link with uploaded tinymce in django?
I published my django site but everyday i am finding new problems :) Today i realised my images in the article has no slugify link. Forexample in this page https://www.endustri.io/monokristal-gunes-paneli-nedir-calisma-prensibi-avantajlari/ This image has url like this. How can i make this image url like endustri.io/(image or media)/image-name.webp data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApQAAAGVCAMAAAB3pZE2AAAC2VBMVEXz8/Tz8/QoKCktLS4iQX0iRYI6OjwgNmz///8xMTMhQ38hSIchSoo2NjdYWFohPnchOnIhQn5/f4EhR4W+H3DMzM6mpqchRYQhSIYiRoPI0eEhRIJeXl9iYmTX19fIz97p6eoAAACbnaBuRO/Wi/Sf2N27f+CaPUOkapdYxS6xil1jFKrWOUWscotY5Rah2j1DpGqXWMUusYpdb5AlujV99XpgrKAAAAAElFTkSuQmCC -
Store flutter ocr image data to Django SQL [closed]
I have created a ocr image reader and it's read the image and convert to word but how to store the word data to Django data sqlbase .. Thanks 🙏 Pls help urgent 🙏🙏🙏 -
Selenium test failed with RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
I'm running tests with selenium and i want to test the admin panel in django so i made the below tests import pytest from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By #create pytest database with admin credintials @pytest.mark.selenium def test_create_admin_user(create_admin_user): assert create_admin_user.__str__() == "admin" @pytest.mark.django_db def test_dashboard_admin_login(live_server, create_admin_user, firefox_browser_instance): browser = firefox_browser_instance browser.get(("%s%s" % (live_server.url, "/admin/login"))) username = browser.find_element(By.NAME, 'username') password = browser.find_element(By.NAME, 'password') submit = browser.find_element(By.XPATH, '//input[@value = "Log in"]') username.send_keys("admin") password.send_keys("admin") submit.send_keys(Keys.RETURN) assert "Site administration" in browser.page_source fixtures: import pytest @pytest.fixture def create_admin_user(django_user_model): """ Return admin user """ return django_user_model.objects.create_superuser("admin", "admin@admin.com", "admin") confest: pytest_plugins = [ "core.test_setup.fixtures", "core.test_setup.selenium", ] when i run the tests it appears that 1 passed, 1 failed the one passed is test_create_admin_user and the one failed is def test_dashboard_admin_login Error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. -
Truncate consecutive values in a Django (TimescaleDB) QuerySet
I have a QuerySet consisting of a timestamp and a boolean value. When there are consecutive repeating values, I'd like to truncate them to only show the first (and maybe the last one too, but not mandatory). e.g. the given queryet <TimescaleQuerySet [ {'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 11, 787303, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 27, 7, 971506, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 9, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}] should truncate to <TimescaleQuerySet [ {'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}] I'm breaking my head over this. Is there an elegant way to achieve this? I want to avoid looping over the whole queryset, it's just too slow when theres >1000 results. -
custom message if there isnt any record to show in django-template
Hello there im trying to show a custom message like "Doesnt exists" if there isnt really any record to show and ignore having None in the template for empty records Template : <div class="col-md-6 col-sm-12 col-xs-12 form-group pull-right "> <label style="color : blue;" class="control-label col-md-5 col-sm-3 col-xs-12 pull-right size_Style"><i class="fa fa-circle" style="color : blue;" aria-hidden="true"></i> knowledge cost :</label> <span class="col-md-12 col-sm-12 col-xs-12 form-group pull-right colorfull"> {{ special_knowledge.knowledgecost|safe }} </span> </div> <div class="col-md-6 col-sm-12 col-xs-12 form-group pull-right "> <label style="color : blue;" class="control-label col-md-5 col-sm-3 col-xs-12 pull-right size_Style"><i class="fa fa-circle" style="color : blue;" aria-hidden="true"></i> knowledge cost percemtage :</label> <span class="col-md-12 col-sm-12 col-xs-12 form-group pull-right colorfull"> {{ special_knowledge.knowledgecost_percent }} </span> </div> based on the given HTML the first Field would Be None becuase i dont have any record for it in my db , so is there any more efficient way than using if for each record ? i tried this method for all to handle any empty record {% if special_knowledge.knowledgecost %} {{ special_knowledge.knowledgecost|safe }} {% else %} Doesnt exist {% endif %} -
Unitest DRF with CONTEXT
I am wondering if anyone could help me with the appropriate way to create a unitest in DRF when using context inside a serializer. as you can see in the serializer below, I am adding a field called distance to my serializer. class CompanySerializer(serializers.ModelSerializer): """Serializer for companies.""" distance = serializers.SerializerMethodField() class Meta: model = Company fields = ['id', 'company_name', 'lat', 'long', 'logo', 'distance'] def get_distance(self, company): """Return context""" print(self.context) return self.context['distances'][company.pk] Then when calling the unitest I get an error: KeyError: 'distances' COMPANY_URL = reverse('company:company-list') def test_company_list_limited_to_user(self): """Test list of companies is limited to authenticated user.""" other_user = create_user( email='other@example.com', password='password123' ) create_company(user=other_user) create_company(user=self.user) res = self.client.get(COMPANY_URL) companies = Company.objects.filter(user=self.user) serializer = CompanySerializer(companies, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) Is there a better way to write this test, so it can pass? I did check and the context distance is create and passed to the serializer with no issue, but the test is not passing :/ Tks a lot! Kind regards Victor Almeida -
manage.py invaild syntax error in kali server
I have a django project I want to publish it on an ubuntu server when I activate the virtual environment and make python manage.py runserver: File "manage.py",line 17 )from exc ^ SyntaxError:invalid syntax I'm getting the same error in every command about manage.py, not just the run server. I tried the makemigrations and migrate commands, it didn't work. I activated the virtual environment, it still didn't work I deleted django and reinstalled it still didn't work -
Handling form fields in django for logged in user
Im trying to handle the existing name of a Category, so that users wont be allowed to create 2 categories with the same name, but at the moment its taking all categories from the database, not only for the logged-in user. I dont know how and where to implement request.user. I`m building an inventory app where everyone creates their own categories and adds items. Thank you. This is my model: class Category(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE, related_name='category', null=True) name = models.CharField(max_length=100, null=False, blank=False) slug = models.SlugField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now=True) class Meta: ordering = ['-timestamp'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('category_detail', kwargs={'slug': self.slug}) This is my form: class CategoryForm(forms.ModelForm): add_category = forms.BooleanField(widget=forms.HiddenInput, initial=True) class Meta: model = Category fields = ['name'] def clean_name(self): name = self.cleaned_data.get('name') if (name == ""): raise forms.ValidationError('This field cannot be left blank') for instance in Category.objects.all(): if instance.name == name: raise forms.ValidationError('There is a category with the name ' + name) return name This is my view: @login_required def index(request): categories = Category.objects.filter(user=request.user) items = Item.objects.all() add_item = ItemForm() add_category = CategoryForm() query = None if request.method == 'POST': if 'add_item' in request.POST: add_item … -
Django dj-rest-auth (django-allauth) redirection doesn't work, however, LOGIN_REDIRECT_URL is set
I'm using Django 4.1 (Djoser doesn't work with 4.x) and dj-rest-auth (if I'm not mistaken, registration is provided by django-allauth module). What am I trying to achieve is getting new user to a profile creation page ('/api/v1/new_hero/' endpoint), right after he signs up. Without any email verification, just right into it. But for now, with all theese settings, after registration, django keeps the user on the same ('auth/registration/') page with tokens demonstration and other stuff. By the way, situation keeps similar with loginning. How am I supposed to direct the user to a target page? settings.py: DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' REST_USE_JWT = True JWT_AUTH_COOKIE = 'jwt-auth' SITE_ID = 1 LOGIN_REDIRECT_URL = '/api/v1/new_hero/' ACCOUNT_SIGNUP_REDIRECT_URL = '/api/v1/new_hero/' ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = True ACCOUNT_EMAIL_VERIFICATION = 'none' items/urls.py urlpatterns = [ path('items/', ItemsListCreateView.as_view(), name='list_items'), path('items/<int:pk>/', ItemDetailView.as_view(), name='update_item'), path('heroes/', HeroListView.as_view(), name='list_heroes'), path('new_hero/', HeroCreateView.as_view(), name='create_hero'), path('heroes/<int:pk>/', HeroDetailView.as_view(), name='update_hero'), path('classes/', HeroClassListCreateView.as_view(), name='list_classes'), path('weapons/', WeaponClassListCreateView.as_view(), name='list_weapons'), # path('reg/', Registration.as_view(), name='custom_registration'), ] I tryied different django-allauth settings, checked correctness of INSTALLED_APPS, AUTHENTICATION_BACKENDS and other sections of settings.py, and it all end up here, with me writing a question. -
s3 bucket does not collect created pdfs in media folder django/aws
I just deployed my django application to a beanstalk server linked to an s3 bucket in the aws console. In my application pdfs from each post are created and forwarded to the media folder in the subfolder "postings". However, in the bucket no such folder is created and the pdfs also don't show up anywhere else. only the uploaded images of the post is there. How do I get the pdfs there? also, I get an ValueError now for the Image in the PDF (which is the uploaded image, and which was working just fine before adding the bucket). How do I get it to work again? I think both problems are due to some connection missing... This is my first project deploying to aws. Please help me out with a little explanation. Here is the code of the created upload and pdf: views.py def post_create(request): if request.method == 'POST': form = PostCreateForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['num_post'] = Post.objects.count() + 1 Post.objects.create(**form.cleaned_data) else: form = PostCreateForm() return render(request, 'index.html', {'form': form}) def upload(request): if request.method == 'POST': image = request.FILES.get('image_upload') caption = request.POST['caption'] num_post = Post.objects.count() + 1 new_post = Post.objects.create(image=image, caption=caption, num_post=num_post) new_post.save() # create pdf buffer = io.BytesIO() … -
Problem with running maintenance mode in my Django and React apps that are stored on Azure Web App for Containers?
I have deployed Django and React application on Azure. I am using Web Application for Containers. One Web App is for Django and second one is for React (CORS headers are properly confiured, both apps are connected to each other). Docker images are stored on Azure Container Registry. I am looking for an option to switch both apps to Maintenance mode when doing some maitenance things or deploying. I was thinking abouting creating extra env variable called MAITENANCE_MODE in Application settings where I can switch manually from false to true and then it switches the mode on websites automatically. Another idea would be to create some webjobs but I am not familiar with these topics and I am asking for an advice on how to do it or at least where to look for such solution. -
place an order for a product in django
I have some products on my website And I want customer to place an order when clicking on a specific product ... and then the order form contains charfield or something from that product model to identify the order for which product is. How can I do this Thanks 😘☺️ I did the products model and I displayed them And I did the order model and I could get the data from user But I stil can't make a correct order -
Django modeltranslation and AutoSlugField
I'm struggling with combination of AutoSlugField (from django-extensions) and ModelTranslation. class Article(models.Model): title = models.CharField(max_length=255, default="") slug = AutoSlugField( populate_from=[ "title", ], overwrite=True, ) Make perfect sense without model translation. Unfortunately, if title and slug fields are translatable it does not work out of the box. The migration file created by ModelTranslation contains description for AutoSlugField: migrations.AlterField( model_name="article", name="slug_de", field=django_extensions.db.fields.AutoSlugField( blank=True, editable=False, null=True, populate_from=["title"] ), ), migrations.AlterField( model_name="article", name="slug_en", field=django_extensions.db.fields.AutoSlugField( blank=True, editable=False, null=True, populate_from=["title"] ), ), But slug_en should be based on title_en and slug_de should be based on title_de. Is it possible to enforce such behavior? -
login don't work in django user not login
login dont work i don't where the problem please help. https://youtu.be/tUqUdu0Sjyc ----- Dennis Ivy -- video learn in youtube views from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'post': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') return render(request, 'login.html') html <form method="post"> {% csrf_token %} <input type="username" name="username"> <input type="password" name="password"> <input type="submit" name="submit"> </form> url path('login/', views.login, name="login") -
How to update ManyToManyField when source model is deleted?
Consider this model.py for a MariaDB-based setup: class User(models.Model): email = models.CharField(max_length=255) class Newsletter(models.Model): subscribers = models.ManyToManyField(User, blank=True) title = models.CharField(max_length=255) If I delete a User, I want the reference to it removed from any Newsletter's subscribers list. I do not want to delete the Newsletter itself at any point, even if the subscribers list is empty. Is this possible automatically with some Django feature like on_delete=REMOVE_FROM_LIST? -
if I pass hyderabad2 or hyderabad3 or Hyderabad in parameter then I want to get whole zeroth object in response. Could you please help me
data: string 0: object name: Hyderabad child: string 0: object name: hyderabad2 1: object name: hyderabad3 I am expecting whole object when name match found -
How do you implement csrf protection between Django and Php
If you wish to port backend endpoints from php to Django while the front end is still in php, how do you implement csrf protection in that case? There won’t be any way for each to have access in a secure manner to the same key correct? I also wish to run each eventually in their own kubernetes pod. -
How to let users download an excel file in a specific path in Django?
I am a beginner in Python Django. I am trying to let users download an excel file in a specific path in Django. My views.py is as follows. As you can see, I want to let user download OOOO.xlsx in the path /mysite/upload/. def download_file(request): # Define Django project base directory BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Define file name filename = 'OOOO.xlsx' # Define the full file path filepath = BASE_DIR + '/mysite/upload/' + filename # Open the file for reading content path = open(filepath, 'r') # Set the mime type mime_type, _ = mimetypes.guess_type(filepath) # Set the return value of the HttpResponse response = HttpResponse(path, content_type=mime_type) # Set the HTTP header for sending to browser response['Content-Disposition'] = "attachment; filename=%s" % filename # Return the response value return response My urls.py is as follows. urlpatterns = [ path('admin/', admin.site.urls), path('',views.index), path('download/', views.download_file), ] However, it keeps showing an error like this on my HTML page. <> Please help me to find the bug. -
Django Channles: Websocket connection failed
I am using Daphne + Gunicorn + Nginx for my django deployment. Following this tut., Everything worked fine on Localhost but once I publish to Ubuntu server, Connection to websocket failed. Question How can i log errors/warning/issues causing websocket connection failure. It will be easy to debug application or server. Package and versions: django==3.2.4, channels==3.0.5, channels-redis==3.4.1, daphne==3.0.2 -
I am trying to send data from my flutter application to my local api made with django
here you can see views.py, models.py and url.py and you can see here my flutter postdata function with static values when i call my function it's dont work and it's return status.code error 400 but when i try to post data using postmant it's work