Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I connect my Firebase Hosted Website to my Android App? I want to use a common realtime database for app and website users
I have already hosted my web app on Firebase. I have connected by Android application to firebase. How can they communicate in real time and using a common database. I have used Django for backend of the website. -
How to solve "IntegrityError at /measurements/ NOT NULL constraint failed: diabetes_measurements.patient_id" probem in django
I have made a form which name is MeasurementsForm by using Measurements model. by whenever I use form.save() in views, it throws an error and does not store data. but if i do not use form.save() it does not throw an error also does not store data. in Measurements model, I have a field name patient which has foreign key relation with user sign up custom model. now how to fix this and store data after submitting the form. my models: class Measurements(models.Model): d_value=models.IntegerField() created=models.DateTimeField(auto_now_add=True) patient=models.ForeignKey(UserSignupModel,on_delete=models.CASCADE) def __str__(self): return str(self.patient) my forms : class MeasurementsForm(forms.ModelForm): d_value=forms.IntegerField(help_text="insert the diabetes") class Meta: model=Measurements fields=('d_value',) my views: def measurement(request): if request.method=="POST": form=MeasurementsForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form=MeasurementsForm() return render(request,'diabetes/measurement.html',{'form':form}) -
FileField does not work properly in template but in admin it works , Django , Digitalocean , Aws S3
I have some problems with imagefield , I store them on AWS though DigitalOcean . Here is most interesting : When I upload image on though admin panel on works fine and when I'm trying to do the same in template , image updated but not stored on AWS . When I try to click to this image in admin panel instead of image I get this This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <BucketName>financal-space</BucketName> <RequestId>tx000000000000004683770-005ec5341d-ab90b1-ams3b</RequestId> <HostId>ab90b1-ams3b-ams3-zg02</HostId> </Error> Here is my image post request if 'imagechange' in request.POST and request.FILES['image']: user = request.user.id image = request.FILES['image'] fs = FileSystemStorage() image_fs = fs.save(image.name, image) image_new = CustomUser.objects.filter(user=user).update(image=image_fs) is there any solutions ? -
Python3.7 ImportError: No module named 'django'
Few days ago i decided to update python from 2.7 to 3.7 version. So now here is how looks my configuration: Ubuntu 16.04 Python 3.7.7 Django 3.0.6 Apache/2.4.18 using command python -m venv --system-site-packages /var/www/path/to/myenv i've create virual environment, after activation of this environment i've created new project. So path to the environment looks like this /var/www/path/to/myenv and path to project looks like this /var/www/path/to/myenv/myproject. Configuration of myproject.conf looks like this: <VirtualHost *:80> ServerName myproject.com ServerAlias www.myproject.com WSGIDaemonProcess myproject processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/path/to/myenv python-path=/var/www/path/to/myenv/myproject WSGIProcessGroup candyhand WSGIScriptAlias / /var/www/path/to/myenv/myproject/myproject/wsgi.py <Directory /var/www/path/to/myenv/myproject/myproject/> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/path/to/myenv/myproject/> Require all granted </Directory> CustomLog /var/www/path/to/myenv/myproject/logs/apache_access.log combined ErrorLog /var/www/path/to/myenv/myproject/logs/apache_error.log Alias /static/ /var/www/path/to/myenv/myproject/static/ <Directory /var/www/path/to/myenv/myproject/> Options Indexes MultiViews FollowSymLinks AllowOverride None Require all granted </Directory> Alias /media/ /var/www/path/to/myenv/myproject/media/ <Directory /var/www/path/to/myenv/myproject/> Options Indexes MultiViews FollowSymLinks AllowOverride None Require all granted </Directory> </VirtualHost> But i've got 500 error from apache server. Here is log from apache server: mod_wsgi (pid=9495): Target WSGI script '/var/www/path/to/myenv/myproject/myproject/wsgi.py' cannot be loaded as Python module. [Wed May 20 16:25:08.145621 2020] [wsgi:error] [pid 9495] mod_wsgi (pid=9495): Exception occurred processing WSGI script '/var/www/path/to/myenv/myproject/myproject/wsgi.py'. [Wed May 20 16:25:08.145788 2020] [wsgi:error] [pid 9495] Traceback (most recent call last): [Wed May 20 16:25:08.145864 2020] … -
reverse for 'topic' not found. 'topic' is not a valid view function or pattern name
I am new to Python3 and Django and I am trying to build a small webapp by following instructions from a book. I have been trying other solutions find online like using " instead of ' or change the name of the template 'topic' that does not work as its name was too close from another template 'topics' of the app which might have caused trouble for Django. Here are my three files: urls.py """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name= 'learning_logs' urlpatterns=[ #Home Page path('', views.index, name='index'), # Topic Page path('topic/', views.topics, name='topics'), path('topics/<int:topic_id>/', views.topic, name='topic'), ] views.py from django.shortcuts import render from .models import Topic # Create your views here. def index(request): """The home page for Learning Log""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics= Topic.objects.order_by('data_added') context= {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries""" topic= Topic.objects.get(id=topic_id) entries= topic.entry_set.order_by('-data_added') context= {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ` topic.html {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ sujet }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p> {{entry.data_added|date: 'M d, Y H:i'}}</p> <p>{{entry.text|linebreaks}}</p> </li> {% … -
How to pass a decorated Factory as a SubFactory in factory_boy
I have the following decorated class: @factory.Faker.override_default_locale("en_CA") class AddressFactory(factory.django.DjangoModelFactory): address_line_1 = factory.Faker("street_address") address_line_2 = factory.Faker("secondary_address") postal_code = factory.Faker("postalcode") country = "CA" state_province = factory.Faker("province") city = factory.Faker("city") telephone = "+16045555555" class Meta: model = Address and I need to use AddressFactory as a sub factory for my UserFactory: class UserFactory(factory.django.DjangoModelFactory): first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') title = factory.Faker('job') address = factory.SubFactory(AddressFactory) class Meta: model = User password = factory.PostGenerationMethodCall("set_password", "pi3.1415") However, when I try to create an instance using UserFactory() I get the following error: ValueError: A factory= argument must receive either a class or the fully qualified path to a Factory subclass; got instead. I know the error is due to the decorator, so is there any way to solve this without removing the decoration since I will have to pass the locale in the fields I need it or I will have to change the global locale which is not what I want. -
How to create multiple y-axis time series chart
I am trying to map multiple charts where x-axis (time) is fixed but y-axis can take multiple values like CPU%, RAM, IO-RATE and so on. If I try to build individual graphs things seems pretty easy but I have this weird requirement where I need to map everything on to same chart. I have been trying out things with chartjs library and I could see that Cartesian axes is capable of handling multiple axes. But the examples I find around Cartesian mostly have x-axis with some fixed label values. In my case it's time and I wonder how to do the same for time series. I also found this example for multiple time series but that doesn't seem to create multiple y-axis. What is required is something like this but I am having hard time trying to figure out how to achieve this. I am using django for backend and I am open to try out any library out there that does this and can easily integrate with django. Currently I have been exploring things with chartjs. -
Django: BlockingIOError: [Errno 11] write could not complete without blocking
I have django project: In have a view which updates some values In the view i have few print commands I am trying to run the same url using curl multiple times like eg: curl "127.0.0.1:8000/update?var=somevalue001" curl "127.0.0.1:8000/update?var=somevalue002" . . . . . . curl "127.0.0.1:8000/update?var=somevalue100" But after 40 times running it starts giving the error BlockingIOError: [Errno 11] write could not complete without blocking How to avoid it -
Django Social Auth Google Oauth2 user not authenticated
Trying to implement a simple Signup/Login with Google but on the login redirect view the user is AnonymousUser. Tried to pdb in the pipelines and the user is authenticated correctly until it reaches the complete view in social_django/views.py The user is created correctly, a user social auth link is also created like email@example.com 47 google-oauth2 email@example.com Below are my settings settings.py MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True SOCIAL_AUTH_POSTGRES_JSONFIELD = True SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "KEY" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "SECRET" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' LOGIN_URL = '/auth/social/' LOGIN_REDIRECT_URL = '/auth/social/' SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/auth/social/' SOCIAL_AUTH_LOGIN_ERROR_URL = '/auth/error/' SOCIAL_AUTH_LOGIN_URL = '/auth/social/' -
Pass parameters to GET api in Django Swagger
I am currently able to view the endpoint in swagger UI but I am unable to pass the url parameter in the UI as shown below. views.py @api_view(['GET']) def single_page_scan(request): """ param --- career site url """ url = request.GET.get('url') start = time.time() ans = site_scan_helper(url) end = round(time.time() - start) final_ans = {} final_ans[url] = ans time_taken = str(end) + ' Seconds ' data = table(name = request.user.username,url = url, time_taken=time_taken, status='Success', run_type='Single_Scan', timestamp=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')) data.save() return JsonResponse(final_ans,safe=False) Please suggest how to pass parameters in the swagger UI -
Django Admin Debounce
I am using Python Django Admin with as little as possible custom templates and javascript code. Is there a way to debounce click on specific button (or form submit)? E.g. if user clicks two times (in a short period of time) on the save button, only one call should be made. -
How can I make datetime.now() returns a timezone aware date object?
I'm changing an application to save all the dates in UTC. The application uses datetime.now() in many places across several modules. I would like a way in which datetime.now() be in UTC timezone by default without having to change every line to timezone.now() or datetime.now(timezone.utc) nor something similar. The application is in python 3.6.6. I thought that changing USE_TZ to True and set TIME_ZONE = 'UTC' when calling datetime.now() would return a timezone aware date object, but it's not working. Is there a way to accomplish this without changing line by line? -
django debug toolbar not showing on server
I'm using Django 2.2. I want to show django-debug-toolbar on the staging server. I have added the server ip to the INTERNAL_IPS list INTERNAL_IPS = ['server-ip'] and the urlpattern if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns This is showing debug toolbar on localhost when INTERNAL_IPS is set to ['127.0.0.1'] But on the server the same is not showing. Debug to True and all other features of debug is working. -
How to use DRF Object-level permissions together with a token?
I may have a simple question. I only want to allow the creator of a post to delete or update it. All other users can only read the post. For this I use the object-level permissions of the Django Rest Framework. To authenticate the user I use django-rest-knox. Knox creates a token for each user for authentication. Permission class PostOwnerPermssion(permissions.BasePermission): """ Check if authenticated user is story author """ def has_object_permission(self,request,obj,**kwargs): if request.user.id == story.author: return True return False API # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, PostOwnerPermssion ] serializer_class = UserSerializer def get_object(self): return self.request.user However, if I now use Postman to update another user's post, I can still do so. For example, when I put the token of user 12 in the header of the post request I can still edit the post created by user 20. I think the reason for this could be that Django does not know to which user ID the token belongs. So my question is, how can I translate the Knox token into a user ID? -
DJANGO - Upload an image file from directory to DB
I've Images in my project folder created automatically and I want to upload these images to my MySQL DB. These images are named img0.png, img1.png.. etc What I am currently doing : views.py ... for i in range(imageCount): img = open("img%s.png" %i) obj = userImages(userId = userid, images=img) obj.save() ... models.py class userImages(models.Model): userId = models.IntegerField() images = models.ImageField() This doesn't work. How can I make it work?? -
Translate django model choices
i'm looking for a way to tranlate my models choices. There is my model: class CompteFinancier(models.Model): STATUS__OUI_NON = ( ('--------', '--------'), (STATUS_OUI, 'Cas num 1'), (STATUS_NON, 'Cas num 2') ) Cabinet = models.CharField(blank=True, max_length=200, null=True) requis_pour_deposer = models.CharField(blank=True, max_length=200, null=True) credibilite_cabinet= models.CharField(choices=STATUS__OUI_NON) Can someone show me show to trans my choices cas please ? -
Best way to reference two associated models in the third model in Django
I need to reference Category and SubCategory models in the Product model. But SubCategory has a ForeignKey to Category. Right now I am referencing as shown below. Is there a better way or is this correct? class Category(models.Model): category_name = models.CharField(max_length=250) def __str__(self): return f'{self.category_name}' class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory_name = models.CharField(max_length=250) def __str__(self): return f'{self.subcategory_name}' class Product(models.Model): company_category = models.ForeignKey(Category, models.SET_NULL, blank=True, null=True) company_subcategory = models.ForeignKey(SubCategory, models.SET_NULL, blank=True, null=True) -
Does anyone know how Django Simple History handles future model changes?
This is general, but does anyone have any idea if after the initial migration, Django Simple History will also handle future updates to that model? So, say I have Model 1, and it's registered with DSH so there is a separate historic records table for it - if I modify Model 1 later (add a new field, for example) and then migrate - does it also update the related DSH table with the new field? Similarly, if you delete a field, how does that affect it? Thanks T -
django rest framework display model instances
I am trying to display all model instances. Main Project urls.py: from .views import api_root, endpoint_info, test urlpatterns = [ path('admin/', admin.site.urls), path('test', test) ] Main Project views.py: from project.models import Project from rest_framework.decorators import api_view, renderer_classes from rest_framework.renderers import JSONRenderer @api_view(['GET']) @renderer_classes((JSONRenderer,)) def test(request): projects = Project.objects.all() for project in projects: return Response({'client_name': project.client_name}) # return Response({'client_name': 'string_value_random'}) <-- tried returning string too I get this error: AssertionError at /test Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` Also I tried returing return Response({'client_name': 'string_value_random'}) but still get the same error. How should I display the records? -
Imagefield does'not properly work , Django , Digitalocean , Aws
I have some problems with imagefield , I store them on AWS though DigitalOcean . Here is most interesting : When I upload image on though admin panel on works fine and when I'm trying to do the same in template , image updated but not stored on AWS . When I try to click to this image in admin panel instead of image I get this This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <BucketName>financal-space</BucketName> <RequestId>tx000000000000004683770-005ec5341d-ab90b1-ams3b</RequestId> <HostId>ab90b1-ams3b-ams3-zg02</HostId> </Error> Here is my image post request if 'imagechange' in request.POST and request.FILES['image']: user = request.user.id image = request.FILES['image'] fs = FileSystemStorage() image_fs = fs.save(image.name, image) image_new = CustomUser.objects.filter(user=user).update(image=image_fs) What are problems ? -
How to change the value of BooleanField automatically
This is my first Django application. I am making a blog and I want to categorize the posts according to their category(World, Tech, Tutorial, etc.). So I am using multiple boolean fields for a user to check according to the post type. But I want other values to turn False if one is checked(turned True) Please help me -
Problem while loading static files|| django
iam learning Django i have learned pretty much. I used static method to rendered css and other static files. But changes iam making to css which is in static files are not reflacting on webpage . i have to close all files and restart vscode again to see those changes. I have not added code because im not getting any error at all . Any one who knows why because to see changes restart whole project will never be a good option. thanks in Advance -
Annotation with a subquery with multiple result in Django
I use postgresql database in my project and I use below example from django documentation. from django.db.models import OuterRef, Subquery newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1])) but instead of newest commenter email, i need last two commenters emails. i changed [:1] to [:2] but this exception raised: ProgrammingError: more than one row returned by a subquery used as an expression. -
Can someone help me fix this? first time trying this. AttributeError: type object 'Post' has no attribute 'published'
This is in view.py class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 4 template_name = 'blog/post/list.html' -
{{ obj.photos.url }} not showing images
i have a PostListView page and a DetailPageView in the DetailPageView i have no problem to show the image and fetch the data BUT in PostListView i CAN fetch data without problem BUT the images shown only in path, like /media/blog/img/01.jpg <-- The path is correct but there is not showing any image. Do you have any idea what the problem could be list.html {% for obj in object_list %} ... {{ obj.photos.url }} ... {% endfor %} detail.html {{ object.photos.url }}