Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create comment, like, tag, report, and so on for a post model in django?
I created a model which name is Post and placed in this path : MyProject/Postapp/models look like this: class Post(models.Model): user = models.ForeignKey(User, related_name="posts", on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] So in the following I want to add comment, ... to each Post which created by Users. Should I start a new app (Commentapp, ...) or create models in current path and add some fields in the Post model? -
Cannot upload file via django form running apache/linux
I could use some help deciphering the following traceback and resolving specifically on a linux machine running apache and django with DEBUG = False Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 189, in __call__ response = self.get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 218, in get_response response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 256, in handle_uncaught_exception 'request': request File "/usr/lib/python2.7/logging/__init__.py", line 1200, in error self._log(ERROR, msg, args, **kwargs) File "/usr/lib/python2.7/logging/__init__.py", line 1293, in _log self.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 1303, in handle self.callHandlers(record) File "/usr/lib/python2.7/logging/__init__.py", line 1343, in callHandlers hdlr.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 766, in handle self.emit(record) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 129, in emit self.send_mail(subject, message, fail_silently=True, html_message=html_message) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 132, in send_mail mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/mail/__init__.py", line 98, in mail_admins mail.send(fail_silently=fail_silently) ... error: [Errno 111] Connection refused It is unclear to me why send_mail(..., fail_silently=True, ...) should fail if fail_silently=True How do I debug this error if it only manifests when DEBUG = False? -
How to use django with python pip
I have a tutorial which say: Installation pip install django-peeringdb Then add django_peeringdb to INSTALLED_APPS My question is! if I install django-peeringdb from pip where can i find manage.py to change settings!!! -
How to do proper reverse querying when using Django generic relations?
I have implemented Django generic relations to create relations between models. My models are class CessPoint(BaseModel): .... title = models.CharField(max_length=100) class BilledVehicle(BaseModel): .... source = models.ForeignKey(CessPoint, on_delete=models.CASCADE) class Bill(BaseModel): ..... content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, null=True) object_id = models.UUIDField(null=True) billed_item = GenericForeignKey() class BillPayment(BaseModel): ..... bill = models.ForeignKey(Bill, on_delete=models.CASCADE) I would like to get the payments for BilledVehicle. This is how I would like to go about it. BillPayment.objects.filter(bill__content_type=ContentType.objects.get_for_model(BilledVehicle)).values('bill__billed_item__source__title').annotate(total_paid=Sum('amount_paid')).order_by('-total_paid') I am getting the error: Field 'billed_item' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. -
how to generate the pdf file using xhtml2pdf that have the persian data in template
I have a problem in generating the pdf using Django. in my template, I have Persian data like this احمدو محمودbut when the pdf file show the Persian data was hashed like this. this is my view def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() print(html) pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result ) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None this is the funcation called template def mypdf(request): pdf = render_to_pdf('viewpdf.html') return HttpResponse(pdf, content_type='application/pdf') This is my template enter code here Title body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; /* text-align: right;*/ padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px 0px 20px; text-align: left !important; /margin-left: 40%;/ } .hrItem { border: none; height: 1px; /* Set the hr color / color: #333; / old IE / background-color: #fff; / Modern Browsers */ } Invoice # احمدومحمود at the end this is the output: enter image description here -
django, how to get object from get_or_create and use it to other get_or_create?
CODE example: keyword = Keyword.objects.get_or_create(text=text) sub_keyword = SubKeyword.objects.get_or_create(keyword=keyword, user=request.user) It returns: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Keyword' from line: sub_keyword = SubKeyword.objects.get_or_create(keyword=keyword, user=request.user) How to do it? -
How to write single class based view for multiple url?
I have urls reporting?id=1 and reporting?students=bachelor. For both these urls I am using same base url 'reporting' in urls.py. urls.py from .views import Reporting urlpatterns = [ path('', AnalyticsData.as_view()), path('reporting', Reporting.as_view()), path('index', index.as_view()) ] How could I use the same class view to execute different get methods so that for the first URL, a method to get students by id is executed and for the second URL, a method to get bachelor students is executed. For now, I am writing code in the following way views.py class Reporting(APIView): def get(self, request): id = self.request.GET.get("id") student_type = self.request.GET.get("students") if id: *logic* if student_type=="bachelor": *logic* But I don't know if this is the right way. Also, if there are multiple parameters than there will be many if conditions. Is there any other way available? -
Reverse for 'filer_folder_changelist' not found
I am deploying site to divio server with django and django-cms. I do R&D but not found much information about this. Facing Error: Reverse for 'filer_folder_changelist' not found. 'filer_folder_changelist' is not a valid view function or pattern name. Exception Type: NoReverseMatch Exception Value: Reverse for 'filer_folder_changelist' not found. 'filer_folder_changelist' is not a valid view function or pattern name. Exception Location: /virtualenv/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497 Python Executable: /virtualenv/bin/uwsgi {% cms_toolbar %} -
Django: Creating a new table for each existing row in a different table
I want to create a database in django in which I want to create a table and in that table if I add a new row a new table should create associated with that row and then I could add data to that new table according to my choice. -
pycharm django super().get_context_data(**kwargs) has errors
This is my code I'm trying to: class PublisherDetail(SingleObjectMixin, ListView): paginate_by = 2 template_name = "books/publisher_detail.html" def get(self, request, *args, **kwargs): self.object = self.get_object(queryset=Publisher.objects.all()) return super().get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['publisher'] = self.object return context def get_queryset(self): return self.object.book_set.all() in this line: context = super().get_context_data(**kwargs) Pycharm says: python version 2.7 does not support this syntax. P.S: 1) Setting > Editor > Inspection > Code compatibility is disabled 2) My interpreter is python 3.6.3 and the second error is about (in the same line): Unresolved attribute reference 'get_context_data' for class 'super' P.S: I have marked source root in Pycharm. How can I get rid of these errors? (both are errors, not warnings) Pycharm version: PyCharm 2018.2.3 (Professional Edition) Build #PY-182.4323.49, built on September 4, 2018 Windows 10 10.0 -
How to control progress of view in Django?
Here is my problem: I've view which processing very long, I want to control progress of this view. I know two variants: 1)Using Celery 2)Writing neccesary value in txtfile or in database and then reading it from other view. Maybe anyone knows the best solution for this?(not Celery) -
ubuntu14 pache2.4 Django1.1.15 python2.7.13 not connect
enter image description here my /etc/apache2/sites-available/000-default.conf CONF file I modified it to meet my requirements. I want the first screen of the warehouse project to be printed out. but enter image description here The website had to be output and the file explorer was output. What problems should I fix? If you need more information, I'll leave it as a reply. -
Effecient Bulk Update of Model Records in Django
I'm building a Django app that will periodically take information from an external source, and use it to update model objects. What I want to to be able to do is create a QuerySet which has all the objects which might match the final list. Then check which model objects need to be created, updated, and deleted. And then (ideally) perform the update in the fewest number of transactions. And without performing any unnecessary DB operations. Using create_or_update gets me most of the way to what I want to do. jobs = get_current_jobs(host, user) for host, user, name, defaults in jobs: obj, _ = Job.upate_or_create(host=host, user=user, name=name, defaults=defaults) The problem with this approach is that it doesn't delete anything that no longer exists. I could just delete everything up front, or do something dumb like to_delete = set(Job.objects.filter(host=host, user=user)) - set(current) (Which is an option) but I feel like there must already be an elegant solution that doesn't require either deleting everything, or reading everything into memory. -
How to display Datatable in django using stored procedures
i am using django-datatables-view for displaying data in the Datatable. When i try to use this plugin with tables i got output as i needed.I have a procedure in MySQL. How can i use procedures in data tables in django. -
Django timezone ET instead of EST/EDT
what timezone value should I use to show "ET" instead of "EST" or "EDT"?Also I am using pytz for my functions. Thanks. Currently this shows "EDT": TIME_ZONE = 'US/Eastern' While this shows "EST": TIME_ZONE = 'America/Cancun' -
updating UserProfile (OneToOne model to Django User model)
I am new to Django and creating a Django project with an account system. I extended the User model with a one-to-one UserProfile model. However, I am having problems saving the data in the UserProfile model (saving to User model is having no problem). I tried to follow this guide to fix it but ran into AttributeError at /account/login/ 'User' object has no attribute 'UserProfile' errors which is saying there are errors with instance.UserProfile.save() under models.py How do I get the UserProfile form to save and fix this no attribute error? models.py from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save import datetime from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, blank=True, null=True, unique=True, related_name='userprofile' ) bio = models.CharField(max_length=200, default='', blank=True) campus = models.CharField(max_length=100, default='', blank=True) website = models.URLField(default='', blank=True) phone = models.IntegerField(default=0, blank=True) image = models.ImageField(upload_to='profile_image', blank=True) birthday = models.DateField(blank=True, default=datetime.date.today) gender = models.CharField(default='', blank=True, max_length=20) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.UserProfile.save() forms.py # Edit User form class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name', 'password', ) # Edit … -
Django Login using user class redirecting to the same page
I am new to Django and I am developing a website that has some functions like Login and Register. I have already tried the register function (registrarUsuario) and I think it is working properly but when I try to Log In using the account created it redirects me to the same page and the user does not Log In (I checked this with request.user.is_authenticated). I have researched a lot and I haven't found a solution yet. Note: the login used to work with predefined users that I created with django (just username and password)... but I am using my own model WITH THE User Class I will post the register User code just in case the problem is there. VIEWS def registroUsuarios(request): #REGISTER USER FUNCTION form=RegistrarUsuario(request.POST) if form.is_valid(): data=form.cleaned_data regDB=User.objects.create_user(data.get("username"),data.get("password")) usuario=Usuario(user=regDB,correo=data.get("correo"),nombreCompleto=data.get("nombreCompleto"),direccionUsuario=data.get("direccionUsuario"),perfil=data.get("perfil")) regDB.save() usuario.save() usuarios=Usuario.objects.all() form=RegistrarUsuario() titulo="Mis Perris | Registro Usuarios" return render(request,"registroUsuarios.html",{'titulo':titulo,'form':form,'usuarios':usuarios}) def ingresar(request): #LOG IN FUNCTION titulo="Mis Perris | Login" form=Login(request.POST or None) if form.is_valid(): data=form.cleaned_data user=authenticate(username=data.get("username"),password=data.get("password")) if user is not None: login(request,user) return redirect('inicio') return render(request,"login.html",{'form':form,'titulo':titulo}) MODELS class Usuario(models.Model): #USER CLASS user=models.OneToOneField(User,on_delete=models.CASCADE) #username=models.CharField(primary_key=True, max_length=20) #password=models.CharField(max_length=20) correo=models.EmailField(max_length=30) nombreCompleto=models.CharField(max_length=30) direccionUsuario=models.CharField(max_length=30) perfil=models.CharField(max_length=20,default="Guest") FORMS perfiles=( ('Administrador','Administrador'), ('Guest','Guest'), ('Usuario','Usuario'), ) class RegistrarUsuario(forms.Form): #REGISTER USER username=forms.CharField(widget=forms.TextInput(),label="Nombre de Usuario") password=forms.CharField(widget=forms.PasswordInput(),label="Contraseña") correo=forms.EmailField(widget=forms.EmailInput(),label="Correo") nombreCompleto=forms.CharField(widget=forms.TextInput(),label="Nombre Completo") direccionUsuario=forms.CharField(widget=forms.TextInput(),label="Dirección") perfil=forms.ChoiceField(choices=perfiles) … -
django - testing inline formset with many-to-many key
I'm doing a formset validation testing (clean method), so I need to make my own formset and test it with formset.is_valid() method. I have a model that looks like this: class MataPelatihan(models.Model): nama_mata_pelatihan = models.CharField(max_length = 150, help_text = 'Misal: Interpersonal Relationship') waktu_mulai_raw = models.DateTimeField(verbose_name = 'Waktu Mulai') waktu_selesai_raw = models.DateTimeField(verbose_name = 'Waktu Selesai') pengajar_mata_pelatihan = models.ManyToManyField(User, verbose_name = 'Pengajar', related_name = 'mata_pelatihan_pengajar', blank = True) Also a User object instance like so: self.wi1 = User.objects.create_user(username = 'wi01', email = 'user01@gmail.com') self.wi1.save() In unit testing, I already have inline_formset_factory to build the formset like so: self.MPInlineFormset = inlineformset_factory(Kegiatan, MataPelatihan, form = MataPelatihanForm, formset = MataPelatihanInlineFormset, fields = ['nama_mata_pelatihan', 'waktu_mulai_raw', 'waktu_selesai_raw', 'pengajar_mata_pelatihan', ], ) and then I will make a formset with the test case data like so: formset = self.MPInlineFormset(data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-nama_mata_pelatihan': 'Pelatihan 1', 'form-0-waktu_mulai_raw': datetime.datetime(2018, 11, 1, 8, 0, 0, tzinfo = pytz.timezone('Asia/Jakarta')), 'form-0-waktu_selesai_raw': datetime.datetime(2018, 11, 1, 9, 0, 0, tzinfo = pytz.timezone('Asia/Jakarta')), 'form-0-pengajar_mata_pelatihan': self.wi1, }, prefix = 'form') Then I would call self.assertFalse(formset.is_valid()) But even before I can call formset.is_valid(), I got an error that says TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use pengajar_mata_pelatihan.set() … -
Not able to install packages or upgrade pip with Heroku
I'm using GitHub and Heroku to run my Django app. The app works as expected locally but I'm running into problems when pushing (via GitHub) it up to Heroku. I think I boiled it down to something not working with requirements.txt or the general pip set up. Specifically, I've been trying to install Django-Bootstrap4. It is in the requirements file. I definitely don't understand this process and I very well might not even be asking the right questions. But I've tried following all of the documentation found here: https://devcenter.heroku.com/articles/python-pip. When I'm in the virtual environment locally, everything looks fine. Then after doing: > heroku login > heroku run pip install django-bootstrap4 (or pip or pandas) It seems to install, but then running: > heroku run pip list nothing has changed. TIA -
Use amp-mustache variable in Django Template
So I want to change the timezone in Django, and use a variable inside an amp-mustache template. Something like this: {% timezone "{% templatetag openvariable %} timezone_name {% templatetag closevariable %}" %} or like this: {% timezone "{% verbatim %}{{timezone_name}}{% endverbatim %}" %} I need to use the templatetag or verbatim because amp-mustache syntax is in conflict with the Django syntax. I need to use the timezone of the amp-mustache template to avoid the local timezone that Django gets when the page is cached by Google -
Display a confirmation message after a password change
After a user succesfull password change I keep the user on the same page named password_change. url.py: path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('password_change')), name='password_change'), I tried using the messages framework with: views.py: def password_change(request): password_form = PasswordChangeForm(instance = request.user, data = request.POST) if request.method == 'POST': if password_form.is_valid(): password_form.save() update_session_auth_hash(request, password_form.user) # <-- keep the user loged after password change messages.success(request, 'Your password has been updated', extra_tags='safe') return render(request, 'registration/password_change_form.html', {'password_form': password_form}) with this in my html : {% if messages %} {% for message in messages %} <p class='{{ message.tags }}'>{{ message }}</p> {% endfor %} {% endif %} And I tried: views.py: def password_change(request): success = False; password_form = PasswordChangeForm(instance = request.user, data = request.POST) if request.method == 'POST': if password_form.is_valid(): password_form.save() update_session_auth_hash(request, password_form.user) # <-- keep the user loged after password change success = True; return render(request, 'registration/password_change_form.html', {'password_form': password_form, 'success': success}) with that in my html : {% if success %} <div>Password changed !!!</div> {% endif %} The password is changed but I can't display a message to celebrate this wonderful success. -
Django specify default serializer for model?
Note: this question is about django.core.serialize, not django-field-history Right now, I am using a neat little plugin called "django-field-history". I specify what fields I want to track and this plugin creates a log whenever one of those field changes. Things gets a little complicated for me because the model I want track is an inherited model: from polymorphic.models import PolymorphicModel from accounts.models import Account class Website(PolymorphicModel): account = models.OneToOneField( Account, blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('Account')) # Track account field with django-field-history field_history = FieldHistoryTracker([ 'account', ]) class WordpressWebsite(Website): wp_external_id = models.CharField( max_length=L, unique=True, validators=[validate_external_id]) So how django-field-history works is that it basically calls django.core.serialize to serialize the existing object that it's tracking and stores that serialized data into the database. The serialization takes place here. Now this becomes an issue because I am seeing null when a website's account is changed: I did a bit of research and found out that "fields" is empty because the model is the subclass and not the root class. Question: How can I specify a default serialization method for WordpressWebsite such that calling serialize.serialize('json', wordpress_website, field_names=['account']) will return something like this [{"model": "websites.website", "pk": 242, "fields": {"account": 349}}] ? -
mirror multidatabase setup in Django 2.1 testing
Here is the situation: We are creating a new, small REST API in Django 2.1. It needs read-only access to four tables, two on each of two mysql databases. For concreteness, let's say the two dbs are called A and B and the tables one, two, three and four. So, A.one, B.two, C.three and C.four. I am already using the solution from Django Testing - I only want one of my databases created - how to specify to prevent the tests from talking to the real databases. What I want to do is setup the four tables in the test database (models.py is already set up for this with managed = false) with test data that mirrors the above database and table structure, but inside the test sqlite database. This is so that, for example, a query to B.three gets routed correctly to test_B.three and not A.three or some top level table. One of the reasons for this is that our databases are very large and some of the tables contain two or three million rows. We do not want tests accessing them or copying data off of them. Further, since the app is does not own the database schemas, … -
Retrieve a QuerySet with GROUP BY with full related model instances instead of dict
I have 3 (simplified for this quenstion) models: TaxRate(models.Model): rate = models.DecimalField() name = models.CharField() @property def friendly_name(self): return some_string InvoiceLine(models.Model): invoice = models.ForeignKey('Invoice', related_name="lines") netto = models.DecimalField() rate = models.ForeignKey('TaxRate') Invoice(models.Model): no = models.CharField() I'm trying to get lines of Invoice grouped by taxrate__rate. I do invoice.lines.order_by('-taxrate__rate').values('taxrate__rate')\ .annotate( sum_netto=models.Sum('netto') ) and I get list of dicts with like this [{'taxrate__rate': Decimal(7.00), 'sum_netto': Decimal(12.00)}]' which is kind of ok, but I would like to get the same result with object of TaxRate where I can use method friendly_name. Is there a way to do this using only one simple ( like this ) query ? I know I cannot use .only() .defer() because then it's not grouped by taxrate__rate, because id field is obligatory there. I also don't want to do this in on the python side ( like for-loop over distinct taxrates and then aggregate sum_netto or just create list of dicts in python from queryset ) -
How to prevent token updates after login using allauth
When a user signs up my app, a token is saved in a db. In my app user can add some other API scopes like AdWords etc. (every user can have different scopes.) Then the token is updated with the right scope. When the user quits app and logs in again the token is updated again. But it uses just basic scopes for login so the token is invalid for AdWords. I whould need to prevent updating token when login. Any thoughts on how to sort this flow? (I use django-allauth)