Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my txt file not exporting with newlines properly?
I know how to make and read from txt files in python, but it's not working properly when I do it as an HttpResponse in django. def abc(request): users = User.objects.all() filename = "my-file.txt" text_string = '' for user in users: text_string += '{} {}\n'.format(user.id, user.username) print(text_string) # prints properly in the terminal with a new line response = HttpResponse(text_string, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response This file downloads just fine, but the content looks like this when opened: 1 userA2 userB3 userC But I am expecting it to look like: 1 userA 2 userB 3 userC Another odd thing I noticed is when I copy / paste the contents in this text editor, it retains the new lines I'm expecting, but is not displaying it as I want in the file. -
Trying to prevent international users from accessing my Django site
I don't want to have a cookie policy, so for legal issues, I want to block international users from my site - basically redirect them to a "sorry not available to international users page" and prevent them from accessing the main site. How should do I prevent them from accessing the main site? There is no authentication system for the main site currently. This is mostly a design question. This is how I thought about doing it, but it would be hard. Is there an easier way? First, I pull their country from their IP (which I already have). Then, I force them into a first level login page, that they need a username and password to login. However, this is painful, since I already have a user authentication system for paying users. Is there a better way to do this? -
How to exclude querysets that already has m2m relationship
I'm creating a Model with a many2many relationship, if the other model has a parent it needs to be excluded from the form I know how to exclude if I know the pk but it has to be for any relationship, I read the django official documentation and can't solve it yet models.py: `class Invoice(models.Model): invoice_created = models.DateField(auto_now_add=True,verbose_name='Date_limit') class GlobalInvoice(models.Model): date_limit = models.DateField( auto_now_add=True, verbose_name='Date Limit' ) invoices = models.ManyToManyField( Invoice, verbose_name='Invoices' )` forms.py `class GlobalInvoiceForm(forms.ModelForm): def __init__(self, *args, **kwargs): invoices = Invoice.objects.filter( invoice_created__lte=date.today() ) # the exclude should be here super(GlobalInvoiceForm, self).__init__(*args,**kwargs) self.fields['invoices'] = forms.ModelMultipleChoiceField( label='Invoices:', widget=forms.CheckboxSelectMultiple, queryset=invoices ) class Meta: model = GlobalInvoice fields = '__all__' ` If I create a new Global Invoice the Invoice field needs to exclude the Invoices that already has a Global Invoice assigned -
Display radio button with dropdown user selection
I would like to create two fields: a radio button and dropdown radio button will populate given choice and dropdown will pull from the DB. Getting stuck with displaying the radio and fetching value Should I be using modelform or form? I would like to store data in DB when radio button selection is down with dropdown value and like to take that value to display a case types. MODEL.py class Selections(models.Model): roletype = models.CharField(max_length=8, default=None) LOCATIONS = (('DC1','DC1'), ('DC2', 'DC2'), ('DC3', 'DC3')) location = models.CharField(max_length=4, choices=LOCATIONS) def __str__(self): return self.roletype FORMs.py from django import forms from .models import Selections class SelectionsForm(forms.ModelForm): ROLES = (('1','Type1'),('2','Type2'),('3', 'Type3')) roletype = forms.ChoiceField(choices=ROLES, widget=forms.RadioSelect) class Meta: model = Selections fields = ['roletype','location'] VIEWs.py ## VIEW: Populate dropdown to select Data center def get_role_dc_data(request, *args, **kwargs): location = Midtier.objects.get(id=0) # List of objects roletype = Midtier.objects.get(id=1) # List of objects context = { 'location': location, 'roletype': roletype } return render(request, 'selections/view.html', context) view.html <th> {% for radio_input in context.roletype %} <input type="radio" name="choice" id="{{ radio_input.id }}" value="{{ radio_input.id }}"> {% endfor %} </th> <th> <div class="fieldWrapper" align="center" id="mainselection"> <select name="location"> <option selected="selected">Select an the site</option> {% for instance in context.location %} <option >{{ instance.location }}</option> … -
Python 3.6.4 - Having problems installing mysqlclient?
I am trying to install mysqlclient with the pip command but for some reason it just doesn't work. I am running this on a macOS. Python 3.6.4 Django 2.1.5 I have seen the question here Unable to install mysqlclient in python3 virtualenv but none of the answers are any useful. I am also aware of some of the issues affecting macOS as mentioned here https://pypi.org/project/mysqlclient/ but I don't think my error is to do with that. Here are the error logs ERROR: Command errored out with exit status 1: command: /Users/azky/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-wheel-a12yp4ks --python-tag cp36 cwd: /private/var/folders/nl/5frbk1n9067bt8hd8n96z3k00000gn/T/pip-install-tr2cx0p_/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.6-intel-3.6 copying _mysql_exceptions.py -> build/lib.macosx-10.6-intel-3.6 creating build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb creating build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.macosx-10.6-intel-3.6/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.macosx-10.6-intel-3.6 /usr/bin/clang -fno-strict-aliasing … -
When I have 100 columns, what should I do to retrieve the columns?
Hello I have a question for django orm ~! table model is this author | ca1 | ca2 | ca3 | ca4 | ca5 | ca6 | … | ca100 mike | rabbit | bird | shark| mouse | dog | cat | When I search using the search term tiger To get the next search result mike, ca5, dog What should I do with orm? thank you for let me know~! -
How could I change a Boolean field to show a value like Up = true or Down = False in a serialized field in Django
I have a serialized data set in Django Rest Framework to be consumed, but I have a question that I want to solve, there is a field that is Boolean, and clearly when I serialize it shows two values: true or false, the question is that I do not want show these values, I want to show UP = True, DOWN = False These fields in question are: status and ospf My Model class Interfaces(models.Model): id_interface = models.PositiveIntegerField(primary_key=True) id_EquipoOrigen = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_origen') id_PuertoOrigen = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_origen', null=True, blank=True) estatus = models.BooleanField(default=False) etiqueta_prtg = models.CharField(max_length=80, null=True, blank=True) grupo = models.PositiveSmallIntegerField(default=0, blank=True) if_index = models.PositiveIntegerField(default=0, blank=True) bw = models.PositiveSmallIntegerField(default=0, blank=True) bw_al = models.PositiveSmallIntegerField(default=0, blank=True) id_prtg = models.PositiveSmallIntegerField(default=0, blank=True) ospf = models.BooleanField(default=False) description = models.CharField(max_length=200, null=True, blank=True) id_EquipoDestino = models.ForeignKey(Equipos, on_delete=models.DO_NOTHING, related_name='equipo_destino') id_PuertoDestino = models.ForeignKey(Puertos, on_delete=models.DO_NOTHING, related_name='puerto_destino') ultima_actualizacion = models.DateTimeField(auto_now=True) My Serializers Model Interfaces class InterfaceSerializer(serializers.ModelSerializer): EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class InterfacesViewSet(viewsets.ModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer pagination_class = PostPageNumberPagination filter_class = InterfacesFilter -
How to Execute an Asynchronous Infinite loop on a Python Django server?
Consider the following code: import asyncio, aiohttp async def get_access_token(session, token): url = ... headers = ... data = ... async with session.post(url, headers=headers, data=data) as res: return await res.text() async def get_access_tokens(credentials): async with aiohttp.ClientSession() as session: tasks = [] for token in credentials: task = asyncio.create_task(get_access_token(session, token)) tasks.append(task) return await asyncio.gather(*tasks) async def main(): test = ... data = await get_access_tokens(test) print(data) if __name__ == '__main__': asyncio.run(main()) This code works as expected, but I need it to run in an infinite loop on a django server, so that it is executed every 2 hours (to update API access tokens) What is the pythonic way of running a script like this from a Django server? I can't seem to find anything on running code outside of a Django view. Any advice/links to related topics is appreciated. -
Chromedriver got ad error TypeError: environment can only contain strings
I'm using Selenium to open a Chrome Web Page with a user-agent, whitout Celery all is ok but when I call a def with Celery i got an error: app = Celery() @app.task(bind=True) def test(self, post_id): lui = Author.objects.get(pk=post_id) print lui.pk opts = Options() opts.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1') dri = r"C:\chromedriver.exe" driver =webdriver.Chrome(executable_path=r'C:\chromedriver.exe', chrome_options=opts) the error: Traceback (most recent call last): File "c:\python27\lib\site-packages\celery\app\trace.py", line 382, in trace_task R = retval = fun(*args, **kwargs) File "c:\python27\lib\site-packages\celery\app\trace.py", line 641, in __protected_call__ return self.run(*args, **kwargs) File "pathto\test.py", line 129, in test driver =webdriver.Chrome(executable_path=r'C:\chromedriver.exe', chrome_options=opts) File "c:\python27\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__ self.service.start() File "c:\python27\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start stdin=PIPE) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 658, in __init__ reraise(*exc_info) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 627, in __init__ restore_signals, start_new_session) File "c:\python27\lib\site-packages\gevent\subprocess.py", line 1028, in _execute_child startupinfo) TypeError: environment can only contain strings Any suggest? -
What does this Apache HTTP rewrite rule do?
I'm looking to next block invalid HTTP_HOST headers at a server level on my Elastic Beanstalk Django app. Spammers keep hitting my website with invalid host headers (like HOST_HEADER = bad.com) and I want to block them at a server level (as compared to at a Django level). I found the following Apache server configuration here. I'm trying to figure out what this last RewriteRule is doing files: "/etc/httpd/conf/http-redirect.conf": mode: "000644" owner: root group: root content: | RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTP_USER_AGENT} !ELB-HealthChecker RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} It appears that RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} is forcing you to go the url that you have set as your HTTP_HOST, preventing you from hosting the website good.com at another domain like bad.com, as it redirects you to bad.com if that's what you've set as the host. If you don't set this line, it looks like the default setting would be RewriteRule (.*) https://good.com%{REQUEST_URI}. Am I correct in my understanding of this RewriteRule, and would using this config be an appropriate method of deflecting constant stream of invalid hosts? Potentially helpful for future searchers, here is my current .config file, which redirects to HTTPS: files: "/etc/httpd/conf.d/ssl_rewrite.conf": mode: "000644" owner: root group: root content: … -
Serializing Django. How to set custom template
Good day! Trying to figure out how to generate xml in Django What do i have? Objects that appear on the site. The data of these objects must be generated in special fields in the xml file. I created views.py: def xml(request): listings = Listing.objects.all().filter(is_published=True) listings = serializers.serialize('xml', listings) context = { 'listings': listings } return HttpResponse(listings, content_type='application/xhtml+xml') As a result, I get: <django-objects version="1.0"> <object model="listings.Listing" pk="1"> <field name="price" type="IntegerField">100</field> </object> <object model="listings.Listing" pk="2"> <field name="price" type="IntegerField">100</field> </object> </django-objects> As I understand it, this is a standard template in Django Question! How to specify a custom template so that all markup is implemented by me, for example: <offer id="1"> <price>100</price> </offer> <offer id="2"> <price>100</price> </offer> Thank you in advance! -
Custom method for field
I used cookiecutter django to create a project and django builder for my first app to get up and running quickly. I'm using crispy forms and I want to replace the default checkbox with an image. I have a model with only boolean fields - I want to display images depending on the field is set true or false in the form. I got a function which maps the column name to a image path which I can use in the template but I have no idea how to do it without adding a function call to the template Ideally I would have a field.image method which I can insert in the src element, my function call looks like this image_src = image_path(field.label) And as I see the best access to the field.label is in this template. Thats my custom template I want to use {% load crispy_forms_field %} <li> {% crispy_field field 'class' 'custom-control-input' %} <label for="{{ field.id_for_label }}"><img src="{{ field.image }}" alt="{{ field.label }}"/></label> </li> This is my forms.py class ProtectiveEquipmentForm(forms.ModelForm): class Meta: model = ProtectiveEquipment def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.layout = Layout( Fieldset( 'first arg is the legend of the fieldset', Field('head_protection', 'eye_protection', 'template="graphical_checkbox.html"), … -
How to make a Django UpdateView only work the first time?
Suppose I two objects with a many-to-one relationship, like a Car and a Manufacturer, and would like to capture the first_car_name of the Manufacturer, that is, the first car that the manufacturer created. I have the following two models: from django.db import models from django.urls import reverse class Manufacturer(models.Model): name = models.CharField(max_length=255) first_car_name = models.CharField(max_length=255, blank=True) def get_absolute_url(self): return reverse('manufacturer-detail', kwargs={'pk': self.id}) class Car(models.Model): manufacturer = models.ForeignKey( 'Manufacturer', on_delete=models.CASCADE) name = models.CharField(max_length=255) the following views.py: from django.http import HttpResponseRedirect from django.views.generic import UpdateView from django.views.generic.detail import DetailView from myapp.models import Manufacturer, Car class ManufacturerDetailView(DetailView): model = Manufacturer class AddCarView(UpdateView): model = Manufacturer fields = ['first_car_name'] def form_valid(self, form): Car.objects.get_or_create( name=form.cleaned_data['first_car_name'], manufacturer=self.object) self.object.refresh_from_db() if self.object.car_set.count() == 1: return super().form_valid(form) return HttpResponseRedirect(self.get_success_url()) the following urls.py, from django.contrib import admin from django.urls import path from myapp import views urlpatterns = [ path('admin/', admin.site.urls), path('manufacturer/<int:pk>/', views.ManufacturerDetailView.as_view(), name='manufacturer-detail'), path('manufacturer/<int:pk>/add-car/', views.AddCarView.as_view(), name='add-car') ] and the following unit test in tests.py: from django.test import TestCase from django.urls import reverse from myapp.models import Manufacturer, Car class ManufacturerViewTests(TestCase): def test_add_car(self): manufacturer = Manufacturer.objects.create(name='Ford') self.client.post( reverse('add-car', kwargs={'pk': manufacturer.id}), data={'first_car_name': 'Model T'}) self.assertEqual(Car.objects.count(), 1) self.assertEqual(Car.objects.first().name, 'Model T') self.assertEqual(Car.objects.first().manufacturer, manufacturer) manufacturer.refresh_from_db() self.assertEqual(manufacturer.first_car_name, 'Model T') self.client.post( reverse('add-car', kwargs={'pk': manufacturer.id}), data={'first_car_name': 'Focus'}) manufacturer.refresh_from_db() self.assertEqual(manufacturer.first_car_name, … -
Django keeps throwing a UNIQUE constraint failed error every time I try to save a new foreign key instance
I have a foreignkey connected to a django model. I would like there to be numerous instances to the django model through foreign keys. My first foreign key saved to the model is saved successfully but every other foreignkey that is saved after that incident keeps throwing back this error: UNIQUE constraint failed: moderator_product.product_id. I can't seem to figure out where I'm going wrong. class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) slug = models.SlugField(max_length=100, unique=True, default='') open = models.IntegerField() close = models.IntegerField() def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Detail, self).save(*args,**kwargs) class Store_image(models.Model): image = models.OneToOneField(Detail, on_delete=models.CASCADE, primary_key=True,) image = models.FileField(blank=True) class Product(models.Model): product = models.ForeignKey(Detail, on_delete=models.CASCADE,unique = False,) name = models.CharField(max_length=100, blank = True) price = models.IntegerField() description = models.CharField(max_length = 500, blank= True,) product_image = models.FileField(blank=True) def addproduct(request,slug,pk): Detail = Detail.objects.get(pk=pk) if request.method == "POST": name = request.POST.get("name") price = request.POST.get("price") description = request.POST.get("description") image = request.FILES['image'] Detail.product_set.create(name=name,price=price, description=description, product_image=image,) return render(request,"moderator/addproduct.html") -
How can i add spans after input tags in django without rendering forms manually?
I want to add span tags after input tags in forms to show icons or so. the idea is in Django the forms is just rendered automatically by calling the form's context name in a template tag so is there any way I can add tags to each or only one tag without rendering the whole form manually? can I add anything in the forms.py file to make these changes? -
Problem: Any logged-in user can access Django Admin panel
I have my account with is_superuser = 1 and other users with is_superuser = 0 and is_staff = 0. But Django does not restrict access to "not-staff" users. So, any logged-in user can access admin panel. From Django documentation: By default, logging in to the admin requires that the user has the is_superuser or is_staff attribute set to True. But this does not work. I do not have any changes in admin settings. Except custom admin panel URL: from django.contrib import admin urlpatterns = [ path('my-admin/', admin.site.urls), ] So where can be the problem with not working Django restrictions? Django==2.2.4 Database: MySQL -
Why JSON.stringify() return undefined and produce auth.js:65 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined?
I'm trying to login in my django application using axois and react-redux. My problem is when I entered wrong login information then the LOGIN_FAIL action is work fine but when entered correct login information the LOGIN_SUCCESS action is not work and produce the following error "Uncaught (in promise) TypeError: Cannot read property 'data' of undefined". I have debugged my code and this line "const body = JSON.stringify({ username, password });" is return undefined even username and password data is successfully received. Is the problem heppend this reason? I am confused!! Can anyone solve my problem? Thanks in advance. Here is my action code: import axios from "axios"; import { errorMessage } from "./messages"; import { USER_LOADING, USER_LOADED, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL } from "./types"; // Login User export const login = (username, password) => dispatch => { // Headers const config = { headers: { "content-type": "application/json" } } // Request body const body = JSON.stringify({ username, password }); axios.post("/api/auth/login", body, config) .then(res => { dispatch({ action: LOGIN_SUCCESS, payload: res.data }); }).catch(err => { dispatch(errorMessage(err.response.data, err.response.status)); dispatch({ type: LOGIN_FAIL }); }); } -
Failed to start uWSGI Emperor
following the best tutorials on the internet, still not able to make emperor.uwsgi.service working. my configuration files as follows: /etc/uwsgi/emperor.ini emperor = /etc/uwsgi/vassals uid = user1 gid = www-data limit-as = 1024 logto = /var/log/uwsgi.log /etc/uwsgi/sites/project.ini [uwsgi] project = project base = /home/user1/project uid = user1 gid = www-data plugins = python3 chdir = %(base) home = %(base)/venv #module = project.wsgi:application wsgi-file = /home/user1/project/project/wsgi.py workers = 4 master = true processes = 10 socket = /home/user1/%(project)/%(project).sock chown-socket = %(uid):www-data chmod-socket = 664 vacuum = true buffer-size = 65535 /etc/uwsgi/vassals/(ln -s) /etc/systemd/system/emperor.uwsgi.service [Unit] Description=uWSGI Emperor After=syslog.target [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown user1:www-data /run/uwsgi' ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini # Requires systemd version 211 or newer RuntimeDirectory=uwsgi Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target all files under the same uid, gid user1:www-data I tried a lot of things and I found some other directories for uwsgi, I changed the user in #/etc/init.d/uwsgi, and I found the emperor file in the same location, I don't know what else I should modify. the error messages I get when I run systemctl status emperor.uwsgi.service Process: 788 ExecStart=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini (code=exited, status=1/FAILURE) Aug 04 18:03:26 mymachine systemd[1]: emperor.uwsgi.service: Service RestartSec=100ms expired, scheduling restart. Aug 04 18:03:26 … -
mysql query to django ORM
I am trying to make a query with django ORM but I could not. The models are: class Prestamo(models.Model): PENDIENTE = 1 PAGADO = 2 FUSIONADO = 3 ANULADO = 4 ESTADOS = ( (PENDIENTE, 'pendiente'), (PAGADO, 'pagado'), (FUSIONADO, 'fusionado'), (ANULADO, 'anulado') ) cliente = models.ForeignKey(Cliente, on_delete = models.CASCADE) fecha_prestamo = models.DateField(default=timezone.now) capital_prestado = models.FloatField() porcentaje_aplicado = models.ForeignKey(Interes, on_delete=models.CASCADE) valor_interes = models.FloatField(null=True) fecha_registro = models.DateTimeField(default=timezone.now) prestamo_nuevo = models.ForeignKey('Prestamo', on_delete=models.CASCADE, blank= True, null=True) estado = models.IntegerField(choices=ESTADOS, default=PENDIENTE, blank= True) class Abono(models.Model): prestamo = models.ForeignKey(Prestamo,on_delete=models.CASCADE) fecha_abono = models.DateField(default=timezone.now) valor_abono_capital = models.FloatField() valor_abono_interes = models.FloatField() class Descuento(models.Model): prestamo = models.ForeignKey(Prestamo,default=None,on_delete=models.CASCADE) fecha_descuento = models.DateField(default=timezone.now) valor_descuento = models.FloatField() I have the following query in MySQL which is the one I need but in django ORM, In this I am making a query to the three tables of loan, credit and discount. left join is required because a loan may not have payments yet made and no discounts select p.id,fecha_prestamo,p.capital_prestado,CONCAT(clientes_cliente.nombres,' ', clientes_cliente.apellidos) 'Cliente', IFNULL(sum(prestamos_abono.valor_abono_capital), 0) abonos, (select IFNULL(sum(prestamos_descuento.valor_descuento) , 0) from prestamos_descuento where prestamos_descuento.prestamo_id = p.id) 'descuentos', (p.capital_prestado - IFNULL(sum(prestamos_abono.valor_abono_capital), 0) - (select IFNULL(sum(prestamos_descuento.valor_descuento) , 0) from prestamos_descuento where prestamos_descuento.prestamo_id = p.id) ) 'saldo capital' from prestamos_prestamo as p left join prestamos_abono ON prestamos_abono.prestamo_id = p.id … -
How to add field in admin/app/add panel which wont be included in model in Django?
I have to add extra field in Django admin/app/add panel which wont be included in my model, but I want to use the value in Model.save() method. It must be like: on "add" panel I can enter minutes and seconds, but in model.save() I save only mins*60+seconds. -
DoesNotExist at /admin/login/ Site matching query does not exist in wagtail
I can't do anything in my admin panel because when i go to locahost:8000/admin it shows those errors: DoesNotExist at /admin/login/ Site matching query does not exist. Full traceback: Environment: Request Method: GET Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['home', 'search', 'blog', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social_django', 'django.contrib.sites', 'django_comments_xtd', 'django_comments'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware'] I also tried this question but it also throws errors: Traceback: File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/contrib/sites/models.py" in _get_site_by_request 39. SITE_CACHE[host] = self.get(domain__iexact=host) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/db/models/query.py" in get 408. self.model._meta.object_name During handling of the above exception (Site matching query does not exist.), another exception occurred: File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py" in wrapper 102. return view_func(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/fullnamedebian/.local/lib/python3.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return … -
How do I fix this fake scripting in django? It doesn't work for me
I'm using the Faker for fake populating my database, but it doesn't work. It says my models doesn't have "objects" member and the Faker itself doesn't work. I tried to run this file with python, I get errors. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() ## FAKE POP SCRIPT import random from first_app.models import Topic, Webpage, AccessRecord from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range(N): # Add topic for the entry top = add_topic # Create fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date)[0] if __name__ == "__main__": print("Populating Script!") populate(20) print("Populating Complete!") I expect the output of the "Populating the databases...Please Wait" and the fake populating my database and then after it's finished, "Populating Complete" should be printed. -
Send 2 args to Celery eta task
I use eta to program a task: test.apply_async(eta=datetime(2019, 8, 4, 17, 01)) but I have a task on test.py that take an arg from view, for example 'post': app = Celery() @app.task(bind=True) def test(post, self): #somecode I need to pass 'eta' and 'post', I try with: test.apply_async(post, eta=datetime(2019, 8, 4, 17, 01)) but give an error: functools.partial object argument after * must be an iterable, not Author what's wrong? -
Ceate a ImageField from an existing URL
I'm creating ImageField on one machine (uploading an image to aws) and I want to create the same ImageField on another machine with this already existing url. How can I do that? -
deserializing a model with a custom field
I have a model in django with a 3rd party CustomField. dumpdata works fine serializing the field to json, but loaddata is unsuccessful in deserializing this specific field (due to a bug in the code of the CustomField). How can I write a deserializer to overwrite the original deserializer of the field in a way that django can use it in loaddata command. class MyModel(models.Model): id = models.IntergerField() custom = CustomField()