Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model description in django-admin
Is it possible to put a model description or description on the list display page of a certain model in django-admin? I'm talking about something like when you click a model name link on the homepage of django-admin and when you go to the list display page of that model. There will be a description written on top of the table. Something like "This model is used to log all accounts that will be fetched by our scrape.... And so on" Something like that, is it possible? -
How to load external html into html inside Django template
I am trying to incorporate a django application into a web site where static html accounts for the majority. The directory structure is as follows. root/ ├ var/ │ └ www/ │ ├ html/ │ ├ static │ │ ├style.css │ │ ├base.js │ │ │ ├ web/ │ ├head.html │ ├footer.html │ ├base.html │ └ opt/ └ django/ ├ project/ │ ├ apps/ ├ ├ views.py ├ template/ ├ index.html I want to make /opt/django/template/index.html read html in /var/www/html/web/. I do not know how to include. {% include "/var/www/html/web/head.html" %}was useless. I do not want to change the directory structure. (I'm sorry for poor English) -
Django JsonResponse sends duplicate objects sometimes and not others
This is a super weird bug I'm running into. I have a python script that generates a JSON object which I want to respond with using JsonReponse. This response successfully comes back, but sometimes it contains multiple copies of the object, sometimes it contains one, and it just goes up and down and all over the place in terms of the number of objects it sends back. No idea how this is even possible. My views.py has a function like this that handles a web crawler script. def webcrawler(request): source = request.GET.get('source') method = request.GET.get('method') nodes = request.GET.get('nodes') depth = request.GET.get('depth') keyword = request.GET.get('keyword') webcrawler = WebCrawler(source, method, nodes, depth, keyword) data = webcrawler.jsonSerialize() return JsonResponse(data, safe=False) My jsonSerialize() function looks like this: def jsonSerialize(self): for n in self.graph.nodes: n.sourceNodes = [] self.graph.edges = list(self.graph.edges) return json.dumps(self.graph, default=lambda o: o.__dict__) Why would I be getting random numbers of copies back from this response? I'm making a new request every time and create a new object every time, but it seems like the number of objects sent back just grows and sometimes goes up an down. If I open a new tab and make a new request, the same thing happens. … -
Wow does six.with_metaclass() work?
Hi Stackoverflow community I have been trying to understand how Django (and Wagtail's Stream-field) work under the hood. Doing that I learned about metaclasses and believe to have a handle on the principle. That said, Python 3's six package executes the with_metaclass function is still a little obscure to me. Here is the code followed by a specific question: models.py class BlogPage(Page): blogElement = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.TextBlock()), ('picture', ImageChooserBlock()), ], default=[]) wagtailcore > fields.py class StreamField(models.Field): def __init__(self, block_types, **kwargs): if isinstance(block_types, Block): self.stream_block = block_types elif isinstance(block_types, type): self.stream_block = block_types() else: self.stream_block = StreamBlock(block_types) super(StreamField, self).__init__(**kwargs) wagtailcore > blocks > stream_block.py class StreamBlock(six.with_metaclass(DeclarativeSubBlocksMetaclass, BaseStreamBlock)): pass six.py def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) QUESTION (1) The description suggests that we generate a temporary dummy metaclass that replaces itself with the actual metaclass. (2) How does this work? (3) How would we sequence the meta class … -
Uploading large files to google drive via 3rd party dashboard
I am currently thinking of creating a custom dashboard. One of the features of this dashboard is to allow users to upload files to their google drive account. However, I am a bit at a lost of the implementation of such a feature. according to https://support.google.com/drive/answer/37603?hl=en Google drive support up to All other files: Up to 5 TB. Since the dashboard uses Oauth2 to access a user's google drive account, I was thinking that uploads would first be sent to my server, before my server calls the api and transfers the data over (I realized this would cause major issues for larger file sizes as it basically doubles throughput and thus time) How is this usually implemented in other cases? Should I encode the Oauth2 access_token into the client side dashboard javascript and have it upload from there instead (thus bypassing my servers)? If it is of any use, I am currently using django with python 3.5 -
Django - Get a list of repeated queryset results from a list of values
I have the following model named Profile, which has a field named address class Profile(models.Model): user = models.OneToOneField(User, primary_key=True) address = models.CharField(max_length=100, blank=True, null=True) Anyway, I have a list like this one, which contains the primary keys of certain users. pks=[1, 1, 2, 1, 3] I need to make a Queryset which filters the users who are in that list, returning the value of its address no matter how many times one user appear in the pks list. Hence, I have done the queryset as follows: Profile.objects.filter(pk__in=pks).values_list('address', flat=True)) The problem is that I'm getting something like this: ['address 1', 'address 2', 'address 3'] And I need something like this: ['address 1', 'address 1', 'address 2', 'address 1', 'address 3'] P.S: I'm trying to avoid using a for loop, because the pks list can grow very large, and it wouldn't be efficient for the DB... So, any help? -
Pass model objects to choices field in django
I have a model called Student that has a manytomany relationship with a model called Courses. I have another model called Attend in which I want to get all the courses the student is taking and pass it in as a select menu containing the courses the student is taking. I tried to get the id using the foreign key "student" and then get courses belonging to that student and put it in a list and pass it to choices but it didn't work obviously. I would like to know how I can get the courses belonging to the student to appear in the select menu. Here is my model. class Attend(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, default="") time_signed_in = models.DateTimeField(auto_now_add=True) isSignedIn = models.BooleanField(default=False) # Below does not work, I get an error 'ForeignKey' object has no attribute 'id' #courses = User.objects.get(id=student.id).courses course = models.ForeignKey(Course, on_delete=models.CASCADE) -
SyntaxError at / invalid syntax (views.py, line 221)
views.py: @login_required def ListEspeci(request, id_especialidad): especialidad = Especialidad.objects.get(id=id_especialidad) if request.method == 'GET': if estadis = Especialidad.objects.filter(estadistica=0) ---------->#221! form = EstadisticaForm(request.POST, instance=especialidad) if form.is_valid(): form.save() return HttpResponseRedirect('/solicitar/lista/%s/' % id_especialidad) return render(request, 'estadis.html', {'form':form}) else: pedido = Pedido.objects.filter(especialidad=especialidad) return render(request, 'index2.html', {'pedido':pedido, ' especialidad':especialidad}) models.py: class Especialidad(models.Model): nombre = models.CharField(max_length=50, blank=True) estadistica = models.IntegerField(blank=True) encargado = models.ForeignKey('Encargado', blank=True, on_delete=models.CASCADE) First I capture the id of the Specialty model, then I believe in the conditional if, if the statistical field of the specialty is equal to 0, it sends me a template of the model form to enter the quantity, and otherwise it passes the template where a table. Maybe I have not formulated well the sight for the desired logic, some help? please -
Django - passing model object datas to template
I could'nt solve it. I want to pass specific datas from model to template. I had tried something could'nt figure it out.Can anyone help me out , should I need to write logic to view.py or is there easy way to pass data. class Receipt(models.Model): amount = models.DecimalField(max_digits=5, decimal_places=2) vat = models.DecimalField(max_digits=5, decimal_places=2) total_amount = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return str(self.total_amount) #My view.py class IndexView(TemplateView): template_name = "index.html" model = Receipt class DetailView(TemplateView): template_name = "detail.html" model = ReceiptItem #index.html <div class="panel panel-default"> <div class="panel-heading">Market</div> <table class="table"> <tr> {% for amount in objects %} <td>{{ amount }}</td> <td>{{ vat }}</td> <td>{{ total_amount }}</td> {% endfor %} </tr> </table> </div> -
Different static files in different templates
I had stuck in static files. When I tried to {% load staticfiles %} in my main template (e.x. {% static "main.js" %}), it works great in main.html template. But when I tried to extend main.html template by detail.html template, and put there another static file (e.x. {% staticfiles 'fancybox.js' %}), it displays only <script type="text/javascript" src="static/main.js"></script> instead <script type="text/javascript" src="static/main.js"></script> <script type="text/javascript" src="static/fancybox.js"></script> in my detail.html. Can somebody help me with solution? Thanks mates. -
Custom Django Form Not Displaying - Using Wagtail
Wagtail Blog Site - Comment Model Form Issues I'm creating a blog site, using Wagtail, and I've run in to a snag. I've added a Comment Model to my page, which I can add comments through the admin section and they display on the correct posts, but the comment form I've created is not displaying for some reason. Here's my relevant code. Any tips on where I went wrong would be greatly appreciated. blog/models.py class Comment(models.Model): post = models.ForeignKey(BlogPage, related_name='comments') author = models.CharField(max_length=250) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __unicode__(self): return self.text def __str__(self): return self.text blog/forms.py from .models import Comment from django import forms class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) blog/views.py from django.shortcuts import render from forms import CommentForm def view_post(request, slug): post = get_object_or_404(BlogPage, slug=slug) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect(request.path) return render_to_response('/blog/blog_page.html', { 'post': post, 'form': form, }, context_instance=RequestContext(request)) blog_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-blogpage{% endblock %} {% block content %} <div class="section"> <div class="container"> <h1 class="title">{{ page.title }}</h1> <p class="meta subtitle">{{ page.date }}</p> … -
Django rest framework : extend user model for customer - one to one field
I have a customer model in Bcustomer app that extends the django User model, So I will save the basic details such as name in User table and the remaining data (city, etc) in customer table. When I call the below code through API, it shows the following error. But data is saving in the tables. I also want to implement the get and put calls for this api. Got AttributeError when attempting to get a value for field `city` on serializer `CustomerSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'city'. my Bcustomer/models.py class BCustomer(models.Model): customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, blank=True ) address = models.CharField(max_length=50) city = models.CharField(max_length=256) state = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, on_delete=models.CASCADE, related_name='customer_creator') #more fields to go def __str__(self): #return str(self.name) (This should print first and last name in User model) class Meta: app_label = 'bcustomer' my Bcustomer/serializers.py from django.contrib.auth import get_user_model from models import BCustomer class CustomerSerializer(serializers.HyperlinkedModelSerializer): city = serializers.CharField() class Meta: model = get_user_model() fields = ('first_name', 'email','city') def create(self, validated_data): userModel = get_user_model() email = validated_data.pop('email', None) first_name = validated_data.pop('first_name', None) city = … -
Getting POST data not returning expected results
I get post data from another site and I printed the results to a file f1.write(request.POST) and get this <QueryDict: {u'action': [u'scheduled'], u'appointmentTypeID': [u'2598966'], u'calendarID': [u'1036269'], u'id': [u'89298741']}>0 All I want is the id but when I do something like this this_id = request.POST.get('id') this_id ends up having one more digit at the end and the second to last digit ends up being incorrect. Something like this for example 892987480 I understand the that the data is a application/x-www-form-urlencoded POST request, so maybe I need to decode it somehow, but I don't know how. -
Django sending email: Connection unexpectedly closed
Getting error "Connection unexpectedly closed" both through site and shell. Code: Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.live.com' DEFAULT_FROM_EMAIL = 'username@hotmail.com' EMAIL_HOST_USER = 'username' EMAIL_HOST_PASSWORD = 'Hunter2' EMAIL_USE_TLS = True EMAIL_PORT = 587 Views.py: send_mail( 'Test', 'test', 'example@hotmail.com', ['example@hotmail.com'], fail_silently=False, ) Any help would be greatly appreciated. Thanks in advance -
Easiest way to run python script with parameters on a web server
Thought this would be straightforward, but it's giving me a lot of trouble. What's the simplest way to run a python script with params on a web server? I've tried Node, but had a lot of trouble with spawning child processes, tried PHP but ran into a similar problem and just couldn't get exec to work for even the simplest script. Just spent a while trying Django, but that turned out to be far too involved. How can I do this without re-inventing the wheel? For example, take the following request: www.example.com/someprogram?foo=bar&bar=baz And render the output from a script run with those params: python someprogram.py foo bar -
Django URL with space
I have a URL that looks like this in my urls.py: url(r'^ex/(?P<example>)$', views.example, name = 'example') but the variable I have has a space in it ex. This Example and the page is giving me an error. -
in django, let me know drop- down list
i want to make nationality drop down list i know how to make it, the problem is the number of nationality is over 100... i do not think i can type all nationalities... can you help me..? here is my model Nationality_CHOICES = ( ('AFGHANS', 'Afghans'), ('ALBANIANS', 'Albanians'), ...... ) class Student(models.Model): Nationality = models.CharField(max_length=2, choices=Nationality_CHOICES, null = False) here is all the nationalities : Afghans Albanians Algerians Americans Andorrans Angolans Argentines Armenians Aromanians Arubans Australians Austrians Azerbaijanis Bahamians Bahrainis Bangladeshis Barbadians Basotho Basques Belarusians Belgians Belizeans Bermudians Boers Bosniaks Brazilians Bretons British British Virgin Islanders Bruneians Bulgarians Macedonian Bulgarians Burkinabès Burundians Cambodians Cameroonians Canadians Catalans Cape Verdeans Chadians Chileans Chinese Colombians Comorians Congolese Croatians Cubans Cypriots Turkish Cypriots Czechs Danes Dominicans (Republic) Dominicans (Commonwealth) Dutch East Timorese Ecuadorians Egyptians Emiratis English Eritreans Estonians Ethiopians Falkland Islanders Faroese Finns Finnish Swedish Fijians Filipinos French citizens Georgians Germans Baltic Germans Ghanaians Gibraltar Greeks Greek Macedonians Grenadians Guatemalans Guianese (French) Guineans Guinea-Bissau nationals Guyanese Haitians Hondurans Hong Kong Hungarians Icelanders I-Kiribati Indians Indonesians Iranians Iraqis Irish Israelis Italians Ivoirians Jamaicans Japanese Jordanians Kazakhs Kenyans Koreans Kosovars Kurds Kuwaitis Kyrgyzs Lao Latvians Lebanese Liberians Libyans Liechtensteiners Lithuanians Luxembourgers Macao Macedonians Malagasy Malaysians Malawians … -
How to storage objects for communication without the database in Django?
I'm working on a project where i do need to do a communication in 3 parts. Let me explain: 1.- The user fills a form, which is used to create a set of objects from the models. This objects are not saved in the database on this moment. All the objects are related between them. 2.- This objects must be saved in some way for an admin user to check the data and decide if proceed to save it, or if any element is invalid and reject the form. 3.- If the admin decide that the data is correct, select an option to send a .save() to add the data to the database. At least that's the idea i have on how should work. I decided to create the objects before send it to the admin because it sounded easier to show that if i sended the request.POST and the request.FILES. My problem is that i don't know where could save the objects to show it to the admin when he connects(There are 2 types of users, Normal and Admin, the normal are the ones that fill the forms, the admins only check it, the two of them has their … -
cookiecutter django edit email
So I'm using cookiecutter-django, which has django-allauth for user registration and django-anymail as a backend for sending email. I want to customize the emails that are being sent to the users when they sign up or forget their passwords. I can't seem to find the code in my cookiecutter-django project, it seems like its done from a template from outside my app (maybe in anymail module), so I don't know where or how should I write a customized email message. Also, since the sign up template doesn't have a view inside my project I can't find my way through the debugger. This is the url code that calls the sign up template: <li class="nav-item mx-md-3"> <a id="sign-up-link" class="nav-link" href="{% url 'account_signup' %}"><i class="fa fa-user-plus"></i> {% trans "Sign Up" %}</a> </li> And this is the URL configuration inside my project: # User management url(r'^users/', include('solucionesverdesweb.users.urls', namespace='users')), url(r'^accounts/', include('allauth.urls')), -
How can I display my dynamic image as a background?
I am developing a django aplication, which is a simple website where I can put many images dynamically, from my admin site(models). I know how to display these images in my html template with one loop, but I don't know how I can display these images as background or header in my html template. Have anyone a idea how my html would be? Have I to use css to do it? -
Inserting template date tag in Django
I'm attempting to insert a date tag in my Django template, and I've read the Django documentation but I can't seem to get it to work. Here's what I've got in my latest attempt, which basically came directly from my understanding of the docs and example within them: {{ datetime|date:"l" }} Now, I haven't done anything in Python to create a view or a model using any importation of datetime, and the Django documentation didn't implicitly state I needed to beforehand. I'm using Django 1.10.6 -
Django - add image to list display in django admin
Please help me. I gave up. I am trying to add additional field to my django admin. I would like to insert image thumbnail there. This is part of my admin.py: class SiteAdmin(admin.ModelAdmin): list_display = ('is_active', 'name', 'description', 'keywords', 'date') fields = ('name', 'url', 'category', 'subcategory', 'category1', 'subcategory1', 'description', 'keywords', 'date', 'group', 'email', 'is_active') readonly_fields = ('date',) list_display_links = ('name',) list_filter = ('is_active',) actions = [activate_sites, deactivate_sites] I wolud like to add 'image' to list_display. Images are generating by thumbalizr. I have a method in models.py: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'SubCategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True, blank=True, null=True, default=None) name = models.CharField(max_length=70, verbose_name="Tytuł") description = models.TextField(verbose_name="Opis") keywords = MyTextField(max_length=100, verbose_name="Słowa kluczowe") date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) category1 = models.ForeignKey('Category', related_name='category', blank=True, null=True, default=None) subcategory1 = ChainedForeignKey( 'SubCategory', chained_field='category1', chained_model_field='category', related_name='subcategory', show_all=False, auto_choose=True, blank=True, null=True) group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'), ('premium', 'premium')), default='podstawowy', help_text="<div id='group'><ul><li>You can add site to 2 <b>categories</b></li></ul></div>") email = models.EmailField(help_text='Podaj adres email') def get_absolute_url(self): return reverse('site', args=[str(self.category.slug), str(self.subcategory.slug), str(self.id)]) def get_thumb(self): host = urlparse(self.url).hostname if host.startswith('www.'): host = host[4:] thumb = 'https://api.thumbalizr.com/?url=http://' + host + '&width=125' return thumb It is get_thumb() method. How can I take image to every … -
How do I get multiple post requests from Django and Ajax on the same page working?
I have been banging my head over this all day long. Nothing seems to be working. Here's my situation. I have a Django form with two fields: redirect_from, redirect_to. There are two submit buttons to this form: Validate and Save. When the page loads, Submit is hidden and only Validate is shown. So now, when the user fills the two fields and clicks Validate I used Ajax to confirm that both the fields are the same. If they are, show the Save button. Clicking the Save button should save the form to the database. I also put in an oninput listener so that after the Ajax call is made, if the user tries to change the data, the Save button is hidden again and he has to now evaluate it again. Apparently this is supposed to be easy with Ajax, but I'm finding it extremely difficult and frustrating. This is my code so far: My Template: form method="post"> {% csrf_token %} {% include 'partials/form_field.html' with field=form.redirect_from %} {% include 'partials/form_field.html' with field=form.redirect_to %} <button id="submit" class="btn btn-lg btn-primary" type="submit" name="save" value="Save">Save</button> <button id="ajax_submit" class="btn btn-lg btn-primary" type="submit" name="ajax" value="Ajax">Validate</button> </form> {% endblock %} {% block extra_scripts %} {{ block.super }} … -
File size upload restrictions in Django when using Django-filer
I have no idea where else to post this, I am using django-filer (https://django-filer.readthedocs.io/en/latest/) and running into limits when trying to upload files. The problem is the software fails silently and does not give any errors and acts like it uploaded just fine. While I understand Django-filer is niche (no support forums it seems), I am trying to figure out where to start looking to even begin to trouble shoot my file over 2GB not being uploaded. I guess I should say it doesn't fail silently, but the errors I see in the var/log/httpd/error_log do not really make sense to me: [Wed Mar 15 16:19:16.107217 2017] [authz_core:debug] [pid 15399] mod_authz_core.c(809): [client 172.20.0.80:43660] AH01626: authorization result of Require all granted: granted, referer: https://somesite.com/admin/filer/folder/23/list/?order_by=-modified_at [Wed Mar 15 16:19:16.107234 2017] [authz_core:debug] [pid 15399] mod_authz_core.c(809): [client 172.20.0.80:43660] AH01626: authorization result of <RequireAny>: granted, referer: https://somesite.com/admin/filer/folder/23/list/?order_by=-modified_at [Wed Mar 15 16:19:16.614657 2017] [:info] [pid 16476] mod_wsgi (pid=16476): Initializing Python. [Wed Mar 15 16:19:17.235272 2017] [:info] [pid 16476] mod_wsgi (pid=16476): Attach interpreter ''. [Wed Mar 15 16:19:17.236272 2017] [proxy:debug] [pid 16476] proxy_util.c(1843): AH00925: initializing worker proxy:reverse shared [Wed Mar 15 16:19:17.236298 2017] [proxy:debug] [pid 16476] proxy_util.c(1885): AH00927: initializing worker proxy:reverse local [Wed Mar 15 16:19:17.236353 2017] [proxy:debug] … -
MultiValueDictKeyError at , when rendering multiple formsets with prefixes
Hello folks Im back with a new riddle . Im trying to render a form and 2 formsets and to do so I use prefixes. But I dont seem to understand how to use prefixes . The result is that when I try to add more forms to the formsets with an add button i get the error mentioned above.If you can provide me with a solution or even show me some tips i would be glad . Here is my views.py(i dont include the imports): def get_researchnew(request): change_crit = '0' change_alt = '0' CriterionFormSet = formset_factory(CreateCriterionForm,extra=1,can_delete=True) AlternativeFormset = formset_factory(CreateAlternativeForm,extra=1,can_delete=True) if request.method == 'POST': if 'add_criterion' in request.POST: post_data = request.POST.copy() post_data['criterion_form-TOTAL_FORMS'] = int(post_data['criterion_form-TOTAL_FORMS']) + 1 research_form = CreateResearchForm(post_data,prefix='research_form') criterion_formset = CriterionFormSet(post_data, request.FILES,prefix='criterion_form') alternative_formset = AlternativeFormset(post_data,request.FILES,prefix='alternative_form') change_crit ='1' elif 'add_alternative' in request.POST: post_data = request.POST.copy() post_data['alternative_form-TOTAL_FORMS'] = int(post_data['alternative_form-TOTAL_FORMS']) + 1 research_form = CreateResearchForm(post_data,prefix='research_form') criterion_formset = CriterionFormSet(post_data, request.FILES,prefix='criterion_form') alternative_formset = AlternativeFormset(post_data,request.FILES,prefix='alternative_form') change_alt = '1' elif 'submit' in request.POST: research_form = CreateResearchForm(request.POST,prefix='research_form') criterion_formset = CriterionFormSet(request.POST, request.FILES,prefix='criterion_form') alternative_formset = AlternativeFormset(request.POST,request.FILES,prefix='alternative_form') if research_form.is_valid() and criterion_formset.is_valid() and alternative_formset.is_valid(): research_form.save() research_instance = research.objects.last() for form in criterion_formset: if form.is_valid(): instance = form.save(commit=False) instance.criterion_research = research_instance instance.save() for form in alternative_formset: instance = form.save(commit=False) instance.alternative_research = research_instance …