Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing JSON to file causing Unicode Error on Ubuntu Server 16.04LTS
I am sure that the problem I am experiencing isn't directly related to the OS or version, but instead to some kind of setup. In a python django app I am writing JSON to a file which can contain characters from other languages like 我, ל, and は. At no point in time in the flow of data am I changing the encoding as far as I am aware. During local development, this was not a problem. with open(self._json_path, 'w') as f: json.dump(test_dict, f, indent=2, ensure_ascii=False) answer, wordid, question = self._unpack_dict(test_dict) Once I deployed to the live web server, I began getting: 'ascii' codec can't encode character '\u90fd' in position 1: ordinal not in range(128) I know for a fact that the data in test_dict is encoded properly. As soon as the json.dump occurs, it errors. If I open the file that was created, it fails at the very first non-latin character I put into it. I've been through this post, but couldn't sort out the problem. I've also tried rebuilding the virtual environment. On the server here are some results: echo $LANG en_US.UTF-8 python -c "import sys; print(sys.stdout.encoding)" UTF-8 Local environment: echo $LANG en_US.UTF-8 python -c "import sys; print(sys.stdout.encoding)" … -
Django multiply a model field by a constant in bulk
I have a Django model with an integer field that I need to multiply by a constant value C. Is there an efficient way to perform the query in bulk? (the number of instances to be updated is huge) e.g. MyModel.objects.filter(...).update(my_int_field=my_int_field * C) -
Celery receives periodic tasks but doesn't execute them
I use celery to run periodic tasks in my Django DRF app. Unfortunately, registered tasks are not executed. Project structure: project_name ___ cron_tasks ______ __init__.py ______ celery.py celery.py: app = Celery('cron_tasks', include=['cron_tasks.celery']) app.conf.broker_url = settings.RABBITMQ_URL app.autodiscover_tasks() app.conf.redbeat_redis_url = settings.REDBEAT_REDIS_URL app.conf.broker_pool_limit = 1 app.conf.broker_heartbeat = None app.conf.broker_connection_timeout = 30 app.conf.worker_prefetch_multiplier = 1 app.conf.beat_schedule = { 'first_warning_overdue': { 'task': 'cron_tasks.celery.test_task', 'schedule': 60.0, # seconds 'options': {'queue': 'default', 'expires': 43100.0} } } @shared_task def test_task(): app.send_task('cron_tasks.celery.test_action') def test_action(): print('action!') # print is not executed # I also tried to change the data, but it never happens too. from django.contrib.auth import get_user_model u = get_user_model().objects.get(id=1) u.first_name = "testttt" u.save() setting.py: RABBITMQ_URL = os.environ.get('RABBITMQ_URL') REDBEAT_REDIS_URL = os.environ.get('REDBEAT_REDIS_URL') CELERY_BROKER_URL = os.environ.get('RABBITMQ_URL') CELERYD_TASK_SOFT_TIME_LIMIT = 60 CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = os.environ.get('REDBEAT_REDIS_URL') CELERY_IMPORTS = ("cron_tasks.celery", ) from kombu import Queue CELERY_DEFAULT_QUEUE = 'default' CELERY_QUEUES = ( Queue('default'), ) CELERY_CREATE_MISSING_QUEUES = True redbeat_redis_url = REDBEAT_REDIS_URL Rabbitmq is running properly. I can see it's there in the celery worker terminal output: - ** ---------- .> transport: amqp://admin:**@localhost:5672/my_vhost Redis is pinging well. I use redis to send beats. I run: celery beat -S redbeat.RedBeatScheduler -A cron_tasks.celery:app --loglevel=debug It shows: [2019-02-15 09:32:44,477: DEBUG/MainProcess] beat: Waking up … -
My datetime field in models.py does not work even though it does not raise any exceptions while migrating
In my models.py I have a field created = models.DateField(auto_now_add=True) which does not raise any problems while migrating and such, however when I save a post, it gives me ValueError at /admin/blog/post/ invalid literal for int() with base 10: b'14 21:27:46.098090' I have went through documention, and I tried doing input_format but I couldn't get it to work I just want to be able to not have just the date saved, without the time. Or perhaps I just format it in the template to show day,month,year. But how do I do that? -
'UpdateQuery' object has no attribute 'get_field' error
Is there something wrong with my code below? The intent is that when the user updates a venue the all events that are linked to the venue are marked as modified. The error that I'm getting is "'UpdateQuery' object has no attribute 'get_field' error". What is really strange is that I believe that the code was tested and working a month ago and it suddenly stopped working. My code: def save(self, *args, **kwargs): super(Venue, self).save(*args, **kwargs) # Call the "real" save() method. Event.objects.all().filter(venue=self).update(modified=timezone.now()) This error is thrown in subqueries.py: def add_update_values(self, values): """ Convert a dictionary of field name to value mappings into an update query. This is the entry point for the public update() method on querysets. """ values_seq = [] for name, val in six.iteritems(values): field = self.get_field(name) -
how to sent random genereate number to email with django?
while login sent an verification code to gmail and with that verification code is used to get logged in Any hint or suggestion will be greatly appreciated it!! -
Method .clean() of model not triggered when called from viewsets
APIView won't call method .clean() from model on "POST". I have created a model 'Budget' and added an extra validation by overriding method .clean(). The clean is properly called when used in django admin. I have also created an APIView 'BudgetReportView' from this model, however the method .clean() is not called on method "POST". I am looking for the best practice to solve this issue. Should I also add validation in my APIView or override method post and trigger .clean() ? Thanks for the advice (I didn't include code as it is just a question of best practice but I can add it if needed). -
Django create instance model without form
I'm trying to create an instance of "Partita" Model but I don't want to set manually the fields with a form; I need to set the fields (they are two ForeignKey) with a random integer that refers to the id of the Foreign Key. This is for create a type of creator of football matches where "Partita" (match in italian) is composed by team1 and team2 (in my code "casa" and "trasferta") How can I do it? I tried this but it throws a FieldError views.py: def createPartite(request): num1=0 num2=0 gior=0 while num1==num2: num1 = str(random.randint(1,3)) num2 = str(random.randint(1,3)) if num1!=num2: gior=gior+1 cas= get_object_or_404(Fanatsquadra, pk=num1) tra= get_object_or_404(Fanatsquadra, pk=num2) partita = Partita.creaP(cas,tra) partita.save() contesto = { 'partita': partita } return render(request, 'sondaggio/partite.html',contesto) models.py: class FantaSquadra(models.Model): proprietario = models.ForeignKey(User, on_delete=models.CASCADE,unique=True) nome_fantasquadra = models.CharField(max_length=200,unique = True) punteggio = models.IntegerField(default=0) def __str__(self): return self.nome_fantasquadra class Partita(models.Model): giornata = models.IntegerField(default=1) casa=models.ForeignKey(FantaSquadra,on_delete=models.CASCADE,related_name='fantasquadra_casa', unique=True) traferta = models.ForeignKey(FantaSquadra, on_delete=models.CASCADE, related_name='fantasquadra_trasferta', unique=True) def __str__(self): return "giornata "+str(self.giornata) def creaP(self,cas,trasfert): self.casa = cas self.traferta = trasfert return self -
Django2.1.7 ImportError: cannot import name 'util' from 'django.forms' (/Users/lib/python3.7/site-packages/django/forms/__init__.py)
During migration from Django1.5 to Django2.1.7 we are facing an implicit import error in library function when trying to start server. Traceback (most recent call last): Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10945f950> Traceback (most recent call last): File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/MAK/Envs/lifemed3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/json_field/__init__.py", line 1, in <module> from json_field.fields import JSONField File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/json_field/fields.py", line 4, in <module> from json_field.forms import JSONFormField File "/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/json_field/forms.py", line 5, in <module> from django.forms import fields, util ImportError: cannot import name 'util' from 'django.forms' (/Users/MAK/Envs/lifemed3/lib/python3.7/site-packages/django/forms/__init__.py) We have already check this … -
How to reference media url for uploads
I am using a drag and drop JavaScript library to allow users to drag and drop photos onto their profile. The library has a server instance where you point it to where you want to upload the photo to. This is it: server:"#". So basically I'm meant to input the url for where to store my django media files. The issue however is that I don't know how to reference my media urls since it's not really in my urls.py. I've set up the website to recieve media and all but I just don't know how to reference the url for media storahge. I tried "{%url 'media'%}" but that didn't work. #my urls.py below: urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('accountconfirmationpage/', views.accountconfirmationpage, name='accountconfirmationpage'), path('dashboard/', include('main.urls'),)] if settings.DEBUG: urlpatterns +=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) #The Javascript library referencing my media url location <script> FilePond.registerPlugin(FilePondPluginImagePreview); const inputElement = document.querySelector('input[type="file"]'); const pond = FilePond.create(inputElement); FilePond.setOptions({ server: "#" ****Where media url reference is supposed to go**** }); </script> -
Django: How to migrate from ManyToMany to ForeignKey?
I'm building a REST API and server using Django and Django Rest Framework. We are using a postgres database. I need to simplify a badly designed relation. We have a model (House) that has a ManyToMany relationship to another (City). In reality it would be enough when this is a ForeignKey relationship. I googled and couldn't find any blog posts or docs how to properly migrate in this direction. I could only find the other way (FK to M2M). I'm 98% sure that all the data on the server will be consistent with a FK relationship (meaning I'm pretty sure all houses only have one city). We need to change the relationship for several reasons and aren't able to keep the M2M. I'm afraid to just change the model and running makemigrations and migrate. I was wondering, how do you properly migrate from M2M to FK? Are there any caveats I have to take into account? How can I deal with data if surprisingly there are houses with multiple city's? The data set is still quite small (less than 10k entries) if that matters. Thank you very much. -
Can I call DjangoREST APIs from a Laravel application
I have worked on a React-Native application that uses DjangoREST apis to use the database. Basically the backend is on Django. Now I have designed a Laravel web-app for the same organization. Can I call those same APIs so that I can use the same database -
Showing cart status in my shopping webapp
I made my first shopping cart, everything works but now i want to make that when cart is empty then his link should have written "cart is empty" but when i will put something to him then his link should have written "cart". I have that code in html for this: <a href="http://127.0.0.1:8000/cart/"> {% if cart == None %}cart is empty{% else %}cart{% endif %} </a> And now when i am in cart page then his link have written "cart", but when I'm outside cart page then its written"cart is empty", and it doesn't have matter if there are some products in cart or not. cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session=request.session cart=self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart=cart def add(self, product, quantity=1, ): product_id=str(product.id) if product_id not in self.cart: self.cart[product_id]={'quantity':0,'price':str(product.price) } self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified=True def remove(self, product): product_id=str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids=self.cart.keys() products=Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)] ['product']=product for item in self.cart.values(): item['price']=Decimal(item['price']) item['total_price']= item['price'] * item['quantity'] yield item def clear(self): del self.session[settings.CART_SESSION_ID] def get_total_price(self): return … -
static files in django is not working (404) although the path is right
the html page appear without any style or images because of not finding the static files in Django the load : {% load staticfiles %} this is the static call : <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css' %}"> the url setup : STATIC_URL = os.path.join(BASE_DIR, "static/") -
How to create web design like cms and save page as HTML in Django? any suggestion
user create a dynamic web page and some text number fields and save page as HTML and render this page. -
Is there a library in django that can pull docstrings to create documentation?
there appears to be a library to generate docs from docstrings but the documentation will only be available in the django admin interface. Is there a library that will pull the docstrings and dump them in a text, word or excel file? -
django social core `next` parameter lost after do_auht() if user is already logged in
I have couple of services running independently, service B is using social auth to login through service A. When user hit service B like 0.0.0.0:8000/service_b it is redirected to 0.0.0.0:8000/login/service_b. However if user is already loggedIn in service A, while hitting 0.0.0.0:8000/service_b user got logged in thorough service A and next parameter ignored, user remains on service A. I have tried to debug social core pkg, there are couple of methods do_auth() and do_complete(). I can see next parameter at the end of do_auth() stored in session but in do_complete() next parameter is gone. I really want to understand the flow between these two methods that why value stored in session removed between two methods. -
Getting error while pull github to pythonanywhere
error: Your local changes to the following files would be overwritten by merge: db.sqlite3 Please, commit your changes or stash them before you can merge. -
How we can deserialize the nested json object into python model object at once?
When we serialize python model object to nested json data we can serialize it in django as foe example. DataSerializer(data_list, many=True) and output will like that. [ {"name":"user_1", "id":1}, {"name":"user_2", "id":2}, {"name":"user_3", "id":3}, ... ... ] Now I want to deserialize the list of json object to python model object at once. As for example: # the serializer class class UserSerilizer(serializers.Serializer): id = serializers.IntegerField(required=True) name = serializers.CharField(required=True) # Request model class. class UserRequestModel: id = None name = None def __init__(self, dictionary): self.__dict__.update(dictionary) And what I do. # serialize the request data for param validation user_serializer = UserSerilizer(data=request.data) # update the user request model with validate data user_data = UserRequestModel(user_serializer.validated_data) That's why I can access the value user_data.id and user_data.name for the request body {"name":"user_1", "id":1} But how can I do it for list of data at once like we serialize at once with passing parameter DataSerializer(data_list, many=True). -
AWS: Connect RDS postgresql to S3
I'm AWS beginner. I want to build a web app that deals with songs. I used django with RDS postgresql for database. Do I need s3 in order to upload songs? I created S3 bucket, too. but couldn't figure out how to connect rds with s3. Can anybody tell me how to do that, or recommend tutorials? Thanks, in advance. -
django how expire session when the user is not active
I want the session closed when the user is inactive for a certain period of time. I tried set_expiry(300) and SESSION_COOKIE_AGE = 15 * 60, but the session was not extended even if the user was active. -
Group By postgres ORM in Django
i have query like this in postgress select invoice_number,price from order_iklan_baris group by invoice_number,price how i create ORM in django -
How to reuse Django forms
I wanted to reuse Django forms in following scenario Make all form fields "readonly" while displaying Use the same form to get data while editing I've used the below function to make the field readonly while displaying the data, I have also tried with init, class form1(modelForm): fields... def get_form(self, *args, **kwargs): super(form1, self).__init__(*args, **kwargs) for key in self.fields.keys(): self.fields[key].widget.attrs['readonly'] = True but while editing I am unable to use "form1", Django still renders the form as readonly A little help on how to achieve would be greatly appreciated -
How do I extract id from Django queryset in admin update method?
I need to get the id of an object as I update it in the Django Admin. I've tried get() and have printed out the queryset using vars(queryset), but I can't seem to isolate the value I need. I've tried to iterate over it, but to no avail. I should mention I'm using MPTT, so it's a TreeQuerySet. But I don't think that matters. In admin.py: class JokeAdmin(MPTTModelAdmin, ImportExportModelAdmin): ... ... def reviewed_approved(self, request, queryset): queryset.update(reviewed=True, approved=True) print(vars(queryset)) this is the output: {'model': class 'blog.models.Joke','_db': None,'_hints': {},'query': , '_result_cache': None, '_sticky_filter': False, '_for_write': True, '_prefetch_related_lookups': (), '_prefetch_done': False, '_known_rel ated_objects': {}, '_iterable_class': class 'django.db.models.query.ModelIterable', '_fields': None} -
Avoiding getting "Invalid HTTP_HOST header: 'localhost'" message with Django + Elastic Beanstalk
I've got a Django app setup on Elastic Beanstalk. Working and running great. I have my settings file set up with only the allowed hosts needed -- ALLOWED_HOSTS = ['mysite.com'] I get the Django errors sent to my email -- which normally I like. However, every time I redeploy my app (which I do from uploading a ZIP folder, not through CLI) I get this message Invalid HTTP_HOST header: 'localhost'. You may need to add 'localhost' to ALLOWED_HOSTS. I'm having no problems running my site, I just don't like getting this error. I think I could just add localhost (or 127.0.0.1 probably) as an allowed host--however I'm not sure if this is a good idea for security reasons. What might be happening here and how can I fix it? Is adding these hosts OK?