Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Project to Create App Files and Project Templates
Hey StackOverflow Community, I've created a project to help fill in all the files I normally use/create for my Django Projects. This has saved me a lot of time so I wanted to share it. https://github.com/linusidom/django_create_base Questions I had (no particular order/importance): How can I make this project more useful? What areas can I refactor? What are some best practices that I'm missing? Are there projects like this that exist already? Anything else that I should look at to make this project more useful? Thanks in advance and I hope this helps others :) -
unable to serve Django media files on the server?
I am using a Django version - 2.0.6. and running the server on google compute engine VM instance. My apache files are not configured to server the production base and local settings differently. Currently the settings are running from base.py and local.py. I have configured my media and static files like this: my settings module(both base.py and local.py): STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "static-root") MEDIA_URL = '/media/' MEDIA_DIR = os.path.join(BASE_DIR,'media') MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "media-root") my urls.py: urlpatterns = [ .... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I try to upload any media file it does not get saved in the "MEDIA_ROOT" location rather it get saved in "MEDIA_DIR". How to serve media_root and media_dir in production?(/var/www/venv) Static files are functional. Hierarchy: /var/www/ ----->media-root >static-root >venv--->src--->manage.py >media >other apps & settings -
Auto Self Many to Many Relations on Post Save
I created self many to many relation on my model and i want to add automatically relationship to self. i add this field to my model : client = models.ManyToManyField('self', blank=True, symmetrical=False) i tried two way : one is on model saved function : def save(self, *args, **kwargs): self.client.add(self) super().save(*args, **kwargs) second way is post save signal : @receiver(post_save, sender=Company) def post_save_receiver(sender, instance, *args, **kwargs): instance.client.add(instance) instance.save() but relationship is not happening. -
Images aren't cached using Amazon S3
I am using Amazon S3 for serving image files. Ever since, when I reload the page none of the images from S3 are cached and therefore a lot of requests are made to S3 as well as the loading time significantly increased. I added the Cache-Control header and Expires header through AWS management and I can see they are applied to every image. What do I need to do to make the images being cached and retrieved from cache for the user? -
Adjust visibility in UpdateView and its fields
Adjust visibility in UpdateView and its fields, I'm updating here the image field, and it's working perfectly, my question is: I did not want the field "currently" to be visible, and I'm not getting validation of the form, if I send it blank it passes However, afterwards I will do via updateviews the update of email, name, and the others and in that I wanted that the popup was populated by the data views.py class PhotoUpdate(LoginRequiredMixin, UpdateView): model= Usuario fields = ['foto'] template_name='change-photo.html' def get_object(self, queryset=None): if queryset is None: queryset = self.get_queryset() # This should help to get current user # Next, try looking up by primary key of Usario model. queryset = queryset.filter(pk=self.request.user.usuario.pk) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404("No user matching this query") return obj def get_success_url(self): return reverse('sistema_perfil') url.py from django.conf.urls import url from django.urls import include, path, re_path from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from .views import ( index, cadastro, cadastro_novo, cadastro_negocio, activate, account_activation_sent, perfil, profile_detail, change_password ) urlpatterns = [ url(r'^index/$', index, name='sistema_index'), url(r'^cadastro/$', cadastro, name='sistema_cadastro'), url(r'perfil/$', perfil, name='sistema_perfil'), url(r'^cadastro-novo/$', cadastro_novo, name='sistema_cadastro_novo'), … -
How to marge created barcode image in Django 2?
I was trying to create barcode image and I did that successfully but the problem is now I want to merge them in one image like the user will say I need 4 images then the system will generate one image with 4 barcodes where the barcode weight is 4 cm and height is 2 cm View.py import barcode from barcode.writer import ImageWriter @login_required(login_url='loginPage') def printBarCode(request): barCodeImage = barcode.get('Code128', '12345678910', writer=ImageWriter()) file = barCodeImage.save(barCodeImage) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) The image I get The image I want -
Django images NOT showing when exporting template as PDF
I've been looking for and trying out quite some solutions for this problem (here, here and many more) but I'm still not able to fix this. So, I'm using PDFViewMixin to export a template as a PDF: from django.views.generic.detail import TemplateResponseMixin class ExportViewMixin(TemplateResponseMixin): filename = None content_type = 'text/html' def get_filename(self): return self.filename def get_content_type(self): return self.content_type def document_to_response(self, response, context=None): raise NotImplementedError('Subclasses must implement this method') def render_to_response(self, context, **kwargs): response = HttpResponse(content_type=self.get_content_type()) response['Content-Disposition'] = 'attachment;filename="%s"' % self.get_filename() self.document_to_response(response, context=context) return response class PDFViewMixin(ExportViewMixin): '''Generic view that render a template into a PDF and return it as response content. ''' content_type = 'application/pdf' def gen_pdf(self, context): template = get_template(self.template_name) # need absolute_uris to correctly get static files try: html_doc = HTML(string=template.render(Context(context)), base_url=context.get('base_url')) except TypeError: # Django>=1.11 html_doc = HTML(string=template.render(context), base_url=context.get('base_url')) return html_doc.render() def document_to_response(self, response, context=None): self.gen_pdf(context).write_pdf(response) def get_context_data(self, **context): context = super(PDFViewMixin, self).get_context_data(**context) context['base_url'] = self.request.build_absolute_uri() context['content_type'] = self.get_content_type() return context The view that controls the template inherits from PDFViewMixin and django DetailView. In the template I try to render the model's ImageField as follows (which perfectly works before exporting it): {% if object.image %} <img src="{{ object.image.url }}"> {% endif %} I believe (as pointed out here) … -
how to create a service that can be fired like command `start/stop/status servicename` in centos6
i need to create centos6 service that can be fired like start/stop/status nameservice and inside this service i want to put python command like python manage.py runserver. I am totally new and don't know how to achieve this, so can anyone help me here with explanation how this can be done? -
Can't use uwsgi to launch django service after update the code
I can't access my website after update codes. My Django server was launched by "Uwsgi" When i access my website, it will raise an exception "No module named xxx.urls", by the way "xxx" which means a new app which i just added. But if i use python manage.py runserver, it works. Cant't figure out! Need some help! -
Receiving Wagtail API responses programmatically
Suppose I have defined a Wagtail endpoint: class EventEndpoint(BaseAPIEndpoint): model = Event In this case, Event is subclass of the Wagtail Page class. I have another view (an old school Django view function), which sends various information from a few models that might look like this: { "motd": "...", "opening_times": [ ... ], ... } I would like to nest the result of some queries inside that function, like so: { "motd": "...", "opening_times": [ ... ], ..., "events_today": { /* serialized result */ } } Where events_today might contain a the serialized result of Events How can I programmatically serialize the result of a query (say Event.objects.filter(...)) to inject into that view, in the same way that BaseAPIEndpoint does it? -
Backend for react native application
I already tried various resources available on internet. I also refer django rest framework documenatation. I need sample code in django or flask or any python code which can be used as a backend for app which having sample login screen with usene and password -
Integrating CCAavenue Payment Gateway with Django
I have downloaded the CCavenues Python Starter kit but I am unable to figure out how to integrate it with my Django application. Could anyone please provide me the steps or guide me on how to proceed with this. please note I have the necessary keys with me. Just need to figure out how to put it all together. -
Django:Applying filter() function is giving NameError
Class Connect(models.Model): connection = models.Charfield(max_length=120) Values of 'connection' field of objects of 'Connect' model can be 'Chat','Video' or 'Call'. Following is my Visitor model which has 'connecting_medium' as M2M field. Class Visitor(models.Model): name = models.CharField(max_length=120) connecting_medium = models.ManyToManyField('Connect') What i know that if 'v' is an object of 'Visitor' model then the following line of code will give list of connection for this particular visitor 'v'. connection_list=list(v.connecting_medium.values_list('connection',flat=True)) Now my motive is to get all those 'Visitor' objects which have 'Chat' in their connection_list.I have written the following code but it doesn't seem to work.It is raising an error that: name 'connecting_medium' is not defined. def my_view(request): context['list_no'] = Visitor.objects.filter('Chat' in list(connecting_medium.values_list('connection',flat=True))) #--------------------rest-of-the-code----------------------------# P.S: Above code is only sample.I am not allowed to post source code of company's project.But the situation is exactly like this. -
Trouble using <username> in URL
I am trying to give my URL a more personalized design so for every user I want them to access their profile following this path: www.mysite/profile/myname I have tried that on the URL : path('profile/<username>/', user_views.profile, name='profile') But when i go there http://localhost:8000/profile/gg/ there is no profile and the error is : profile() got an unexpected keyword argument 'username' Thanks -
Persistent data among tests with django and pytest
The idea behind this question is simple to understand but complex to solve: I need to share data among tests. I have a Django project and I use pytest-django and pytest-descibe for defining and running tests. While in pytest the database is rolled-back after every test, in the "describe-way" it's common to share "context" among tests within the same describe. This makes writing tests more readable and fast to run, and allows to run all the assertions even if a single test fails in between. For this reason I'd like to turn off the default behaviour of database rollback on each test and instead do it after the whole describe is run. This is a simplified version of my tests: pytestmark = [pytest.mark.django_db] def describe_users(): email = 'foo@example.com' def test_create_a_user_and_it_exists(): User.objects.create(email=email) assert User.objects.filter(email=email).exists() # Pass def test_the_user_keeps_to_exist(): assert User.objects.filter(email=email).exists() # Fail I tried using the fixture db_access_without_rollback_and_truncate suggested on the documentation but it didn't work, database is still reset after each test. Is there an easy way to achieve this? Thanks in advance. -
Code coverage report with SonarQube for a Django Project in Jenkis?
I am unable to produce code coverage numbers in sonarqube for my existing project. Showing 0 Coverage Following setting in jenkins done: 1) I have kept coverage.xml in the project directory - github that reads on a build job in jenkins. 2) Have this put up: sonar.python.coverage.reportPath=coverage.xml, in additional properties in jenkins. Everthing is working well with jenkins and sonarqube, I am just unable to fetch code coverage in sonarqube's dashboards. -
why CSRF token is not found in Set-Cookie header field?
I have a Django Rest-framework APIView class which is as below: class HelloView(APIView): def get(self, request): clients = client.objects.all() serializer = ClientSerializerAPIView(clients, many=True) return Response(serializer.data) def post(self, request): serializer = ClientSerializerAPIView(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) when i send a get request by postman there is a csrf token in the cookie section of postman, but the problem is that there is no Set-Cookie field in the header file received for me to gram csrftoken from. -
Django-celery run group of tasks inside a task
I did not manage to run a tasks list inside a group inside a task itself started by a rest call. Here is what I'm trying to do, I removed useless stuffs: @api_view(['POST']) def run_some_tasks(request): runner = uuid.uuid4().hex #start tasks in background inside celery multiple_tasks.delay(request.data) #respond to rest api so the browser app does not wait return Response(dict(status = 'running', id = runner), status=status.HTTP_200_OK) @shared_task def task_one(args1, args2): time.sleep(10) @shared_task def multiple_tasks(args1): for action in ['action1', 'action2', 'action3']: job = group([task_one.s(action, 1), task_one.s(action, 2)]) job.apply_async() with allow_join_result(): # I use allow_join_result() to ignore the error about .get() inside tasks forbidden while not res.ready(): # wait for group finished before scheduling next group of action time.sleep(2) This code works but all task_one are run one by one while group should run it in parallel. But If call the multiple_tasks without .delay in run_some_tasks the tasks are run in parallel within the group as expected, but the Rest API call is blocked and that's not what I want. Any idea how I should handle this ? Maybe I'm having the wrong approach.. -
Django Clean architecture flow
Several days, I searched structure pattern for django. (exactly, django rest framework) And I found some interested article. Django Clean Architecture To refer it, I made structure. Below picture is current system's data flow. Flow User request to views views pass request object to interactor interactor convert request object to entity object and doing some business logic interactor pass entity object to repository repository convert entity object to model object and connect with database repository convert model to entity repository pass entity object to interactor interactor pass entity object to views views rendering data with entity to user So my question is, My flow is correct? All of business logic must inside of interactor. right? You know that, between interactor and repository, data come and go with entity. Is this because of hide exact method for each layer? Any feedback will be appreciated. -
Lambda Function unable to read file from s3
I've one Machine Learning algorithm which predicts value based on 'token' (i.e. short description text). Python code is working fine in Spyder but I want to trigger this .pkl file through API gateway in Lambda but every time I tried to trigger it shows me an error: An error occurred (404) when calling the HeadObject operation: Not Found: ClientError Traceback (most recent call last): File "/var/task/myfunction.py", line 17, in lambda_handler s3_client.download_file(bucket, key, download_path) File "/var/runtime/boto3/s3/inject.py", line 172, in download_file extra_args=ExtraArgs, callback=Callback) File "/var/runtime/boto3/s3/transfer.py", line An error occurred (404) when calling the HeadObject operation: Not Found: ClientError Traceback (most recent call last): File "/var/task/myfunction.py", line 17, in lambda_handler s3_client.download_file(bucket, key, download_path) -
Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser'
i have problem with my code when i want signup error appear Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' , i try solotion of other questions same like Manager isn't available; 'auth.User' has been swapped for 'members.CustomUser' but all of them asking to replace User = User = get_user_model() but i am not use any User in my code or i dont know where i used that.im new in django , python , js and etc so if my question is silly forgivme . for more information : i used Django Signup Tutorial for create signup method . first that was working well but after i expand my homework project i get error . model.py : from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): def __str__(self): return self.email class Meta: verbose_name = "member" verbose_name_plural = "members" setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'card.apps.CardConfig', 'members.apps.MembersConfig', 'search.apps.SearchConfig', 'products.apps.ProductsConfig', 'rest_framework', ] AUTH_USER_MODEL = 'members.CustomUser' admin.py: from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username'] admin.site.register(CustomUser, CustomUserAdmin) form.py: # users/forms.py from django.contrib.auth.forms import … -
how can i apply filter to django modelform and retun form to view in Django
i am trying t get user details in model form to create a service object.Instead of returning all users from my accounts app, i wanted to apply custom filter 'is_admin = False' in object filter but it returning users without applying filter. Help me to achieve this.... Forms.py code from django import forms from.models import Service from accounts.models import User class AddServiceForm(forms.ModelForm): class Meta: model = Service fields = ['service','title','manager','serviceMobile','alternateMobile', 'latitude','longitude','city','street','landmark','keywords'] def __init__(self, user, *args, **kwargs): super(AddServiceForm, self).__init__(*args, **kwargs) self.fields['manager'].queryset = User.objects.all().filter(is_admin=False) views.py code class AddService(LoginRequiredMixin, LogoutIfNotAdminMixin, CreateView): login_url = reverse_lazy('mlogin') permission_required = 'is_staff' def post(self, request, *args, **kwargs): context={} context['city'] = City.objects.all() if request.method == 'POST': form = AddServiceForm(request.POST) if form.is_valid: form.save() return redirect('servicedata') else: form = AddServiceForm() return render(request, 'aapp/locations/service/uservicedata.html', {'form': form, 'context': context}) -
DJANGO Complex querysets, that allows to calculate different filtered annotations
Hello there! Here the thing: i need to make 3 different queryes, from 1 model, but with different filter, and annotate a sums for further request.GET filterset. Models.py class Customer(models.Model): id = models.BigAutoField(primary_key=True, db_index=True) customer = models.CharField(max_length=300, blank=True, null=True, unique=True, verbose_name='name', db_index=True) comment = models.CharField(max_length=600, blank=True, null=True, verbose_name='name') class RList(models.Model): id = models.BigAutoField(primary_key=True, db_index=True) doc = models.CharField(max_length=20, blank=True, null=True, verbose_name='name', db_index=True) checked = models.BooleanField(default=False, verbose_name='name', db_index=True) date_doc = models.DateField(blank=True, null=True, verbose_name='name', db_index=True) date_fact = models.DateField(blank=True, null=True, verbose_name='name', db_index=True) project = models.ForeignKey(NktProject,blank=True, null=True, on_delete=models.PROTECT, to_field='proj_id', verbose_name='name', db_index=True) contract_id = models.ForeignKey(Contract,blank=True, null=True, on_delete=models.PROTECT, to_field='contract_id', verbose_name='name', db_index=True) customer = models.ForeignKey(Customer,blank=True, null=True, on_delete=models.PROTECT, related_name='Customer1', to_field='customer', verbose_name='name', db_index=True) #, to_field='customer' agent = models.ForeignKey(Customer,blank=True, null=True, on_delete=models.PROTECT, related_name='Customer2', to_field='customer', verbose_name='name', db_index=True) #, to_field='customer' move_from = models.ForeignKey(Logistic,blank=True, null=True, on_delete=models.PROTECT, related_name='Logistic1', to_field='destination', verbose_name='name', db_index=True) move_to = models.ForeignKey(Logistic,blank=True, null=True, on_delete=models.PROTECT, related_name='Logistic2', to_field='destination', verbose_name='name', db_index=True) stat = models.ForeignKey(Stat,blank=True, null=True, on_delete=models.PROTECT, to_field='stat_name', verbose_name='name', db_index=True) type = models.ForeignKey(NktType,blank=True, null=True, on_delete=models.PROTECT, to_field='nkt_type', verbose_name='name', db_index=True) size = models.ForeignKey(NktSize,blank=True, null=True, on_delete=models.PROTECT, to_field='nkt_size', verbose_name='name', db_index=True) str = models.ForeignKey(StrGr,blank=True, null=True, on_delete=models.PROTECT, to_field='str_gr', verbose_name='name', db_index=True) paint = models.ForeignKey(Paint,blank=True, null=True, on_delete=models.PROTECT, to_field='paint_name', verbose_name='name', db_index=True) amount_1 = models.DecimalField(max_digits=30, decimal_places=0, blank=False, null=False, default=0, verbose_name='name', db_index=True) amount_2 = models.DecimalField(max_digits=30, decimal_places=3, blank=False, null=False, default=0, verbose_name='name', db_index=True) amount_3 = models.DecimalField(max_digits=30, decimal_places=3, blank=False, null=False, default=0, verbose_name='name', … -
django-rest-framework ValueError: hour must be in 0..23
the code like this class StoreViewSet(viewsets.ModelViewSet): queryset = Member.objects.filter(memtype=2).select_related('store') serializer_class = MemberSerializer #paginator = None if set paginator = None then show ValueError enter image description here -
How to Check if Key Exists in a Queryset in Django
Given the queryset as follows: queryset = Department.objects.all() I would like to check whether a key exist. For example in the Department model has a field called name and I would like to check whether the key name exists from that queryset.