Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
imagefield is loading properly in one view but not the other
When a user signs in, they must create a new profile. This uses in the views.py 'def profile_new()'. I cannot get this view to properly save the image they upload. BUT when they edit their profile with 'def profile_edit()' it does upload the image successfully. Both view functions use 'profile_edit.html'. https://github.com/cbaldwin20/project_12/blob/master/p_12/social/views.py#L266 -
What are naming rules of templates in django class based views
When using class-based views, many of them have default rule to automatically search a template so we don't need to specify it every time we use a class-based view. But I can't find any article writes about how default naming is done. What are the rules to define default template name? -
How get resolution of SVG image in python?
Is there any way to get the resolution of an SVG image in python. All other image resolution works fine with PIL. I don't get any solution for SVG image.I am using following code to get the resolution but it works only for some cases, data = request.FILES['picture'] tree = ET.parse(data) root = tree.getroot() h = int(root.attrib['height']) w = int(root.attrib['width']) print(h, w) -
Python : How to remove timezone from PostgreSQL Timestamp field?
In PostgreSQL database, timestamp datatype column has value as : 2018-06-08 12:35:09 But, While retrieving data using django, data is returned as (datetime is combining timezone) : "2018-06-08T12:35:09.225" How can I convert this datetime object to "DD-MM-YYYY HH:MM:SS" format in django ? -
how to use django-reversion to save possible future objects?
I'm creating a website with Django using the Rest Framework, it enables users to modify or create new objects, kinda like Wikipedia where anyone can make edits but it has to go through a process to be accepted. I understand the default behavior for versioning is to save previous changes, but I'd like to use django-reversions or a library to keep track of possible future versions of my models. (Until they get approved by selected users) The thing is the default behavior in django-reversion is that we have to make change to our model object to create a new version, I would instead like to create a new version and then if accepted by the selected users, apply the changes to the object. My question is: how could I create versions of models without altering the original object? I still haven't quite figure out the concept of revision blocks which is why I may be asking this question. If you think there's a better alternative to my problem I'm open to suggestions Link to django-reversion repo: https://github.com/etianen/django-reversion -
NoReverseMatch at /post/new/ Reverse for 'post_publish' with keyword arguments '{'pk': ''}' not found.
base.html <ul class= 'nav navbar-nav navbar-right'> {% if user.is_authenticated %} <li> <a href="{% url 'post_new' %}">New post</a> </li> <li> <a href="{% url 'post_draft_list' %}">Drafts</a> </li> <li> <a href="{% url 'logout' %}">Log out</a> </li> <li> <a >Welcome: {{ user.username }}</a> </li> {% else %} <li> <a class = 'nav navbar-right' href="{% url 'login' %}"> <span class = 'glyphicon glyphicon-user'></span> </a> <a class = 'nav navbar-right' href= "{% url 'signup' %}"> Sign up</a> post_detail.html {% extends 'blog/base.html'%} {% block content %} <h1 class= 'posttitle loader'>{{ post.title }}</h1> {% if post.published_date %} <div class="date postdate"> {{ post.published_date }} </div> {% else %} <a class = 'btn btn-primary' href=" {% url 'post_publish' pk=post.pk %}">Publish</a> {% endif %} <p class = 'postcontent'> {{ post.text|safe|linebreaksbr}}</p> {% if user.is_authenticated %} <a class= 'btn btn-primary' href="{% url 'post_edit' pk=post.pk %}"> <span class = 'glyphicon glyphicon-pencil'></span> </a> <a class= 'btn btn-primary' href="{% url 'post_remove' pk=post.pk %}"> <span class = 'glyphicon glyphicon-remove'></span> </a> {% endif %} <hr> {% if user.is_authenticated %} <a class = 'btn btn-primary btn-comment' href="{% url 'add_comment_to_post' pk=post.pk %}">Comment</a> {% else %} <a class = 'btn btn-primary btn-comment' href="{% url 'comment_redirect' pk=post.pk %}">Comment</a> {% endif %} <div class="container"> {% for comment in post.comments.all %} <br> {% if … -
Django : Update the categories (selected by Select Field) of all checked products at once
This is my Views. @ login_required def product_list(request): products = ProductBasicModels.objects.filter(whose=request.user).prefetch_related('category', 'category__category').order_by('category__ordering_num') context = {'products': products} return render(request, 'medicalapp_1/products_h.html', context) @ login_required def product_edit(request, pk): post = get_object_or_404(ProductBasicModels, pk=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.whose = request.user post.save() return redirect('product_list') else: form = ProductForm(instance=post) return render(request, 'medicalapp_1/product_add.html', {'form': form}) and my Models class SubCategory(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) name = models.CharField(max_length=50) ordering_num = models.IntegerField(default=0) class Meta: ordering = ['ordering_num'] def __str__(self): return self.name class ProductBasicModels(models.Model): whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) check = models.BooleanField(default=False) # this is for Checkbox. category = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # Change this with Checkbox name = models.CharField(max_length=50) standard = models.CharField(max_length=50) maker = models.CharField(max_length=50, blank=True) outbox = models.CharField(max_length=50, blank=True) extra = models.CharField(max_length=100, blank=True) orderto = models.ForeignKey(OrderCompany, null=True, blank=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Forms class ProductForm(forms. ModelForm): class Meta: model = ProductBasicModels fields = ('check', 'category', 'name', 'standard', 'maker', 'outbox', 'extra', 'orderto') def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' and my Template.. <tbody> {% for product in subcat.list %} <tr> <td class="text-center"> <label class="btn btn-default btn-outline btn-block"> <input type="checkbox" name="product_selected" value="{{product.id}}" /> </label> </td> <td class="text-center">{{ product.name … -
How to connect Informix DB with Django Framework
It seems Django Framework does not have default support for Informix DB. Is there any way by which I can use Informix along with Django? -
Get id value from ModelChoiceField that passes to model
form.py class CreateForm(forms.ModelForm): parent_id = forms.ModelChoiceField(queryset=Category.objects.all(), required = False) name = forms.CharField(max_length = 100) class Meta: model = Category fields = ('parent_id', 'name') models.py class Category(models.Model): parent_id = models.IntegerField() name = models.CharField(max_length = 50) def __str__(self): return self.name view.py class CreateView(TemplateView): template_name = 'create.html' def get(self, request): form = CreateForm() return render(request, self.template_name, {'form' : form}) def post(self, request): form = CreateForm(request.POST) if form.is_valid: form.save() return render(request, self.template_name, {'form' : form}) A form is created in template in create.html My problem is when I choose category from dropdown list by ModelChoiceField for parent_id in create.html, I get the object, not the Id. That's why it displays error "[field name] must be an integer" and can't pass the value to the database as the parent_id is declared Integer at models.py. I need to get the id of selected value and pass it to the database under 'parent_id' field. I know something that is working in view: # parent_id = form.cleaned_data('parent_id').id I got the id by this way but it didn't help me because of form.save() won't take anything from view. it works directly with form.py and just save it here. Thanks in advance -
Django get attribute of field value (of foreign key)
I need to get an attribute (code) from a foreign key (Option) for each field in a model object (Jacket). Obviously what I have is wrong. It only returns the field value's Id. I need field value's attribute 'code'. Template: {% for field, value in jacket.get_fields %} <tr> <td> {{field}} </td> <td> {{value}} </td> </tr> {% endfor %} models.py def get_fields(self): return [(field.name, field.value_to_string(self)) for field in Jacket._meta.fields] -
How to set up celery persistent state database
Celery task revocation is stored in the memory, so it will not persist when worker is restarted. In Celery documentation it can be persisted using command celery -A proj worker -l info --statedb=/var/run/celery/worker.state http://celery.readthedocs.io/en/latest/userguide/workers.html#worker-persistent-revokes but when I run the command, I got error file not found, so I created the file, I ran the command again but then it tells me db type could not be determined. I try to lookup how to set the persistent database to use in celery but got no results. Any help will be apreciated -
Perameters in URL
I'm not sure if this is possible, but here goes. Let's say that the user is on a product page. The url is this: http://localhost:8000/product/?value=1&id=1 When the user clicks on a link (let's say Product Detail) on the page, I want to be able to capture the 'value' of 1 and 'id' of 1 at that time and pass it into the 'productdetail' view before the product detail template is rendered. Is this possible? I've added the following code into my productdetail view, but prod is always equal to None. prod = request.GET.get('value') I'm only using products as an example. Thanks! -
ID not replaced by %s in python django
def read_lf_notifiation(request, id, slug): lf = LostAndFound.objects.get(slug=slug) notf = N_lostandfound.objects.get(id=id, lf=lf) if notf.read == False: notf.read = True notf.save() return HttpResponseRedirect('/lostandfound/%s/?notif_id=%s' %(slug, notf.id)) So read_lf_notification is supposed to read the notfication and redirect to the same page but with the url parameter of notif_id. So I want to give the value of notif_id, the id of notf, but when it redirects to the same page, the response is http://localhost:8000/this-is-slug/?notf_id=id But what I want is http://localhost:8000/this-is-slug/?notf_id=12 What am I doing wrong here? Thanks in advance -
django clean multiple fields at once
I have a form with a start date and end date. How do I clean the form so that the end date comes after the start date. I can clean one field, but not sure how to clean a field while comparing it to another field. Also, when this errors out, I'd like to be able to have the error render in the {{ form.end_date.errors }} as opposed to a general section. Is there a way to do that with forms.ValidationError class ContractChangeForm(forms.ModelForm): ... def clean(self): start_date = self.cleaned_data['start_date'] end_date = self.cleaned_data['end_date'] if end_date < start_date: raise forms.ValidationError(u'Error: The ending date must come after the starting date.',code='invalid_date') return end_date -
Replacing random part of a generated key in Django
I am generating a key in my Django project once a user clicks a button, here is the code in the view: key_value = get_random_string(length=14, allowed_chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') if request.method == "POST": form = PostProposal(request.POST) if form.is_valid(): [...] p = Contract.objects.create( key= key_value, [...] The end result is a string of 14 characters, like this example: I8IH2GPH8RNK6A I am trying to create another key: "key1" tha will replace randomly 4 characters by an underscore, so basically I will have: key: I8IH2GPH8RNK6A key1: I8I_2GP_8_NK_A the replacement should be randomly created when the user clicks the button, and it always concern 4 characters. Any help would be appreciated. Thx -
How to make an audio sharing or streaming site like sportify and SoundCloud with django
I am working on making an audio streaming or sharing site like Soundcloud and sportify using django where users can login create account upload audio files share the audio files ... My question is how do I handle the audio files ... do I host the audio files in a separate server or use one of those cloud server... If this would like to know which server any other think I need to know to go about this project Thank you -
How to see models.ManyToManyField('self') in admin?
I have a field in one of my Model: class Article( models.Model ): title = models.CharField("Title", max_length=255) related_articles = models.ManyToManyField('self') But only super-admins can see this "related_articles" currently, there is no permission to be set for non-superadmin. This is my admin file: class Article_Admin(admin.ModelAdmin): list_per_page = 20 search_fields = ['id', 'title''] list_display = ('title',) fieldsets = [ ( "Article Data", { ' 'fields': ['title',] }), ( "Related Articles", { 'fields': ['related_articles'] }), ] How to set permission for non-superadmin to see models.ManyToManyField('self') in admin page? -
Why is my jquery not making Ajax request?
Server side code is irrelevant at this point because no request is coming through, so the issue must be client side and since I don't know much js - I assume there problem is there. What am I doing wrong? html <input type='button' onclick='UpdateStatus()' value='Status Update'> js function UpdateStatus(){ $.ajax({ type:"GET", url:"/edit_view/", data: { product:product, platform:platform, csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(){ console.log(data($data)); } }); } } Also can't get anything to log to chrome dev console - I don't know why.. -
How to pass from detail view to form foreignkey field?
I have a detail view of car and btn of booking href to booking form . I want to pass that car which detail is showing. Rather than i always select from foreignkey dropdown car select. -
Storing the submitted image for image field in a folder and location in the database
I have a form that a user submits with an image for the models ImageFIeld. When they submit the model field. I want to take the image and download it to store it in a local directly. I also want to save the link in the field. How can I do that because the image name is coming up when i print the profile_pic. but the image is not showing up in the correct directly. Here is what i have so far. models: class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='images/profile_pics/', max_length=100) bio = models.TextField() dob = models.DateField(auto_now=False, auto_now_add=False) phone = models.IntegerField() gender = models.CharField(max_length=11) company = models.CharField(max_length=22) occupation = models.CharField(max_length=22) street = models.CharField(max_length=44) city = models.CharField(max_length=22) state = models.CharField(max_length=4) zip_code = models.IntegerField() group = models.CharField(max_length=22) premium = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) here is the views.py file: if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data first_name = cd['first_name'] last_name = cd['last_name'] profile_pic = cd['profile_pic'] print(profile_pic) bio = cd['bio'] dob = cd['dob'] company = cd['company'] occupation = cd['occupation'] gender = cd['gender'] phone = cd['phone'] street = cd['street'] city = cd['city'] state = cd['state'] zip_code = cd['zip_code'] group = "alpha_testing" update_user = User.objects.filter(username … -
Content Download for a GET request is taking a long time
This is my setup: i have django 1.8 in the backend, i use nginx for my webserver. I have a pretty basic API for GET, which queries the backend and returns a response. From backend logging, i can see that the backend returns the request in < 1 second, but on Chrome Developers tool, in the "Timing" section, i can see that "Content Download" is taking about 7+ seconds. If anyone has suggestions about why this happens or some solutions i can try, i deeply appreciate it. -
How to provide user constant notification about Celery's Task execution status?
I integrated my project with celery in this way, inside views.py after receving request from the user def upload(request): if "POST" == request.method: # save the file task_parse.delay() # continue and in tasks.py from __future__ import absolute_import from celery import shared_task from uploadapp.main import aunit @shared_task def task_parse(): aunit() return True In short, the shared task will run a function aunit() from a third python file located in uploadapp/ directory named main.py. Let's assume that aunit() is a resource heavy process which takes time (like file parsing). As I integrated that with celery, It works totally asynchronously now which is good to me. So, the task start -> Celery process -> It finishes then celery set status to Finish. I can view that using flower . But what I want to do is that I want to notify the user who is using my app also through django UI that Your Task is done processing as soon as Celery has finished processing at back-side and set status to SUCCESS. Now, I know this is possible if : 1.) I constantly request the STATUS and see wheather it returns SUCCESS or not. How do I do that via Celery. How can … -
MySQL and Python - "image not found" -- permanent fix?
Everytime I try to run a django app in terminal using a python manage.py runserver command I get the following error: Referenced from: /Users/myname/anaconda/lib/python2.7/site-packages/_mysql.so Reason: image not found. Did you install mysqlclient or MySQL-python? To fix it, I just paste export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/ into my terminal. How can I rearrange my files so that I don't have to paste this in every time? I am working on a Mac. -
Django rest framework posting expects dictionary
I am trying to post to my API with foreign key relationships. It's throwing me back an error saying it's expecting a dictionary as opposed to int for character and character_opponent. This is because the way my models are set up. They have foreign key relationships. The model in question looks like this: import uuid from django.db import models from django.utils import timezone from analysis.models import Analysis from characters.models import Character from stages.models import Stage class Match(models.Model): analysis = models.ForeignKey(Analysis, on_delete=models.CASCADE) character = models.ForeignKey(Character, on_delete=models.CASCADE, related_name='character') character_won = models.BooleanField() character_opponent = models.ForeignKey(Character, on_delete=models.CASCADE, related_name='character_opponent') character_opponent_won = models.BooleanField() created_at = models.DateTimeField(editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4) updated_at = models.DateTimeField(editable=False) stage = models.ForeignKey(Stage, on_delete=models.CASCADE) def __str__(self): return '%s vs. %s on %s' % (self.character, self.character_opponent, self.stage) def save(self, *args, **kwargs): ''' On save, update timestamps ''' if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Match, self).save(*args, **kwargs) class Meta: db_table = "matches" And here is my serializer: from rest_framework import serializers from matches.models import Match from characters.serializers import CharacterSerializer from stages.serializers import StageSerializer class MatchSerializer(serializers.ModelSerializer): character = CharacterSerializer() character_opponent = CharacterSerializer() stage = StageSerializer() class Meta: model = Match fields = ('id', 'analysis', 'character', 'character_won', 'character_opponent', 'character_opponent_won', 'stage') Is there some … -
how to validate a django formset of model forms when one of the objects has been deleted
I have a Django formset to record attendance at an event: AttendanceFormSet = modelformset_factory(Registration, form=AttendanceForm, extra=0) Created from this form: class AttendanceForm(forms.ModelForm): class Meta: model = Registration fields = ( "absent", "late", ) from this model: class Registration(models.Model): event = models.ForeignKey(Event) student = models.ForeignKey(User, on_delete=models.CASCADE) # ... absent = models.BooleanField(default=False) late = models.BooleanField(default=False) However, sometimes attendees will drop the event, after the attendance form has already been loaded. I want to be able to handle these situations gracefully. During my form validation, how can I tell if the Registration object no longer exists? I've tried validating the forms individually, but the validation error doesn't seem helpful: if request.method =="POST": formset1 = AttendanceFormSet( request.POST, request.FILES, queryset=queryset, ) for form in formset1.forms: if form.is_valid(): form.save() else: print("form errors: " + str(form.errors)) The resulting error when this happens looks like this: form errors: <ul class="errorlist"><li>id<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>