Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting different result for django cell attribute in method vs unittest
Work project using Django which has tables, rows, columns, and cells. Column has a reject() method which is supposed to set is_rejected bool attribute to True for the column and then all cells associated with that column. Debug lines in the reject() method look like it is working but assertions in unittests find is_rejected to be False for the associated cells. I thought there might be a race condition where the assertion happened before the process of finding and changing the cells completed so I put in a wait for five seconds after the column.reject() but before the assertion. Still failed. I thought I might have been checking the wrong cell in the unit tests so I verified the cell values vs the cell value reported in the debug lines, changing the value a few times to see that they changed in the debug output which they did. I've been over and over the variable names to make sure I didn't make a dumb mistake, and if I did I still can't see it. this is the reject method in Column (including debug lines): class Column(BaseModel): def reject(self): super().reject() #reject all cells associated with this Column for cell in self.cell_set.all(): … -
Django Model data filter
This is an initial attempt to setup some basic CRUD functionality for an existing database (SQL Server based) for an internal Django App. I would like advice on model definitions that would support a primary table that holds a list of Trading Partners and also identifies a Partner Type. A Partner can in fact have a number of types. For example a Customer could also be a Supplier. There is then a related table of PartnerTypes that provides some extra details but primarily a Textual Description/Name assigned to the Partner Type. When I used the inspectdb command from Django I got what one would expect and the ForeignKeys were setup in the model. I would like to know is it possible to include some type of 'filtering' with in the Model Class to utilise the same table across different Classes. For example create a Model Class for a Client (eg. Client_Partner) and then another for a Supplier (eg. Supplier_Partner) have them both point to the same underlying Partner table and yet allow for the generation of a separate form for each 'Type' of partner? During the Creation of a New Client then the TypeID would need to be prefilled with … -
Send a string when sending data from django to onclick
This is a problem when you pass the price from django to onclick. admin.py class CommCdInfoAdmin(admin.ModelAdmin): class Media: js = ( 'https://ajax.googleapis.com/ajax/libs/d3js/5.7.0/d3.min.js', # jquery 'js/comcdInfoscript.js', # app static folder ) list_display = ('comm_gpcd', 'comm_cd', 'comm_cd_nm', 'comm_use_yn', 'comm_sort', 'register_date', 'status',) def status(self, obj): if obj.comm_use_yn != "": html = "<input type='button' value='edit' onclick='CommCdInfoAdmin_edit({0}, {1})'>" return format_html(html, obj.comm_gpcd, obj.comm_cd) be the result of this part <input type="button" value="edit" onclick="CommCdInfoAdmin_edit(sns, K)"> I want to change it. Come out as below. <input type="button" value="edit" onclick="CommCdInfoAdmin_edit('sns','K')"> ''<-----How do I add it? -
How to provide autocomplete street addresses functionality in django?
Is there any way to provide automatic street address suggestion when user tries to enter their address in the input box using so they start getting automatic address suggestions in django. I was searching autocomplete light but could find specially anything related to that. -
Is it possible to form submit display:none values in django forms
I am trying to form submit in django with multiple details so I have decided to separate have the next button and the first set of details will be hidden and the next set will be displayed and the form submission will happen in the last set of details. I have finished the code and placed the tag on the beggining and the closing tag at the bottom. But the form was not submitting. It was not showing any error. When i click the button nothing happened <form method="POST">{% csrf_token %} <div id="personal_info"> <div class="container"> <div class="form-row"> <div class="form-group col-md-4"> <label for="firstname">First Name</label> {{form.first_name}} </div> <div class="form-group col-md-4"> <label for="middlename">Middle Name</label> {{form.middle_name}} </div> <div class="form-group col-md-4"> <label for="lastname">Last Name</label> {{form.last_name}} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="emailadd">Email Address</label> {{form.email_address}} </div> <div class="form-group col-md-5"> <label for="contact">Contact No</label> {{form.contact_no}} </div> <div class="form-group col-md-1"> <label for="contact">Age</label> <input type="number" class="form-control" id="contact"> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <label for="position">Position</label> {{ form.position_applied_for }} </div> <div class="form-group col-md-4"> <label for="gender">Gender</label> {{ form.sex }} </div> </div> <div class="form-row"> <div class="form-group col-md-6"> <label for="birthplace">Place of birth</label> {{ form.place_of_birth }} </div> <div class="form-group col-md-6"> <label for="birthdate">Date of birth</label> {{ form.date_of_birth }} </div> </div> <div class="form-row"> <div … -
Django Queryset icontains() method not returning exact match
I am trying to filter a model, by passing the text query, and checking if any of the fields contains the value that matches exactly or partially to the given text query. So let's say I have a model named Sample, which contains char fields ["name", "state", "type"]. Assuming one of the model object has a value of state to set as "barely alive" I looked at the methods described in the following django doc: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/search/ I want to retrieve that object by using any of "barely","arely" or "barely alive"as a text query. I initially tried something like Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search__icontains=query_text) Above line will however, will not return a correct queryset if I pass a full text barely alive as a query text and only work when partial text such as barely or alive is passed. So I then tried Sample.objects.annotate(search=SearchVector(*list_of_fields)).filter(search=query_text).filter(search__icontains=query_text) But then it returns an empty Queryset. What am I missing here? -
Django: New field not showing up in form after adding it to model
After adding a new field to my model, it doesn't show up in the form. I have been working on this django app and have extended the already existing User model with my own UserProfile model with extra fields. Recently, I have decided to add an extra field to the UserProfile model (profile_type). I added it to the model and included it in its corresponding form, and ran makemigrations and migrations. I then tried inserting an initial value to this field in my views and found out that it is not showing up in the form through print(), however, all the other fields are. My UserProfile model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name='userprofile') gender = models.CharField(max_length = 10) city = models.CharField(max_length = 45) country = models.CharField(max_length = 45) birthdate = models.DateField(null=True) phone_number = models.CharField(max_length = 15) profile_type = models.CharField(max_length = 6) @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: profile = UserProfile(user=instance) profile.save() My UserProfile forms (UserProfileForm contains the fields necessary for sign up, AdditionalUserProfileForm is the rest) class UserProfileForm(UserCreationForm): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username', 'password1', 'password2') def save(self, commit=True): user = super(UserProfileForm, self).save(commit=True) user.email = self.cleaned_data['email'] user.first_name = self.cleaned_data['first_name'] … -
How to change the format of the nested payload?
I want to change my json payload from: { "grade": "ten", "studentdlList": [ { "studentdetail": { "name": "mw", "rollno": 19 } }, { "studentdetail": { "name": "battery", "rollno": 44 } } ] } To the form below, because the first one becomes too complex and redundant: { "grade": "ten", "studentdlList": [ "studentdetail": { "name": "mw", "rollno": 19 } , "studentdetail": { "name": "battery", "rollno": 44 } ] } To achieve the result my serializers are below: class SerializerTemp(serializers.Serializer): name = serializers.CharField() rollno = serializers.IntegerField() class Studentserializer(serializers.ModelSerializer): studentdetail = SerializerTemp(source="*") class Meta: model = Student fields = ('studentdetail',) class SiteSerializer(serializers.ModelSerializer): studentdlList = Studentserializer(many = True) class Meta: model = Grade fields = ("grade", "studentdlList") The last serializer also has update and create(which I haven't put here). How can I possibly change my payload to the specified form so that it is less redundant and more clearer? -
User Registration: Creating user accounts Django 2.1.5
I'm having some trouble creating new accounts and then authenticating. I enter all the credentials in (username, password), and select "submit", and it successfully redirects me back to the 'account successfully created page'. However i can't find the new user account in the database and on the staff account. This is my views file from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login # Create your views here. def index(request): return render(request, 'user_example/index.html') def register(request): if request.method=='POST': form=UserCreationForm(request.POST) if form.is_valid(): form.save() username=form.cleaned_data.get('username') raw_password=form.cleaned_data.get('password1') '''user=User.objects.create_user(username=username, password=raw_password) user.save()''' user=authenticate(username=username, password=raw_password) user.save() #if user1 is not None: login(request, user) return redirect('success') else: form=UserCreationForm() #context={'form': form} return render(request, 'registration/register.html', {'form': form}) #as def success(request): return render(request, 'user_example/success.html') Please help, what am i doing wrong here? -
NoReverseMatch error even though view and url path already exist
I'm still learning the ropes for programming with django and when I try to open up my website on localhost, I'm getting an error message that does not help to point me in the right direction. This is the error message I'm getting from a file called base.html: NoReverseMatch at / Reverse for 'main-createchannel' not found. 'main-createchannel' is not a valid view function or pattern name. the part of base.html that's calling the urls <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'main:main-about' %}">About</a> <a class="nav-item nav-link" href="{% url 'main:main-channelsettings' %}">Channel Settings</a> <a class="nav-item nav-link" href="{% url 'main:main-channelinfo' %}">Channel Information</a> <a class="nav-item nav-link" href="{% url 'main:main-createchannel' %}">Create Channel</a> <a class="nav-item nav-link" href="{% url 'main:main-findchannel' %}">Find Channel</a> <a class="nav-item nav-link" href="{% url 'main:main-ticketrequest' %}">Submit a Ticket</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="{% url 'main:main-userprofile' %}">Login</a> <a class="nav-item nav-link" href="{% url 'main:users-register' %}">Register</a> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'main:main-userprofile' %}">Profile</a> {% endif %} </div> </div> views.py def createchannelpage(request): if request.method == 'POST': form = CreateChannelForm(request.POST) if form.is_valid(): form.save() channel_room_name = form.cleaned_data.get('channel_room_name') #messages.success(request, f'{channel_room_name} was created!') return redirect('/') else: form = CreateChannelForm() return render(request, 'main/createChannel.html', { 'form': form, 'title': … -
Django not showing all mysql database results despite using fetchall method
I have ten records in mysql database and am using fetchall() method Now I have requirements to display all database result in json using sql queries in django. When I run the code below, it only shows the first records while the rest is not displayed. I was wondering why am getting just only one json record despite using fetchall() approach Here is the code from django.db import connection def read(request): sql = 'SELECT * from crud_posts' with connection.cursor() as cursor: cursor.execute(sql) output = cursor.fetchall() print(output[0]) items=[] for row in output: items.append({'id':row[0], 'title': row[1],'content': row[2]}) jsondata = json.dumps({'items': items}) return HttpResponse(jsondata, content_type='application/json') -
Does Django Rest Framework's Browsable API detect user-agent to auto-disable itself?
Some REST API clients cannot render HTML, so including forms is not efficient. I was curious where in the code this detection happens. I've found that the form may incur extra database queries to pre-populate the fields with choices (e.g. ManyToMany) and this is especially the case if the write serializer and read serializer are different. I wanted to test if this extra query is incurred for non-web browser clients. So how can I test this? I think the reference to the source code would be helpful. -
Searching name and surname in Django
I have this model on Django: class Profile(models.Model): name = models.CharField(max_length=50, blank = False) surname = models.CharField(max_length=100, blank = False) ... For example, I have 2 profiles in the db: John Doe John Smith I want to do a form search, that searches in both name and surname attributes. I tried: Q(name__icontains=text) | Q(surname__icontains=text) But this doesn't work, for example if I search "John Doe" it returns both of them. Any help? -
Problem referring to a third model in Django
I have three models: class Person(models.Model): document = models.CharField(max_length=14) phone = models.CharField(max_length=20) class Address(models.Model): person= models.ForeignKey(Person, related_name='person_address', on_delete=models.CASCADE) zip_code = models.CharField(max_length=9) class StatusPerson(models.Model): person = models.OneToOneField(Person, related_name='person_status', on_delete=models.CASCADE) sms_status = models.CharField(max_length=100, blank=True) activation_status = models.CharField(max_length=100, blank=True) I want to know the the status of the person from the adress class. I've try to: def user_sms_status(self): return self.person.StatusPerson.sms_status And I receive the error: 'Person' object has no attribute 'StatusPerson' Can Anyone help me to get this? -
How to efficiently clear nested many to many relationship in Django?
I have a code with models that have nested many to many relationship and I need to clear the relationship, however the solution I have is really slow, as it makes tons of sql queries. The three models I have are Parent, Child, GrandChild. A parent can have many child and the Child has many Grandchild. What I need to do is remove the relationship of child and grandchild given the parent. parent = models.Parent.objects.get(id=1) children = models.Child.filter(parent=parent) for child in children: children.grandchildren_set.clear() This actually works and removes all the association of the child with grandchild for child associated with the parent we picked. However in my case there is usually over 5k child per parent, and each child has about 2 grandchildren. But this makes tons of sql query, and times out. I am wondering if there is any efficient way to do this in bulk or by prefetching of some kind. -
Django & SQLite: DurationField arithmetics
I have the following model class MyModel(models.Model): start = models.TimeField() finish = models.TimeField() penalty = models.IntegerField(blank=True, default=0) # penalty in minutes And the following queryset annotation in admin def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( total_time=ExpressionWrapper( F("finish") - F("start") + F("penalty") * 60, output_field=DurationField() ) ) return qs When I inspect the annotation value for a row where penalty != 0 I get something like datetime.timedelta(0, 1800, 1800) (in this case penalty is 30 minutes). However, I expect a timedelta like datetime.timedelta(0, 3600). Can someone explain please? I am using Django==2.1.7 and SQLite version 3022000. -
How to fix "myClass has no objects member"
After I added the method post_detail in the file '~/blog/views.py' im getting the error Class 'Post' has no 'objects' member but before doing this the code was working so well. I read a lot of stuff about Models on Django website but i cant find the error. The django server is working fine, 0 errors. I really cant understand why this error and why my application dont work -
Wagtail 2.4 - get_sitemap_urls() takes 1 positional argument but 2 were given
I used to have a working sitemap before I upgraded to Wagtail 2.4. I have upgraded my site according to the documentation here: http://docs.wagtail.io/en/v2.4/reference/contrib/sitemaps.html but still no such luck. The error I'm getting is get_sitemap_urls() takes 1 positional argument but 2 were given. I've added 'django.contrib.sitemaps', to my INSTALLED_APPS in my base settings, and I've added the following to my urls.py: from wagtail.contrib.sitemaps.views import sitemap urlpatterns = [ ... url('^sitemap\.xml$', sitemap), ... ] My Page models have the following included in them: def get_sitemap_urls(self, request=None): return [ { 'location': self.get_full_url(request), 'lastmod': (self.last_published_at or self.latest_revision_created_at), 'changefreq': 'monthly', 'priority': .5, } ] I previously had a sitemap.xml file included to overwrite the old wagtailsitemaps/sitemap.xml that looked like this: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% spaceless %} {% for url in urlset %} <url> <loc>{{ url.location }}</loc> {% if url.lastmod %}<lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>{% endif %} {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %} {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %} </url> {% endfor %} {% endspaceless %} </urlset> Any idea what I'm missing? I have done everything the documentation said to do, and it's pretty basic. I can't find anything else online that includes anything other than these steps. -
Template does not exits exception
I am very new to Django. I am facing an exception TemplateDoesNotExist at /. I guess there is some problem with my template DIR. Here is the URL: from django.conf.urls import url from first_app import views urlpatterns= [ url(r'', views.index, name='index'), ] Here is the view: from django.shortcuts import render from django.http import HttpResponse def index(request): my_dict={'insert_me':"Hello I have created my first dynamic Template"} return render(request,'Twenty3rdMarch/first_app/templates/index.html',context=my_dict) Here is my Settings: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR=os.path.join(BASE_DIR,'templates') print(TEMPLATES_DIR) ALLOWED_HOSTS = [] Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Twenty3rdMrach.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Twenty3rdMrach.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'udemy', 'USER':'root', 'PASSWORD':'Ravi@go123', 'HOST':'localhost', 'PORT':'3306', } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, … -
save videos to file system from request.FILES.getlist()
In my project at first was necessary to save in my file systems the images from request.FILES.getlist() and I can do that with PIL like this: if request.FILES: imgs = request.FILES.getlist('file') dir = '\\some\\directory\\' if not os.path.exists(os.path.dirname(dir)): os.makedirs(os.path.dirname(dir)) for f in imgs: i = Image.open(f) i.save(dir+str(f)) else: for f in imgs: i = Image.open(f) i.save(direc+str(f)) else: imgs = None That works fine but now I need to store videos and images from request.FILES.getlist() How can I store both types? Thanks in advance. -
Django signup view: TypeError: 'set' object is not subscriptable
My web application on django catch an error due signup with different passwords typed. All other form errors works fine include taken email, empty fields and so. Error comes in at validating signup form. Don't really understand why i have this error, because it not affected by my code (i guess). Here is traceback: Traceback (most recent call last): File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/kotofey/AccentAcademy/registration/views.py", line 44, in signup if form.is_valid(): File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/forms/forms.py", line 381, in full_clean self._clean_fields() File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/forms/forms.py", line 402, in _clean_fields value = getattr(self, 'clean_%s' % name)() File "/home/kotofey/AccentAcademy/aaenv/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 101, in clean_password2 self.error_messages['password_mismatch'], TypeError: 'set' object is not subscriptable -
Django email activation via Outlook not working, via Gmail works fine
Using Django activation token via e-mail, sent by existing SMTP server... Does anybody have a clue why this may go wrong using MS Outlook (even when I copy paste the link) while it works fine when I have the activation link sent to my Gmail... In the code below, I get the "Account activation failed..." response instead of being logged in when the link was sent to an Outlook account. The user is created and activated in both cases though... in views.py: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) return redirect('/') else: return render(request, 'account_activation_invalid.html') When using Gmail I get redirected like you would expect... -
Django admin: overriding form for only add object view
I want to override Django Admin form, but only for add view and not the change view. Is this possible? -
Django - calculate a field during save
I have a series of objects that have a 'number' field. Usually, for a field based on something else, I would use a property, but in this case, the 'number' is calculated by checking the total number of objects in the database, and increasing it by one. I've tried doing this: class Foo(models.Model): number = models.IntegerField(null=False) def save(self, *args, **kwargs): prev_number = DirectorLoan.objects.all().count() self.number = prev_number + 1 return super().save(*args, **kwargs) This throws an error, because when calling it, I don't provide the required field 'number'. I thought this would work, though, as the field gets filled in before saving occurs, but apparently not. I'm currently creating this object through the command line. What is the correct way to do this? -
django project, iterate a list of data on each call of a function
I have a django project in which for each user I will call a function. In this function, I have parameter, x_id = my_array[k]. I want to loop through the my_array on each call of the function. I tested putting array data on a file and reading and using iter and next. But on each call it's doing the same and not looping. Any suggestion? my_array = ['red', 'blue', 'orange', 'magenta', 'black', 'yellow', 'pink', 'green'] def my func(): a = my_array[indx] Like I said the goal is rotating my_array list on each call.