Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert a datetime.date object to string in python
When trying to fetch dates from mysql, and doing a json.dunps on the result for sending it back to html, get this following error : TypeError: datetime.date(2019, 6, 26) is not JSON serializable My db result set looks like : [[(B, datetime.date(2019, 6, 26)), (A, datetime.date(2019, 6, 26))], [(A, datetime.date(2019, 6, 26)), (B, '0000-00-00')]] Tried converting the date object to string using strftime. Does not work. row_headers = [x[0] for x in cur.description] for result in rows: json_data.append(zip(row_headers, result)) for tup in i: core, last_modified = tup if last_modified is not None: last_modified = datetime.strftime(last_modified, '%d-%m-%M') t = datetime.datetime(last_modified) t.strftime('%m-%d-%Y') final_result = {'data': json_data} return HttpResponse(json.dumps(final_result), content_type='application/json') -
Why logging.handlers.RotatingFileHandler prints unknown characters?
I want to store django logs in a file on disk. So I'm using the following dictConfig. But when I check my log file, I see there are some unknown characters printed! What's the problem? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[{server_time}] {message}', 'style': '{', } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, }, 'handlers': { 'django.server': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, 'logfile': { 'level': 'INFO', # 'filters': ['require_debug_false'], 'formatter': 'django.server', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'carpooling.log'), 'maxBytes': 50 * 2**20, # 50MB 'backupCount': 3, }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'filters': ['require_debug_false'], 'include_html': True, }, 'null': { 'class': 'logging.NullHandler', }, }, 'loggers': { 'django': { 'handlers': ['null'], 'propagate': False, }, 'django.server': { 'handlers': ['django.server', 'mail_admins', 'logfile'], 'level': 'INFO', 'propagate': False, }, } } When I request to http://127.0.0.1:8000/ on my browser, I see the [21/Aug/2019 18:28:17] "GET / HTTP/1.1" 200 1868 on console but in the log file the record is as follows: [21/Aug/2019 18:28:17] [m[m[m"GET / HTTP/1.1" 200 1868[0m[0m[0m -
what's the best practice of Spring data JPA query on many optional parameters?
I have a mysql table with many columns, and the users need to query based on arbitrary column (or columns). In django I can easily test the existence of the query parameters and append the queryset likewise. But I'm new to JPA, which seems u have to declare all the possible combinations of query parameters in JpaRepository. or u will have to concatenate the raw sql yourself. So whats the best practice of JPA on arbitrary combination of query parameters? Thank u. -
Install Django with pip but can not see in pip list
I have created virtual environment with python 3.6.Trying to install django with pip.When I run pip install django command, it prompts that requirement already satisfy but I cannot find the django in pip list. $pip install django Requirement already satisfied: Django in /usr/lib64/python2.7/site-packages (1.11.21) Requirement already satisfied: pytz in /usr/lib/python2.7/site-packages (from Django) (2019.1) when I try to check django version on python shell . >>> import django Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'django' Even i have checked in /usr/lib/python2.7/site-packages dir, i cannot find django. How do I fix this? -
Django: Adding a test that has its own set of models
I have a peculiar Django package that defines tools for working with models. This means that I need to write tests in which I define a bunch of model classes, and then do tests on them. Note that for each test, I need to manually write a separate collection of model classes. Is that possible with Django? How can I tell Django "for this test, please use these 7 model classes I defined"? -
Python: Using 'Null' for mysql.connector's port argument
I have a mysql database and I fetch it via a domain like www.mydomain-database.com. this domain is given by a company for accessing my database by phpmyadmin. When I browse this domain, it fetches phpmyadmin login page. I try to connect to this database by the following code: db = mysql.connector.connect( host = "www.mydomain-database.com", user = "root", passwd = "**", database = "database", charset = 'utf8', use_unicode=True ) When I run this, I get the following exept: Can't connect to MySQL server on 'https://www.mydomain-database.com:3306' (-2 Name or service not known) As you can see, connector adds port 3306 to my host; but the url with this port is not valid & it doesn't fetch the phpmyadmin! So, for canceling that change, I added the port = "" as an argument for my connection but I got another error that mentioned the port must be integer! Now the question is, how can I remove that port number when connector tries to connect the host? -
Django query on multiple related objects
I'm having trouble doing a query spanning between a lot of models. This is the query I do to list all animals with encounter.status 'in-progress' and the date immunization date is in the futur. def current_with_futur_vaccines(self): Immunization.objects.filter(recorded__gte=datetime.now())) return ( self.filter( status="in-progress").filter( subject__immunizations__recorded__gte=datetime.now(), ) .select_related("subject") .prefetch_related("subject__immunizations", "location") ) The things is when I want to list the immunizations from the query I get all the immunizations for this animal and not only the immunizations that have to take place in the futur. {% for immunization in object.subject.immunizations.all %} {{ immunization }} {% endfor %} This is the model class Animal(models.Model): name = models.CharField(max_length=250) class Encounter(models.Model): subject = models.ForeignKey(Animal, on_delete=models.PROTECT) status = models.CharField(max_length=11) class Vaccine(models.Model): name = models.CharField(max_length=250) class Immunization(models.Model): subject = models.ForeignKey( Animal, on_delete=models.PROTECT, related_name="immunizations" ) planned_date = models.DateTimeField(default=timezone.now) vaccine = models.ForeignKey(Vaccine, on_delete=models.PROTECT) -
Problem when creating a loop that displays forms
I have an activity table, and the user can select a few of those activities. Based on his selection I redirect him to a new page where he has to select for each activity he previously selected a list of subactivities. So I loop over the activities and I filter the queryset (subactivities) for each of the forms.It is displayed properly but when submitting the form it is invalid. At first I thought it could come from the form sharing the same name but even with one form the error is till there. I have tried to print out what the form looks like after selecting both Aluminium and Plastic upcycling: [21/Aug/2019 15:26:53] "POST /subactivities/ HTTP/1.1" 500 59980 False <tr><th><label for="id_subactivity">Select specific activities:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select name="subactivity" required id="id_subactivity" multiple> <option value="Aluminium upcycling">Aluminium upcycling</option> <option value="Plastic Upcycling">Plastic Upcycling</option> </select></td></tr> Internal Server Error: /subactivities/ Traceback (most recent call last): File "C:\Users\lavoye\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\lavoye\AppData\Local\Continuum\anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view blog.views.Subactivities didn't return an HttpResponse object. It returned None instead. class Subactivities(TemplateView): template_name = 'blog/subactivities.html' context = {'title': 'Subactivities selection page'} def get(self,request): self.context['form_subact_list']=[] for activity in … -
How to add a custom field as metadata when creating a customer with woocommerce api
To begin with, I have a field in my model called afm. I find difficulty in posting among with other fields, the value of this field during the procedure of creating a customer. The procedure of creating an instance of a customer happens from my django application. After creation the instance is also visible (after posting) to the woocommerce --> users section of the administration panel of the website. The custom meta field has the key : wholesale_afm How is it possible to put this custom field in the data dictionary? Below is my unsuccessful attempt. def create_woocommerce_client_individually(wcapi,name,surname,username,email,afm): data = { "first_name": name, "last_name": surname, "username": username, "email": email, "meta":{ "wholesale_afm":"afm", } } wcapi.post("customers", data).json() print("storing the client to woocommerce website...\n") -
Return data from SQL with Django/Python
I am new to python/django and am wondering how I go about doing this. Do i need models.py if I already have the database created? If not, how do i go about querying the db to return the data? I have the settings.py file pointed to the db. settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Database', 'USER': 'User', 'PASSWORD': 'Password', 'HOST': 'Server', 'PORT': '1433', -
How can I HyperLink to another model using the property of a ForeignKey in a serializer
I'm trying to generate a link to the user when serializing a snippet (i.e. my model). The model already has a foreign key that links to the user who creates this snippet, but I don't know how to link HyperlinkedRelatedField to that user. The code is based on django-rest-framework's official tutorial 05, you can find it here serializers.py: class SnippetSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="rest-serial:snippet-detail") # TODO: Link to the user # Currently this would use the snippet's pk as the user's pk owner = serializers.HyperlinkedRelatedField(view_name="rest-serial:user-detail") ... class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] models.py from django.contrib.auth.models import User class Snippet(models.Model): owner = models.ForeignKey(User, related_name='snippets', on_delete=models.CASCADE, null=True) ... I was thinking about something like owner = serializers.HyperlinkedRelatedField(view_name="rest-serial:user-detail", queryset=User.objects.filter(id='owner.id')) but apparently that's not how django works. Can anyone point me a direction? -
Adding One-To-One field to the default Django user model
I'm trying to add one-to-one field to the default Django user model but for some reason I keep getting error from the database: django.db.utils.IntegrityError: NOT NULL constraint failed: frontend_usermodel.test_suites_id this is models file: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.db import models class TestSuite(models.Model): id = models.IntegerField(primary_key=True) ... ... def __str__(self): return self.name class Meta: ordering = ('name',) class UserModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) test_suites = models.OneToOneField(TestSuite, on_delete=models.CASCADE) def __str__(self): return self.email @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserModel.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() What can I do to solve this ? -
Amazon Web Services - S3 'The authorization mechanism you have provided is not supported' in Django
I am trying to configure my Django application to host image files within an AWS S3 bucket, but the images won't load. Instead, I receive the following error message: 'The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256' I'm aware that this issue has been raised by others using different languages, and I've tried some suggested solutions but nothing has worked so far. My config settings are displayed below: # env.py os.environ.setdefault("AWS_ACCESS_KEY_ID", "AKIA6A6ODKPNZNKA2ZFS") os.environ.setdefault("AWS_SECRET_ACCESS_KEY", "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") os.environ.setdefault("AWS_STORAGE_BUCKET_NAME", "acceler8-company-logos") os.environ.setdefault("AWS_S3_REGION_NAME", "eu-west-2") # settings.py AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = os.environ.get('AWS_S3_REGION_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # boto.cfg [s3] use-sigv4 = True I initially didn't include AWS_S3_REGION_NAME in my configuration because in the S3 console it says 'S3 does not require region selection'. What I read regarding the error message suggested that this was necessary, but adding it to the config hasn't helped. I also added the 'boto.cfg' file, following AWS guidance (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html) but this hasn't helped either. -
What's the purpose of verbose_name and help_text in Django model fieds?
I'm wondering what's the purpose of setting verbose_name on Django model fields and how it's different from help_text. How are these being used by Django? -
How can I reject and close connections in django-channels 2?
It's been 1 month since I started using django-channels and now I have a feeling that I am not disconnecting websockets properly. When I disconnect I want to destroy the group completely if no one is there and it should be no sign of existence. When I'm rejecting connections I raise channels.exceptions.DenyConnection or send {'accepted': 'False'} I was just wondering if this is the right way to do things that I've mentioned or not. -
Passing two models data which have Foreign key relationship to one html Template
I have two models. First one is Cars second one is Rating. I have list view, I am showing all cars here and I want to show cars average rating and rating count also. I have tried adding new fields (avg_rating and rating_count) to my cars model and updating these fields while new rating was submitted. But it is not seen me as good way. Cars Model class Cars(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name Rating Model class RatingModel(models.Model): reviewed_item = models.ForeignKey( Cars, on_delete=models.CASCADE ) excellent = models.FloatField( max_length=20, default=0 )... bad = models.FloatField( max_length=20, default=0 ) cars view class CarsView(BaseContext, TemplateView): template_name = "pages/all_cars.html" def get_context_data(self, **kwargs): context = super(CarsView, self).get_context_data(**kwargs) context["cars"] = Cars.objects.all().order_by("-id") return context -
Is secure to use jwt in android?
is secure to use JWT token in android ? i'm thinking it's not secure because when the user posts the username and password to the server the receives a token and i should save that to the database and use this token in app but the question is is that secure ??? because any rooted app can access to the database and use token in Api Url. one of the solutions i've read is to save token with encryption methods like AES or RSA (same question is that sequre?) should i use OAUTH2(is that more secure that jwt?)? -
Passing Parameters From a Class Based View in Django
I have a class based Update view "ManifestUpdate", which is a modal pop up, and is launched from within another function based view "Manifest". I need to be able to take the field = 'reference' from my ManifestUpdate view and make it available to the "Manifest" view as 'Reference_Nos'. As you can see ManifestUpdate should direct the user to Manifest, but it does not, just nothing happens (it works if I change this to direct to any other view). I believe this is because I am not passing that parameter. Can anyone tell me how to capture that 'reference' parameter within ManifestUpdate and pass it to Manifest from the class based view? views.py class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() reference_id = form.cleaned_data.get('reference') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': … -
Keeping a database size down using unique fields with Django
I ran into a snag on a project today, and considering it's already got quite a bit of data entered, destruction and rebuilding is not a good option. So here it is... This is a site that is basically a helper tool for people learning Mandarin Chinese (for now). A user keeps track of their phrases, vocab, grammar points. Originally, I just set all three of these to be unique fields in that (for example) nobody can enter the same vocab twice. For some reason, that change was either reverted or I did away with it. I don't remember, and it's too late for back tracking now. So my question here is, how can I change my model up so that one user can't make the same exact entry as another user? And as a follow up, if a user does try and make a duplicate entry, I can give said user is given the option to view\modify that entry? from django.contrib.auth.models import User from django.db.models.aggregates import Count from django.db import models from random import randint # Create your models here. SOURCES = [ ('DUOLINGO', 'Duolingo'), ('MEMRISE', 'Memrise'), ('CLASS', 'Class'), ('OTHER', 'Other'), ] LEVELS = [ (1, 1), (2, 2), … -
How to format Django's timezone.now()
I am trying to autofill a django datetimefield using a timezone aware date. Using Django's timezone.now() outputs Aug. 21, 2019, 5:57 a.m.. How can I convert this to 2019-08-21 14:30:59 ? -
Multiple django fields reflects to one db field
How to create a model with 2 different fields with the same db_column? In my example queue_id and content_type_id are always the same id value. So I don't want to store that information twice in a DB table. I set a db_column for both fields but got the error (models.E007) Field 'content_type' has column name 'queue_id' that is used by another field. I added error supression. As result I have an invalid sql code for migration: CREATE TABLE `queue_items_generic` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `object_id` integer UNSIGNED NOT NULL, `queue_id` integer NOT NULL, `queue_id` integer NOT NULL); Manual migration patch has helped. But is there an easier way to do the same stuff? I don't want to patch migrations and supress any errors. Here is the reproducing problem code: from django.db.models import ( Model, ForeignKey, OneToOneField, CASCADE, PositiveIntegerField, ) from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class QueueGeneric(Model): content_type = OneToOneField( ContentType, on_delete = CASCADE, primary_key = True, ) last_object_id = PositiveIntegerField( default = 0, ) last_object = GenericForeignKey('content_type', 'last_object_id') class QueueItemsGeneric(Model): queue = ForeignKey( QueueGeneric, db_column = 'queue_id', on_delete = CASCADE ) content_type = ForeignKey( ContentType, db_column = 'queue_id', on_delete = CASCADE ) object_id = … -
why its showing csrf verification failed even though i imported render
CSRF verification failed. Request aborted. i already tried importing render but it doesnt worked out for me. from django.contrib.auth import login as auth_login from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) -
How to log request and response for 4XX Http status in Django Rest Framework?
The default behaviour of DRF is to throw exception for 5XX, but return valid response with error details for 4XX. I want to log request and response of any API call which fails with 4XX. Currently the log only shows Bad Request : /path/api/ -
OAuth Callback URL incompatible with nginx proxy server behavior
I have spent a good part of the last 3 days trying every solution that is on the internet and feeling desperate. Here's the problem statement: I have a Dockerized app with three services: A django application with gunicorn (web) A Nginx server (nginx) PostgreSQL (db) My web application requires user to log in with their GitHub account through a fairly standard OAuth process. This has always worked without nginx. User clicks on the "log in with github" button, sent them to GitHub to authorize the application, and redirects it back to a completion page. I have "Authorization callback URL" filled in as http://localhost:8000. Without Nginx I can navigate to the app on localhost, click on the button, and upon authorization, get redirected back to my app on localhost. With Nginx, I would always fail with the error: This is my Nginx configuration: upstream webserver { # docker will automatically resolve this to the correct address # because we use the same name as the service: "web" server web:8000; } # now we declare our main server server { listen 80; server_name localhost; location / { # everything is passed to Gunicorn proxy_pass http://webserver; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; … -
I can't solve this "parsererror" ajax error
I am currently doing ajax with django. However, the response becomes an error. Access the views with ajax and create a model. And now we ’re ready to create. I think there is a problem with the return of views. Add any additional information you need. #error fail 200 (index):150 parsererror (index):151 SyntaxError: Unexpected token a in JSON at position 0 at parse (<anonymous>) at Ut (jquery-3.3.1.min.js:2) at k (jquery-3.3.1.min.js:2) at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2) #JavaScript $('form').on('submit', function(e){ let $submit_input = $(this).find('input') let $data = $(this).data('group') console.log($data); e.preventDefault(); $.ajax({ 'url': "{% url 'groups:ajax_post_add' %}", 'type': 'POST', 'data': { 'group': $data, csrfmiddlewaretoken: '{{ csrf_token }}', }, 'dataType': 'json', beforeSend: function(xhr, settings) { $submit_input.attr('disabled', true); } }).then((...args) => { // done const [data, textStatus, jqXHR] = args; console.log('done', jqXHR.status); }) .catch((...args) => { // fail const [jqXHR, textStatus, errorThrown] = args; console.log('fail', jqXHR.status); console.log(textStatus); console.log(errorThrown); }) }); #python #views @require_http_methods(["POST"]) def GroupRequestAdd(request): group_id = request.POST.get('group') group_id = group.objects.get(id=group_id) request_add = belong.objects.create(user=request.user,group=group_id) return HttpResponse("ajax is done!")