Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Creating a custom Slug
This is how I'm adding a slug in my django app, class Question(models.Model): question_text = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True) def _get_unique_slug(self): slug = slugify(self.question_text) unique_slug = slug num = 1 if Question.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 elif unique_slug == '': # Problem return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() return super(Question, self).save() Problem is that in case slug is '' then I want to auto add the number 1,2,3...n How can I do that? -
view uploaded file in django
working on a file uploading for my project. i want to view my files that has been uploaded in my django project.can someone help me please## here is the code for the project.i want to view all the images that i have uploaded on my index.html webpage : #models.py from django.db import models class File(models.Model): file = models.FileField() def __str__(self): return self.file.name #views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage from file.models import File import os, datetime # Create your views here. def index(request): if request.method == 'POST' and request.FILES['file']: upload_file = request.FILES['file'] extension = os.path.splitext(upload_file.name)[1] rename= datetime.datetime.now().strftime("%y_%m_%d %H_%M_%S") + extension fss = FileSystemStorage() filename = fss.save(rename, upload_file) file = File(file=rename) file.save() upload_file_path = fss.path(filename) return render(request, 'file/index.html',{'upload_file_path' : upload_file_path}) else: return render(request, 'file/index.html') #index.html {% extends 'file/base.html' %} {% block body %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <input type="file" name="file" required="required"/> <br /> <button type="submit" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-upload"></span> Upload</button> </div> </form> {% if upload_file_path %} Uploaded at: <label class="text-primary">{{ upload_file_path }}</label> {% endif %} <br><br> <img src="{{ file.file.url }}" alt="..."> {% endblock %} -
How to include Django CSRF token in request through ngrok?
I am building a Django app that will be hosted on a local network and perform authentication using Facebook Login. Since Facebook Login requires the callback address for a login to either be localhost or publicly-addressable, I'm using ngrok to create an address for Facebook to return data to. After the user logs in with Facebook, I perform a POST with AJAX from the template with their data to a local view (/fb_login) which saves to my database in Django. Since authentication is based on this database, I don't think it's wise to avoid the CSRF checks Django performs on this view. To include the CSRF token in the POST to /fb_login, I'm using the following which a few forums suggested: $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); This should only include the CSRF token to relative URLs (which I understand to be the best practice). When I run the server on localhost and perform the Facebook Login from the same machine, this works fine. However, when I run the system on localhost and access it through ngrok from another machine on … -
How do I join a model after using `.objects.values()`?
I'm making a custom Django manage.py command. Here is the part of it relevant to my question. Model = apps.get_model(app_label="my_app", model_name="MyModel") x = Model.objects.values(*options["fields"].split('|')): I want to join Model with another model, SomeOtherModel. Model has a foreign key field named fk that connects to the primary key for SomeOtherModel. How do I modify my code above to join Model with SomeOtherModel? -
Django: Slug Field not Working
I've created a django app in which a user can ask a question. It seems working fine where Users can ask a question, but there's a huge bug in it. And the problem is that just in case if user types something like @@@, %%%%%%% or ??? in the question form & submit it, it saves the question in database & keeps the slug field empty. And since the slug field is empty entire app breaks down, because slug is required in the URL. Here's my model, class Question(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) question_text = models.CharField(max_length=250) slug = models.SlugField(max_length=255, unique=True) def create_slug(instance, new_slug=None): slug = slugify(instance.question_text) if new_slug is not None: slug = new_slug qs = Question.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" % (slugify(instance.question_text), qs.first().id) return create_slug(instance, new_slug=new_slug) else: return slug views.py def ask_ques(request): if request.method == 'POST': form = MyForm(request.POST or None) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.save() return HttpResponseRedirect(new_form.get_absolute_url()) else: form = MyForm() return HttpResponse('') form.html <form action="{% url 'myapp:ask_ques' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="question_text" required id="id_question_text" maxlength="250"/><br /> <input type="submit" value="Ask" /> </form> How can we fix this issue? -
How Entry.objects.filter() or Entry.objects.get() works?
How Entry.objects.filter() or Entry.objects.get() works.Do they scan the whole database one by one and then give the resulting object.What happens when we do search on the basis primary key value of objects? -
What are good books or materials to gain in-depth knowledge in Django? [on hold]
Im a newbie. Please be helping me out.What are good books for to become a sound learner in django? -
Django asign custom default value to Charfield
I am having some trouble asigning default values to a new object field on Django class Contrato(models.Model): empleado = models.ForeignKey(Empleado, on_delete=models.CASCADE, null=True, blank=True) ref_contrato = models.CharField(max_length=30, default=incrementa_contrato(), null=True, blank=True) # Empleado -> Varios contratos I would like to create a custom autoincrement field on ref_contrato, I have the format but cannot call the function to return the value. I would like to send "self" to the function, there, I would extract the object info, proccess it, and return a new value to be set as ref_contrato. The function: def incrementa_contrato(): # do something return '' # return new default value for ref_contrato I didn't put the code to do the new value because it is not important. I just I am having trouble calling this function from ref_contrato -> default. Which option do you think is better? I tried overriding init function, save() (discarded), and this one I showed you. Thanks in advance -
how to get value equate to less available in queryset
How to get a record in the database, if the form comes a value that you want to equate to less available in queryset'e. Suppose we have records record | number | number_2 ______________________________________ 1 | 5 | 2.00 2 | 3 | 1.00 if the form is nubmer = 3 it is possible to make get Mode.objects.get (number=number) but if number = 4 then get is not already done, because there is no such record, in this case, you need to get a record that will be equal to or less than one order of the number that comes through the form -
How to prefetch_related in reverse of a Django ManyToMany field
In Django, if I have a ManyToManyField: class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) I can minimize hits on the database when accessing the Pizza model's toppings field by using prefetch_related(): Pizza.objects.all().prefetch_related('toppings') How can I do the same but in reverse, to prefetch the pizza_set from a Topping queryset? This doesn't work, and I couldn't find it in the docs: Topping.objects.all().prefetch_related('pizza_set') -
Django message framework rendered in a boostrap Modal
I have a Django App. And I would like to give a Welcome Message after the user signed in. I know how to do it using the framework message but the thing is I would like instead of rendering it within a div I would like to render it within a modal ! I tried : <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}">{{ message }}</li> {% endfor %} </ul> {% endif %} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> But as you may imagine it does not work the modal does not render. Do you have any idea how could I make it work. Actually it is more than a welcome message, it is a welcome and a small tutorial. Thx you very much -
Bind validation and lookup errors to the initial view of a Django form?
I'm working in Django 2.0 and I have a form where a user can submit a postcode. I'd like a forms setup that supports the following: A check to see if it's a valid postcode (as a custom validator inside my forms.py) - if not, return a message to the user. If it's a valid postcode, use a third-party service with requests to look up the matching area for the postcode. If the third-party service is down, or returns no results, return to the form with a message to the user. If the third-party service returns a result, check for a matching area in my local database: if one is found, forward the user to the appropriate area page. If it isn't, return to the form with a message to the user. Here's my code right now. First, forms.py - the print statement in clean_postcode never appears, so I don't think this is ever getting run: # forms.py class PostcodeForm(forms.Form): postcode = forms.CharField(required=True, widget=forms.TextInput() def clean_postcode(self): postcode = self.cleaned_data.get('postcode', '') print('clean_postcode', postcode) if not is_sensible_postcode(postcode): # Custom method raise forms.ValidationError(_("Please enter a valid postcode"), code='invalid') return super(PostcodeForm, self).clean() Next views.py. I'm trying to use request.session to bind errors in to … -
How to Build RSS Reader Django
How would one start out building an RSS reader of Django? I'm pretty new to the space (only built basic blogs following the tutorials), but I'm looking to finally start a project I've been working on. (eventually it'll become a full-fledged news app) I've found two pretty good examplesNewsBlur and Django-Yarr but I don't even know where to begin with breaking them down. So much of the code just goes over my head Anyway, I would really appreciate any insights or advice for this project of mine. Thanks in advance. -
Whiy django internationalization dont translate "About" string?
I'm using django 2.0, when traslate strings in .po file all works good but string with mgid "About" in tamplates not translating -
Django 2.0 Trying to Grab the primary key with regular Expressions but im getting 404
This is my Code .. urlpatterns =[ path('',views.School_Lview.as_view(),name='list'), path('(?P<pk>\d+)/',views.School_Dview.as_view(),name='detail') ] I am trying to get this template to work {% for school in schools %} <h2><li><a href="{{school.id}}"> {{school.name}}</a></li></h2> {% endfor%} -
Django when looping over a queryset, when does the db read happen?
I am looping through my database and updating all my Company objects. for company in Company.objects.filter(updated=False): driver.get(company.company_url) company.adress = driver.find_element_by_id("address").text company.visited = True company.save() My problem is that it's taking too long so I wanted to run another instance of this same code, but I'm curious when the actual db reads happen. If company.visited get's changed to True while this loop is running, will still be visited by this loop? What if I added a second check for visited? I don't want to start a second loop if the first instance isn't going to recognize the work of the second instance: for company in Company.objects.filter(updated=False): if company.visited: continue driver.get(company.company_url) company.adress = driver.find_element_by_id("address").text company.visited = True company.save() -
Postgresql: Efficiently query the ids of existing objects, reading attribute values from a huge csv file
In a postgresql database: class Persons(models.Model): person_name = models.CharField(max_length=10, unique=True) The persons.csv file, contains 1 million names. $cat persons.csv Name-1 Name-2 ... Name-1000000 I want to: Create the names that do not already exist Fetch the ids of the names contained in the csv file to use them for creating a many-to-many relation. My approach: Use the COPY command or the django-postgres-copy application that implements it. Also take advantage of the new Postgresql-9.5+ upsert feature. Now, all the names in the csv file, are also in the database. I need to get their ids either in memory or in another csv file with an efficient way: Use Q objects list_of_million_q = <iterate csv and append Qs> million_names = Names.objects.filter(list_of_million_q) or Use __in to filter based on a list of names: list_of_million_names = <iterate csv and append strings> million_names = Names.objects.filter( person_name__in=[list_of_million_names] ) or ? I do not feel that any of the above approaches for fetching the ids is efficient. -
Dont work selects on form when clone form
I have model form wich i am rendiring with django-semanticui-forms <div class="cloned-row"> <div class="row"> <div class="col"> {% render_field from.filed1 %} </div> <div class="col"> {% render_field from.filed1 %} </div> </div> <a id="add_form">add one more</a> </div> and js wich are cloning this row $("#add_form").click(function() { $(".cloned-row:first").clone().insertAfter(".cloned-row:last"); }); At first its clone with values and when fields are selectable (with semantic dropdown) it doesnt work. And form create one record here is rendered html with cloned row <div class="cloned-row"> <div class="row"> <div class="col"> <div class="required field"><label for="id_quanity">Quanity</label><div class="ui selection dropdown" tabindex="0"><input name="quanity" value="1" type="hidden"><i class="dropdown icon"></i><div class="text">1</div><div class="menu" tabindex="-1"><div class="item" data-value="50">50</div><div class="item" data-value="100">100</div></div></div></div> </div> <div class="col"> <div class="required field"><label for="id_price">Price</label><input type="number" name="price" value="0" required="" id="id_price"></div> </div> </div> <a id="add_form">add row</a> -
django form view show error or not
I'm making a little personal project using Django framework and I get one question while making login view with django form. I was struggled to show form error messages in my template, and I found a cause in my view. This is view that showing error message def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): form.login(request) return redirect('/') else: form = LoginForm() context = { 'form': form, } return render(request, 'member/login.html', context=context) another view that dosen't showing error message def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): form.login(request) return redirect('/') form = LoginForm() context = { 'form': form, } return render(request, 'member/login.html', context=context) and this is my template <form action="{% url 'login' %}" method="post"> {% csrf_token %} {{ form.username}} {{ form.password }} {{ form.non_field_errors }} <button id="login-btn" class="btn btn-default" type="submit">login</button> The difference is just using elsephrase or not in view. I think whether using elsephrase or not, there two views have logically same result... I don't understand difference of those two views. Is there any clue to understand the differece of those two views?.. Thanks -
django paypal paypalrestsdk - how to perform payment ? didn't return an HttpResponse object
I am trying to integrate paypal with my django app using paypalrestsdk https://github.com/paypal/PayPal-Python-SDK I use the same code to generate payment request views.py: def payment_create(request): paypalrestsdk.configure({ "mode": "sandbox", # sandbox or live "client_id": "xxxxx", "client_secret": "xxxxxx" }) payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "paypal"}, "redirect_urls": { "return_url": "http://localhost:3000/payment/execute", "cancel_url": "http://localhost:3000/"}, "transactions": [{ "item_list": { "items": [{ "name": "item", "sku": "item", "price": "5.00", "currency": "USD", "quantity": 1}]}, "amount": { "total": "5.00", "currency": "USD"}, "description": "This is the payment transaction description."}]}) if payment.create(): print("Payment created successfully") else: print(payment.error) however it produced this error: ValueError at /payment/ The view somecomapp.views.payment_create didn't return an HttpResponse object. It returned None instead. The question is what is the problem with this and how to generate a proper paypal payment with django ? -
django how to rename PK field in a url
if anyone can help me with how to rename pk for a class(table) when I use it in the urlpattern. (my goal is using many classes(tables ) PK in the same url and I want to know how to rename PK field for each table) My code below is just for one class(table) for simplicity: models.py: class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return str(self.name) def get_absolute_url(self): return reverse("basic_app:school_detail",kwargs={'pk':self.pk}) views.py: class SchoolListView(ListView): model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_details' model = models.School template_name = 'basic_app/school_detail.html' and my current urls.py (which I want to edit) : urlpatterns = [ url(r'^$',views.SchoolListView.as_view(),name='school_list'), url(r'^(?P<pk>\d+)/$',views.SchoolDetailView.as_view(),name='school_detail'),] So my goal is to make the urls.py file look like this(school_pk instead of pk): urlpatterns = [ url(r'^$',views.SchoolListView.as_view(),name='school_list'), url(r'^(?P<school_pk>\d+)/$',views.SchoolDetailView.as_view(),name='school_detail'),] I know I should add a function below class SchoolDetailView in views.py but I don’t know how ? I am still learning so any help will be highly appreciated..Thanks in Advance -
Use of httpResponse django
As far as I can think of, HttpResponse is used for REST application. I cannot figure out any other use of httpresponse. I want to understand other uses of HttpResponse. Help by anyone would be very appreciated. Thanks in advance. -
Can a user create forms in django?
I'm officially stuck. I'm am building a django application for work purposes. Staff users should be able to create forms using the django admin. The forms should the be able to display on the website with variable labels. Check link for html setup. The labels above the inputs should be editable from the django admin for each specific form. I would also like for users to be able to create as many fields as they like. So for example in the image in the link, there are 8 input fields. Is there any way to do this with a django form/model? I looked at the django forms-builder extension. Basically I want the functionality of being able to press "add another field", but with everything else that comes with the forms-builder package. The form should be stored in the database attached to the corresponding label of that field. I've created my own abstract user, and one user should only be able to fill out a particular form once. But should be able to fill out different forms though. One form should be able to be filled out by many users. Every idea is much appreciated! -
Django model property: missing 1 required positional argument:
models.py class Thread(models.Model): users = models.ManyToManyField(settings.AUTH_USER_MODEL, through="UserThread") @property def from_user(self, current_user): for u in self.users.all(): if u.username != current_user.username: return u else: pass My app contains 1 to 1 conversations, I coded this property to return the opposite user of the thread (e.g. the person I am speaking to). However, when I try to: u = User.objects.get(pk=1) t = Thread.objects.get(pk=1) t.from_user(current_user=u) I get the error that TypeError: from_user() missing 1 required positional argument: 'current_user' -
How to update modified_by field with CurrentUserDefualt
i get this error when i am trying to update modified_by field Tried to update field sales.CustomersTag.modified_by with a model instance, <SimpleLazyObject: <UserProfile: Admin>>. Use a value compatible with CharField. this is my serializer.py: class CustomersTagSerializer(serializers.ModelSerializer): created_by = serializers.CharField(read_only=True, default=serializers.CurrentUserDefault()) modified_by = serializers.CharField(read_only=True, default=serializers.CurrentUserDefault()) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.modified_by = validated_data.get('modified_by', instance.modified_by) instance.save() return instance class Meta: model = models.CustomersTag fields = ( 'id', 'name', 'created_date', 'modified_date', 'created_by', 'modified_by', ) and this my view.py: class CustomerTagGetIdPutView(generics.RetrieveAPIView, mixins.UpdateModelMixin): permission_classes = (AllowAny,) queryset = models.CustomersTag.objects.all() serializer_class = CustomersTagSerializer def get_object(self): id = self.kwargs['id'] obj = generics.get_object_or_404(models.CustomersTag, id=id) return obj def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) i tried alot to solve this problem but i can't .. any one can help me for this problem