Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error while running django first project on my ubuntu
exploit@exploit-desktop:~$ django-admin.py startproject hellodjango bash: django-admin.py: command not found exploit@exploit-desktop:~$ django-admin startproject mysite bash: django-admin: command not found exploit@exploit-desktop:~$ django-admin bash: django-admin: command not found exploit@exploit-desktop:~$ -
Overriden templates aren't rendered in production
I've overriden Django-allauth templates in my Django project just creating a new folder "account" in templates folder. This works during deployment on Windows but when I moved the project to DigitalOcean VPS, it is looking for old templates (in allauth app) so I see old styled allauth pages. This is the structure: firstapp\ authapp\ templates\ account\ email.html login.html anotherapp\ I tried to switch allauth apps and my authapp in INSTALLED_APPS but it doesn't seem to work. And this is my settings.py INSTALLED_APPS. INSTALLED_APPS = ( 'django.contrib.auth', 'mainapp', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sites', 'django.contrib.staticfiles', 'crispy_forms', 'super_inlines', 'django_tables2', 'quizzesapp', 'ordersapp', 'django_extensions', 'authapp', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'languagesapp', 'widget_tweaks', 'localflavor', 'paypal', 'paypal.standard.ipn', 'nested_inline', 'django_forms_bootstrap' ) What do you thing I should do? EDIT: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.core.context_processors.i18n', # 'django.core.context_processors.request', # "django.contrib.auth.context_processors.auth", # "allauth.account.context_processors.account", # "allauth.socialaccount.context_processors.socialaccount", ], }, }, ] -
How to insert multi data form to database
I'm trying to insert some multi data to database with django. (I'm totally new to Django, thus, please have mercy :) ) My model is as follows : class Files(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) file_type = models.ForeignKey(to=FileType) file = models.FileField(upload_to='media/%Y/%m/%d/', blank=True) def __str__(self): return self.file_type.name The view where I fetch the data is as follows : def save_user(request): user = json.loads(request.POST.get("user")) for file_key in request.FILES.keys(): file = Files() file.file_type = FileType.get_by_key(file_key.split('/')[1]) file.file = request.FILES[file_key] file.save() return HttpResponse("User saving...") And the data that I get in request is as follows : request.FILES <MultiValueDict: {'file/ID_CARD': [<InMemoryUploadedFile: check.png (image/png)>], 'file/STATUTES': [<InMemoryUploadedFile: pictures.xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}> and user {'companyName': 'Autralis', 'btwNumber': '84515', 'address': 'Hundelgemsesteenweg 575', 'country': 'Belgium', 'zipcode': '9820', 'place': 'Merelbeke', 'phone': '+32 486386069', 'mobilePhone': '+32 486386069', 'firstName': 'Maida', 'lastName': 'Mesanovic', 'email': 'maida@autralis.com', 'userName': 'Maida', 'password': '123', 'confirmPassword': '123', 'files': [{'file_type': 'LETTER_HEAD', 'values': {'active': False, 'fileName': 'Blank letterhead', 'file': None}}, {'file_type': 'COMPANY_PICTURE', 'values': {'active': False, 'fileName': 'Company photo', 'file': None}}, {'file_type': 'ID_CARD', 'values': {'active': True, 'fileName': 'check', 'file': {}}}, {'file_type': 'STATUTES', 'values': {'active': True, 'fileName': 'pictures', 'file': {}}}], 'terms': True, 'emailNotifications': True, 'smsNotifications': True} How can I add it to the database? -
Is it possible for DRF ValidationError to skip force_text?
it is possible to return json directly in error message through ValidationError? Example: { "uncompleted_tasks_error": [ { "This operation cannot be completed because there are uncompleted tasks.": [ { "id": 1, "description": "Fill in info", "completed_at": null }] } ] } Currently, ValidationError returns "None" instead of null, as it uses force_text to convert serializer.data to JSON. -
storing queryset in session variables
I am using django and trying to store the queryset in session variable def wholelist(request): hotelvar=request.POST.get('service_type') city_list=Hotels.objects.filter(city_name__iexact=request.POST.get('searchabc')) if not city_list: hotel_list=Hotels.objects.all() context={'hotel_list':hotel_list} return render(request, 'polls/homepage.html',context) pricemin=200 pricemax=800 request.session['hlist']=city_list I am getting the following error: [Hotels: ashoka, Hotels: abc] is not JSON serializable I tried to convert into list and then store it request.session['hlist']=list(city_list) I am getting the following error: 'QuerySet' object has no attribute 'POST' Is there a way to store queryset in session variable? -
'Manage.py behave' not recognised as command in Django project
I've had to clone a repository involving a django project. This is my first time using django and the project is configured a bit differently than what a normal django project would be. For instance it has a settings folder with a local.py file that contains a Local(Dev) class. I have installed behave_django, however when I run the command 'manage.py behave' it says that the command is not recognised. Therefore I believe that whilst I have added INSTALLED_APPS = ('behave_django',) to the local.py file it is not getting recognised. I have tried adding it outside the class and within. Is there a way I can run a script to check my list of installed_apps, etc. Also I am new to python and the configuration side has gotten me a bit confused. -
delete template fragment cache from view
In template I have code like this one: {% load cache %} {% cache 500 sidebar request.user.username %} .. sidebar for logged in user .. {% endcache %} Now from a view I need to delete this particular fragment, so based on the id 'sidebar' with arg request.user.username -
Django - calling custom update behaviour when overriding its behavour
What I am trying to do is best described by example. Consider the following: class MyModel(model.Models): # core fields objects = QuerySetManager() class Meta: managed = False db_table = 'my_model' class QuerySet(QuerySet): def update(self, *args, **kwargs): if something_special: # handle that special case else: # call custom update The entire question is how I can call the custom update method using *args and **kwargs. I tried super(self.Model, self).save(*args, **kwargs), but I end up with 'QuerySet' object has no attribute 'Model' error (which is not surprising). Any help on what the correct syntax is? -
Django : One model has two foreign keys is this the right approach in this case
I am currently learning about Django Models. Here is my current situation. I have three models 1-Patient_Names 2-Patient_Responses 3-Doctor_Questions Now here is the relationship there will be multiple patients which will be represented by the model Patient_Names. Now each patient will have specific responses to the questions asked by a doctor these responses are represented by the model Patient_Responses. Because of this the Patient_Responses model will have a field that is a foreignKey to the Patient_Names model.Also since the responses will be for the questions from the model Doctor_Questionsthe Patient_Response has another field that is foreignKey to the model Doctor_Questions. Is this the right approach ? Can a model have two foreign keys? Patient_Names Doctor_Questions | | |---------Patient_Responses -------| | pname = models.ForeignKey(Patient_Names) doctor_questions = models.ForeignKey(Doctor_Questions) -
Clustered foreign key Django
I'm currently working on an existing set of models, with an existing database that suffers from some inconsistencies of data. To visualize, we have tables: A B AtoB FlatTable FlatTable can contain links to A and B individually. As you might guess, this construction allows linkage between an A and a B in FlatTable that's not defined in AtoB. I do not want (or have the opportunity) to change the application completely, I just want to disable improper linkage. A solution would be to create a clustered foreign key which links FlatTable(A,B) to AtoB(A,B). AFAICS https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey doesn't supply this functionality. I could do a lookup for each insert and such, but this creates all kinds of edge cases that should ideally be covered as well (e.g. updates on A, B, AtoB themselves). I'm still not a veteran in Python / Django and hope that someone who is might know the best way to go here. -
object of type 'NoneType' has no len() - Editing Form
I have a Profile model which has a Foreign key to the user model. I've created an 'edit profile' view which allows users to update profile information. One of those fields being an image field (Hosted with cloudinary). Since changing this field to a Cloudinary field i seem to be having issues with newly created profile objects when the profile doesn't have an image uploaded. However, if the user HAS a profile image i can load the 'edit_profile' view no problem. I've narrowed it down to be the image field as when i remove the field it works no problems. Despite the traceback not being very helpful. Here is my edit_profile view. @login_required def edit_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, request.FILES, instance=request.user) profile_form = ProfileForm(request.POST,request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, "Successfully Updated") return redirect('profile:edit_profile') else: messages.success(request, "Please correct the below info") else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'profile/edit.html', { 'user_form': user_form, 'profile_form': profile_form }) I have two forms, one for the user model which allows the user to update first name, last name and email. Then the profile form, which allows to update the additional fields. I think i need to add … -
How to render django modelformset_factory forms manually
I am using django's modelformset_factory form for uploading and editing images. Currently when i display the forms it shows forms with existing data as follows: field name: Currently : link to image (e.g.: images/filename.jpg) Change: image input field check box to delete How can I change the display of (Currently : link to image (e.g.: images/filename.jpg))? would like to change the image link to display image name instead and open it in a new window when user clicks it. I have checked django's documentation to manually render the form but could not find related information. Thank you! -
How can i send the request parameters as a text format(i.e;form-data) in postman
The request data i am sending as Json format is storing in the database but while i am sending in text format it is not storing.How to pass the values in text format I am just beginner so it helps me a lot ,thank you in advance -
Django- duplicate inserts into the choices list of MultipleSelect field in the form
class Form(django_forms.Form): fields_choices = [ ('ID'), ('Name'), ] required_fields = django_forms.MultipleChoiceField() def __init__(self, *args, **kwargs): self.fields_choices.insert(1, 'x') super(Form, self).__init__(*args, **kwargs) self.fields["required_fields"].choices\ = tuple(self.fields_choices) As you could see from the above, I insert one more field into the choices. But if I refresh the form view, there would be two 'x' in the choices. And refresh agagin, one more 'x'. I expect it should be always just one 'x' in the choices. -
delete a father object can't delete children's manytomany relation
in my apps have a problem in django orm. i have two models in my apps, like this: class A(models.Model): name = models.CharField(max_length=200, blank=True) class B(models.Model): name = models.CharField(max_length=200, blank=True) class C(models.Model): name = models.CharField(max_length=200, blank=True) a = models.ForeignKey(A) b = models.ManyToManyField(B) now have three objects: a, b, c, i delete a use a.delete() can delete c, but can't delete b and c relation, must b.remove(c) then do a.delete(). how can i only do a.delete() or others can delete b and c relation. -
error when page is refreshed in django
I am learning to create a website using django. I have a homepage through which user can select city. The next page shows the list of hotels.It works properly,but when page is refreshed it gives me error This is my html file for list page. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script src="//code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script> <script type="text/javascript" src="../js/typeahead/0.11.1/typeahead.bundle.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> {% load static %} <script src="/static/typeahead.js "></script> <script type="text/javascript"> $(document).ready(function(){ // Defining the local dataset var cars = []; {% for city in hotel_list %} cars.push("{{city.city_name}}"); {% endfor %} // Constructing the suggestion engine var cars = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.whitespace, queryTokenizer: Bloodhound.tokenizers.whitespace, local: cars }); // Initializing the typeahead $('.typeahead').typeahead({ hint: true, highlight: true, /* Enable substring highlighting */ minLength: 1 /* Specify minimum characters required for showing result */ }, { name: 'cars', source: cars }); }); </script> <style type="text/css"> *{ font-family: Verdana; } .typeahead, .tt-query, .tt-hint { border: 2px solid #CCCCCC; font-size: 22px; /* Set input font size */ height: 60px; line-height: 30px; outline: medium none; padding: 8px 12px; width: 350px; color: … -
Django Ldap Authentication using default function
I am new to django . I am trying to authenticate my django against the LDAP server . I saw the django-ldap documentation regarding the settings and i configured my settings accordingly : AUTH_LDAP_SERVER_URI = "ldap.forumsys.com" AUTH_LDAP_BIND_DN = "cn=read-only-admin,dc=example,dc=com" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") My doubt is 1) what would i have in my Views . 2) should i hav to redirect my url to my views again ? 3) how would i run this ? Thank you -
After configure Django with Postgres, Nginx, and Gunicorn on CentOS 8,no matter how i change the Django ,there has no change
Recently I configure the web server as the guide of this link: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7#create-a-python-virtual-environment-for-your-project I can normally visit the homepage like: the normal page AND I can normal visit domain_name/admin . After that ,when i create my_apps,even i change the url this: from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ ] Once i visit the domain_name or domain_name/admin or IP/admin,there has no change.There has no warning and no change -
Noob in web dev, python + Django
I have a question about web. I am learning python and I am really exited about how easy and comprehensive object manipulation is compared to java. Let's say I wanna build a small we project ( few pages; home, about page, contact page, some forms and a reservation app for a family bakery). I have read some of the Django tutorials/overview and it doesn' t say much about the the style of the web page.The question: Do I also need to learn css and html (and JS) to build this kind of web page? ... It's kind of overwhelmig having to know all this stuff. I have a Small background in Java, making simple but functional Jframe apps using Mysql, but only locally. I know some relational DB stuff but never done somethig on the internet. Does Django offer some of the desing part of web development? Can you provide some resources to get going with 'templates'? Thank alot in advance! We have a great community here in SoloLearn. Good stuff going on! ( Small note: I am not looking for an easy way out, just wondering if knowing all this stuff is necessary for a small project. If the … -
python views value not display in html
i'm using below code to display value from excel def readExcel(request, template='dashing/base.html'): wb = open_workbook('D:\\test.xls') for sheet in wb.sheets(): number_of_rows = sheet.nrows number_of_columns = sheet.ncols test = sheet.cell_value(2, 1) print test context = { 'test' : test, } return render_to_response(template, RequestContext(request, context)) but nothing is display in html -
How can I insert data in two different models?
I'm newbie in coding, and I'm trying my first Django app. This time I have three different models, but with a single form at the momment when I hit Save I want to save data on that form model and in the others 2 models. So in my display I want to loop the other two models to show what I have. Is that even possible? models.py class Personame(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Personlastname(models.Model): last_name = models.CharField(max_length=128) def __str__(self): return self.last_name class Personinfo(models.Model): personame = models.CharField(max_length=128) personlastname = models.CharField(max_length=128) address = models.TextField() phone_number = models.CharField(max_length=128) hobbies =models.CharField(max_length=128) def __str__(self): return self.personame forms.py: class personform(forms.ModelForm): personame = forms.CharField(label = "Name") personlastname = forms.CharField(label = "Last Name") class Meta: model = Personinfo fields = ["personame","personlastname","address","phone_number","hobbies"] views.py: def index(request): queryset = Personame.objects.all() queryset2 = Personlastname.objects.all() qs = chain(queryset,queryset2) form = personform(request.POST or None) context = { "qs": qs, "form":form, } if form.is_valid(): instance = form.save() return render(request, "index.html", context) index.html: <form method="POST" action="">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save!" /> </form> <table > <tr> <th>Name</th> <th>Last Name</th> </tr> {% for item in qs %} <tr> <td>{{ item.name }}</td> <td>{{ item.last_name }}</td> </tr> {% endfor %} </table> Basically … -
Django: Annotate and order by foreign key AVG ranking not filtering
I have a advertisement model and an review model, related by a Foreignkey('adfk') I am trying to get questions having heighest average ranking for their reviews. For example: AD1 - Average ranking with 4. AD2 - Average ranking with 5. In template the result should show AD2 first and AD1 second. I am using this in my view but its not showing correctly. DB is postgres. IF I change ('-rating') to ('rating') it shows Ad1 first and Ad2 second, I mean atleast consider the order_by. def adhome(request,tag_wise=None): tags = Tag.objects.all() cities= advertisement.objects.all().values('city').distinct() view = request.GET.get('view') if tag_wise: questionlist=advertisement.objects.filter(tags__slug__in=[tag_wise]) else: questionlist=advertisement.objects.all() if view: questionlist = questionlist.filter(city=view) questionlist = questionlist.annotate(rating=Avg('adfk__rank')).order_by('-rating','id') paginator = Paginator(questionlist,10) # Show 10 contacts per page page = request.GET.get('page') try: contacts = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. contacts = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. contacts = paginator.page(paginator.num_pages) return render(request,'classified/home.html',{'contacts':contacts,'tag_wise':tag_wise,'view':view,'tags':tags,'cities':cities,}) -
Exporting Django Objects model in CSV
I wanted to create an extra action for the admin in django-admin to be able to export the data as CSC formats. I have written the code in my admin.py from django.contrib import admin from .models import News, ResourceTopic, Resource, PracticeTopic, Practice, Contacts, Visualization import csv from django.utils.encoding import smart_str from django.http import HttpResponse admin.site.register(News) admin.site.register(ResourceTopic) admin.site.register(Resource) admin.site.register(PracticeTopic) admin.site.register(Practice) admin.site.register(Visualization) def export_csv(modeladmin, request, queryset): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' writer = csv.writer(response) writer.writerow([ "First Name", "Last Name", "Organization", "City", "Country", "Email", ]) for obj in queryset: writer.writerow([ obj.firstName, obj.lastName, obj.organization, obj.city, obj.country, obj.email, ]) return response class contactsAdmin(admin.ModelAdmin): actions = [export_csv] admin.site.register(Contacts, contactsAdmin) But the problem that i had was the file gets downloaded as download.html and the html file displays the same django admin page. -
HTML Anchor Tag Not Working in Outlook
I am making email template in Django to be sent to Outlook and I want to add anchor tag for navigation. However, I found the tags work in html browser but not in Outlook (both 2010 and 2013). Could anyone advise what have gone wrong and how to fix it? Many thanks. Codes are as below: {% for field, fSect in table %} <table><tr><td><p style="margin:0; font-size:15px;"><a href="#body{{field.id}}" id="name{{field.id}}" name="{{field.id}}" style="text-decoration:none; color:#0000FF;"> {{forloop.counter}}.{{field.Title}} ({{ field.NewsPaper }}, {{ field.Date }}, {{ fSect }}) </a></p></td></tr></table> {% endfor %} {% for field, fSect in table2 %} <p name="{{field.id}}">{{ field.gp_Email }}</p> <p name="{{field.id}}">{{ field.N_tag }}</p> <table><tr><td><p id="body{{field.id}}" name="body{{field.id}}">{{ field.NewsPaper }}, {{ field.Date }}, <br> {{fSect}}</p></td></tr></table> {% endfor %} -
How to extract Django Form errors message without the HTML tags
I need to extract the messages and field. For Example, I have this django form error result <ul class="errorlist"> <li>__all__ <ul class="errorlist nonfield"> <li>Pointofsale with this Official receipt and Company already exists.</li> </ul> </li> </ul> from the output of this code def post_sale(request): sale_form = request["data"] if sale_form.is_valid(): save_form.save() else: print save_form.errors But what i need to achieve is to get the message without the tags, so i could just return those message in plain string/text. def post_sale(request): sale_form = request["data"] if sale_form.is_valid(): save_form.save() else: # This is just pseudo code for field in save_form.errors: field = str(field["field"}) message = str(field["error_message"]) print "Sale Error Detail" print field print message error_message = { 'field':field,'message':message } error_messages.append(error_message ) The output would be: Sale Error Detail (the field where form error exists) Pointofsale with this Official receipt and Company already exists. Explored Questions and Documentations displaying django form error messages instead of just the field name Getting a list of errors in a Django form django form errors. get the error without any html tags How do I display the Django '__all__' form errors in the template? https://docs.djangoproject.com/en/1.10/ref/forms/api/ https://docs.djangoproject.com/en/1.10/topics/forms/ Thanks, please tell if something is amiss or something needs clarification so i could …