Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I prefetch ForeignKey of the ModelInline in Django Admin?
For example, I have following models: class Person(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class SNS(models.Model): name = models.CharField(max_length=255) # for display in raw_id_fields def __str__(self): return self.name class PersonSNS(models.Model): person = models.ForeignKey('Person', related_name='sns') sns = models.ForeignKey('SNS') url = models.CharField(max_length=255) And in admin.py class PersonSNSInline(admin.StackedInline): model = PersonSNS fields = ('sns', 'url') raw_id_fields = ('sns',) @admin.register(Person) class PersonAdmin(admin.ModelAdmin): inlines = [PersonSNSInline] def get_queryset(self, request): return super(AppAdmin, self).get_queryset(request).prefetch_related('sns') However, django-debug-toolbar shows the executed SQL like: SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` IN (1, 2, 3, 5, 6) and SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 1 Duplicated 5 times. SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 5 Duplicated 5 times. SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 6 Duplicated 5 times. SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 3 Duplicated 5 times. SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 2 Duplicated 5 times. I'm wondering why the PersonSNSInline still query the database one by one though I have prefetch the related data. -
Django testing combinatory
i´m making some database testing case. We need to make a all test case which only change the insert data. class Tests_All(TransactionTestCase): reset_sequences = True def test_car_pk(self): car = Car.objects.create(company="car_company", type="electrical",type_owner="regular") self.assertEqual(car.pk, 1) So, i have a company choose, type choose and type_owner choose For example, we have 12 Companys, 5 Type, 2 type_owner. A full test should be 12x5x2 = 120 Test. This type of test maybe is not a good practice. But the main question is, there is method in django to make the test ? I read the documentation and didn´t get a example. Is like a general test make with all the case by changing the value of the parameter (compnay,type,type_owner) -
Django DoesNotExist - Matching Query doesn't exist
I'm working on a Django(1.4) and Python (2.7) project in which I have a custom model for user to get loggedin. Here's my model: from models.py: class User_table(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, null=True) emailid = models.EmailField() user_name = models.CharField(max_length=100) password = models.TextField() user_type = models.CharField(max_length=20) # True means drive is available for delivery status = models.BooleanField(default=True) vehicle_no = models.CharField(max_length=50, blank=True, null=True) gender = models.CharField(max_length=10) profile = models.ForeignKey(AddedFile, on_delete=models.CASCADE, null=True, related_name='profile') uploaded_document = models.ForeignKey(AddedFile, on_delete=models.CASCADE, null=True, related_name='document') approval_status = models.BooleanField(default=False) login_try = models.IntegerField(default=0) is_active = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.id) And here's my view: From views.py: def mainlogin(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] try: obj = User_table.objects.get(user_name=username, emailid=email) verify_password = '' try: verify_password = handler.verify(password, obj.password) except Exception as e: print(e) if verify_password is True: request.session['user_id'] = obj.id request.session['user_type'] = obj.user_type user_name = obj.first_name + ' ' + obj.last_name request.session['user_name'] = user_name if not obj.approval_status: return HttpResponse('Your account is not confirmed by administration.') obj.is_active = True obj.login_try = 0 obj.save() return redirect(home) else: try: obj = User_table.objects.get(user_name=username, emailid=email); if obj: s = obj.login_try s = s + 1 obj.login_try … -
Django default root page stops working when I add my app to urlpatterns in urls.py
I am new to Django and only followed one tutorial on Visual Studio which worked fine. Now I was trying to create another project on PyCharm and am facing the below problem. the default Django template sets up fine in Pycharm and I see the default root/landing page when I run the project. but the moment I add a url for my app in urls.py the default Django page stops working, although both the admin url and myapp urls work fine. my Urlspatterns is provided below: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls', namespace='myapp')), ] the moment I remove the line the default Django landing page starts working again. I have tried searching online but was unable to find an explanation. Posting it here because I would really like to know why this happens. -
How to build django template GET request arguments?
Django version >= 2.0.0 for example. in the urls.py, I have a register a view function: path('detail/<str:db_name>/<str:collection_name>', views.detail, name='detail') and in the django template, I want to use the url function to build this url: {% url 'detail' db_name collection_name %}, this will product url: /detail/db_name/collection, but I want the url is /detail/db_name/collection?per_page_count=15. so, How can I build the GET request arguments by url. thanks. -
How do i setup django-channels for two geogrphically located server?
We have two server running in two different region for example on in US and one in Europe. We have a django channels, redis, uwsgi and nginx setup. Issue is how do i set up channel server to serve both the server. Right now both the servers are running separately. asgi-redis==1.4.3 channels==1.1.8 daphne redis-server =4.0.9 -
How to do the same in Django (Python)?
I want to add conditions to my queryset How to do the same in Django (Python)? My example code.. #This is example model in php... class MY_MODEL { function search() { $params = $this->input->post('params'); if(@$params['contact']) { $this->db->where('contact', $params['contact']); } return $this->db->get('my_table'); } } # How to do the same in Django (Python) ?? ... my_field = self.request.GET.get('my_field', '') try: return MY_MODEL.objects.filter( if @my_field: Q(my_field__icontains=query) ) except: return MY_MODEL.objects.all() ... Regards! -
Adapter or Wrapper in django for orm
I wanted to find a way to create a sort of Model adapter, I'll explain better, class Question (models.Model): question_text = models.CharField (max_length = 200) pub_date = models.DateTimeField ('date published') def __str __ (self): return self.question_text def was_published_recently (self): return self.pub_date> = timezone.now () - datetime.timedelta (days = 1) class Choice (models.Model): question = models.ForeignKey (Question, on_delete = models.CASCADE) choice_text = models.CharField (max_length = 200) votes = models.IntegerField (default = 0) def __str __ (self): return self.choice_text I do not want to inherit from models.Model but I would like something of mine, possible to manage and to change structure without having to go crazy on these codes. another possibility was with the Decorators or think of them as a JPA in java es: @Entity class Question: @CharField (max_length = 200) QUESTION_TEXT that is, in practice I would not go for models.Model but have something of my own interchangeable at any time -
Django alluth customisation- I want to add a sports option which multi checkbox selection
Django alluth customisation- I want to add a sports option which can have handball,volleyball,Soccer(5,7) and Basketball(5,7) all implemented with checkbox but I want sports field to hold all values.Please suggest how to implement that as I am struggling to customise alluth. Please find the image for reference as I want to implement that in Django. Checkbox that needs to be implemented -
Create or Alter PostgreSQL Table to ensure Django Models match
I ran into an annoying issue today during the development of a Django project where I was attempting to move between a testing database and a development database, and I cannot seem to figure out a solid way to go about fixing issues with migrations. Let's call my 'test' DB: testDB and my 'dev' DB: devDB I was accessing testDB as usual through Django settings.py and I made migrations adding the clientID field you see in the code below. Then, I decided to swap to devDB in my Django's settings.py to run python manage.py migrate, and my clientID field is not added to the new DB. When I run python manage.py makemigrations I get, as expected, "no changes detected". Just so this is noted, I am using the django-reset-migrations package from PyPi after I make migrations so the migrations folder does not get complicated and everything is stored in a single 0001_initial.py migrations file. I am not seeing a better way to handle this issue than by writing my own script that ensures all Model tables exist in whatever DB I am connected to, and that all Model fields are located in each table, else the table is altered and … -
How to overwrite instance/form values in clean method of Django 2.0?
How to overwrite instance/form values in a clean method of Django 2.0? class LocationForm(forms.ModelForm): def clean(self): # do some work if check_condition: raise ValidationError # pass validation checks # overwrite new field value instance.field = new_val The overwritten field should be overwritten and take effect in the new model instance. The reason I want to do this in the clean method is so that I can raise validation errors within the form. Using a model's save method works, but raising a validation error does not render errors on the form in django template. -
How to display media files stored in Amazon S3?
I have integrated Amazon S3 with my Django app. A media folder has been created in my S3 bucket, and when users upload a file it shows up there just fine. What I'm unclear about is how to display these files in the template. Currently the code is: <img src="https://s3.console.aws.amazon.com/s3/buckets/myprojectbucket/media/{{ model.file }}"/> I've also tried: <img src="{{ model.file }}"/> Another thing to keep in mind is when I try to access these files from the S3 account I get this output. Not sure if this is a permissions issue or what. This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>SDFS9DF87S9D8F3711</RequestId> <HostId>oadsfupa87er0q9we8ri234987P348DSsdfQ9OIYoweiuroweiru</HostId> </Error> Any help would be appreciated. -
Docker together with Django and Postgres
Having following configuration placed in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql$ 'NAME': 'database1', # Or path to database file if $ # The following settings are not used with sqlite3: 'USER': 'database1_role', 'PASSWORD': 'database1_password', 'HOST': 'database1', # Empty for localhost throu$ 'PORT': '5432', # Set to empty string for defaul$ 'ATOMIC_REQUESTS': True } } docker-compose.yml: version: '3' services: # web container, with django + gunicorn djangoapp: build: . environment: - DJANGO_SETTINGS_MODULE volumes: - .:/opt/services/djangoapp/src - static:/opt/services/djangoapp/static - media:/opt/services/djangoapp/media networks: - database1_network - nginx_network depends_on: - database1 # reverse proxy container (nginx) nginx: image: nginx:1.13 ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/opt/services/djangoapp/static - media:/opt/services/djangoapp/media networks: - nginx_network depends_on: - djangoapp # database containers, one for each db database1: image: postgres:10 environment: POSTGRES_USER: database1_role POSTGRES_PASSWORD: database1_password POSTGRES_DB: database1 ports: - "5432" volumes: - database1_volume:/var/lib/postgresql/data networks: networks: - database1_network networks: database1_network: driver: bridge nginx_network: driver: bridge volumes: database1_volume: static: media: I still do receive following error communicate whenever I am trying to access my site using webbrowser: OperationalError at / FATAL: password authentication failed for user "database1_role" Previously I used to have a message that my database does not even exist / psycopg2 cannot make any connections … -
Django Rest Framework How to use UUID as primary key - HyperlinkedRelatedField
I've designed a basic app using DRF and have two simple models, Event and EventSet. EventSets can contain 1 or more Events, and Events can only belong to one EventSet. I setup my models, serializers and views and everything was working correctly. I went back into my code to change the primary key from the default auto increment field 'pk', to a primary key called id, with a UUID as it's type. Deleted tables and ran migrations. Now when I try and browse my API, I receive this error: ImproperlyConfigured at /events/ Could not resolve URL for hyperlinked relationship using view name "event-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. I've tried many different fixes, such as adding lookup_field='id' as an argument in my serializers.HyperinkedModelSerializer without any luck. What am I doing wrong here? models.py class EventSet(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) start_date = models.DateTimeField() end_date = models.DateTimeField() published = models.BooleanField(default=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) event_set = models.ForeignKey( EventSet, related_name='events', on_delete=models.CASCADE) start_date = models.DateTimeField() end_date … -
Understanding Django and Django FormView
I am trying to create a Django web app that accepts text in a form/textbox, processes it and redirects to a webpage showing the processed text . I have written a half-functioning app and find de-bugging quite challenging because I don't understand most of what I've done. I'm hoping you will help me understand a few concepts, Linking to resources, also appreciated. Consider this simple model: class ThanksModel(models.Model): thanks_text = models.CharField(max_length=200) Is the only way to set the text of thanks_text through the manage.py shell? This feels like a pain if I just have one piece of text that I want to display. If I want to display a webpage that just says 'hi', do I still need to create a model? Consider the view and template below: views.py class TestView(generic.FormView): template_name = 'vader/test.html' form_class = TestForm success_url = '/thanks/' test.html <form action = "{% url 'vader:thanks'%}" method="post"> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit"> </form> I need to create another model, view and html template and update urls.py for '/thanks/' in order for the success_url to redirect correctly? (That's what I've done.) Do I need to use reverse() or reverse_lazy() the success_url in … -
Django CreateView form not getting inserted
I'm fairly new to this, but what I'm trying to do is get my form to display (injected as part of a template) in another view. In developer tools I see the HTML for my included page (polls/_poll_form.html), but not the form. I would appreciate it if someone could point me in the right direction. models.py class Poll(models.Model): poll_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) topic = models.ForeignKey( Topic, related_name = 'polls', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) last_updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( 'polls:single', kwargs={'pk':self.pk} ) class Meta: db_table = 'polls' ordering = ['last_updated_at'] views.py class CreatePoll(LoginRequiredMixin, generic.CreateView): template_name = 'polls/_poll_form.html' model = Poll _poll_form.html (injected template) <div class="container poll-form-header"> <p class="text-center">Get Started</p> </div> <form class="create-poll-form" action="{% url 'topics:single' pk=topic.topic_id %}" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-dark float-right"> </form> topic_detail.html {% extends "topics/topic_base.html" %} {%block topics_content %} <div class="col-md-12 list-group polls-list"> <div class="container new-poll-button"> <a class = "btn btn-dark float-right mt-2" data-toggle="collapse" href="#poll-form" role="button" aria-expanded="false">Create Poll</a> </div> <div class="collapse mt-2 new-poll-form" id="poll-form"> <div class="card card-body"> {% include "polls/_poll_form.html" %} </div> </div> {% if topic.polls.count == 0 %} <br> <div class="container no-polls-message"> … -
How do we add a html canvas imgurl after clicking the submit button to django
HI I have created a canvas image like this imgUrl = canvas.toDataURL('image/png'); Upon submit how can I add this to django ? -
Recieve GET when submitting form
I can't see why I'm getting request.method == GET when submitting a form. I have tried different approaches with setting form action to other pages and views. But still only GET from the form. I see the form values in the url though. My forms.py class LoginForm(forms.Form): mail = forms.EmailField(required=True, label='', widget=forms.TextInput(attrs={'placeholder': 'example@mail.com'})) My views.py def index(request): print(request.method) if request.method == 'POST': form = LoginForm(request.POST) print('Its a POST') if form.is_valid(): print('Its a valid form') else: form = LoginForm() print('Look above, Its a GET') context = { 'form': form, } return render(request, 'yo/index.html', context) And my index.html <form method="POST" action=""> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> -
AJAX load div that uses a queryset
I'm developing a dice roller app; I'm using Django (2.1), Bootstrap (4), mySQL, a pinch of JavaScript, and now AJAX, which is where I am struggling. I'm passing a queryset into the template as a kwarg, and then rendering that as an "action log" (history of the dice rolls) in it's own div. I thought that I could just use AJAX to reload that div, but I seem to be missing something. I'm using, amongst other things, this stackoverflow question as a reference. template.html <div class="container-fluid" id="action_log" style="padding:0"> ... <!--display actions--> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(function refresh_action_log(){ $.ajaxSetup ({ cache: false, complete: function() { setTimeout(refresh_action_log, 2000); } }); $('#action_log').load(document.URL + '#action_log'); } </script> What I think should happen is that, after 2 seconds (2000 ms), the AJAX should refresh only the named div. One thing I know I have questions about is the syntax of the last line in the function. In the comments on the page linked above, I see a couple different syntaxes, and I can't figure out which one is right. What have I missed? Thanks, -Van -
Using "in" operator in Django template not working as expected
Could really use help figuring out what I'm misunderstanding about the following: I'm using the built-in "in" operator to check if a user (standard user model) is in a queryset of Board members. This is the Board member model: class BoardMembers(models.Model): board = models.ForeignKey(Board, related_name="memberships", blank=True) user = models.ForeignKey(User,related_name='user_boards', blank=True) member_role = models.CharField(choices=MEMBER_ROLES, max_length=100, blank=True) def __str__(self): return self.user.username Here is the view I'm using: class ViewBoard(SelectRelatedMixin, generic.DetailView): model = models.Board select_related = ("user",) template_name = 'board/view_board.html' def get_context_data(self, **kwargs): context = super(ViewBoard, self).get_context_data(**kwargs) context['boardmembers_list'] = BoardMembers.objects.filter(board__slug=self.kwargs['slug']) return context And this is the html part I'm struggling with: {% if user in boardmembers_list %} <h1>HEY, {{ user.username }}, YOU'RE ALREADY A MEMBER!</h1> {% else %} <a class="btn btn-primary" href="{% url 'board:join_board' slug=board.slug pk=board.pk %}">Join this Board</a> {% endif %} I tested to see if individually the objects could be retrieved in the template and both the user and the boardmembers_list show up correctly. From the docs it looks like this should be a relatively straightforward thing to do. Can anyone tell me where I'm going wrong or what I'm misunderstanding about how these operators work? -
Django: cast field to another type when filtering
I have a model like this, it is an old code that I will not migrate: class MyModel(models.Model): number = models.CharField(...) My problem is to get the MyModel instance with the greatest number value, but because it is a CharField and not a IntegerField for instance, the searching is performed in an alfanumeric way. So number 230 is bigger than 2200. How can I do filter MyModel's queryset casting this field to Integer or similar? -
How optimize a Web scrapper with aiohttp and BS4
Hi i make a web scrapper to take some data from the api.mercadolibre and the web page because the api is not givin me the truthly data, I'm using aiohttp and async module for the asynchronous part and BeautifulSoup for the scraping, the time the script tooks is around 6 hours, but a i need it to be faster because i'm scrapping around 320K urls but it will increase to 1 million later. I will appreciate any help, Here is the code. It's a django app. import random import asyncio from aiohttp import ClientSession from products.models import Product, ProductVariation from time import time from bs4 import SoupStrainer, BeautifulSoup from django.utils import timezone from datetime import timedelta import aiohttp async def fetch(product, session): try: async with session.get(product.url_product, timeout=None) as response: text = await response.read() page_content = BeautifulSoup(text.decode('utf-8'), "html.parser", parse_only=content_product) content = page_content.find('div', attrs={"class": "item-conditions"}) quantity_content = page_content.find('span', attrs={"class": "dropdown-quantity-available"}) price_content = page_content.find('span', attrs={"class": "price-tag-fraction"}) sold_quantity = 0 if content is not None: content_split = content.text.split() for t in content_split: try: sold_quantity = int(t.replace('.','').replace(',','.')) except ValueError: pass else: sold_quantity = 0 if quantity_content is not None: quantity_split = quantity_content.text.replace('(', '').replace(')', '').split() for a in quantity_split: try: quantity = int(a.replace('.','').replace(',','.')) except ValueError: pass … -
Django ORM : How to use Counter with annotate
I want to see how many refered users does have a user: refered_user = User.objects.filter(user__groups__name="Refered") list = refered_user.values_list('referer_email') # Getting all the referers who actually had refered users referer_users = User.objects.filter(user__groups__name="Referer", email__in=clients_referent) Now how can I see how many refered users has a referer? I have tried this without success: counter = Counter(refered_user) referer_users.values('email').annotate(refered_num=counter['email']) -
django user profile upload image
this is my model my user model this is my modelform i imported the user model the view and the template enter image description here i dont know what am doing wrong am new to django -
What does connection limit mean for memcache?
I want to setup Django with MemCachier on Heroku. The free plan says: Connection Limit: 10 I don't understand what this means. How is a connection defined? Every time a user visits my site I will get some values of the cache. Is this already a connection because my website needs to connect to memcache to get this value? And what happens if the total number of connections is reached? Does the website still work?