Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am sending POST request, but got error which says that get method is not allowed
I am sending POST request, but got this error: "detail": "Method \"GET\" not allowed." enter image description here enter image description here -
how to open a postgres database created with docker in a database client?
I have a question about how to open a database created with docker using https://github.com/cookiecutter/cookiecutter in a database client imagen1 imagen2 imagen3 -
django-autocomplete-light Remove Media (JS, CSS)
How can I remove all the media (JS & CSS files), which is added by django-autocomplete-light, from the form? I tried to override self.media in the form with None or even a list. I also tried to create a Media Class inside my Form, but this did not help either. The only thing that worked so far, was to remove the media directly from the source code of the library, but this isn't a appropriate solution. I know that the JS & CSS is needed. But my templates already provide all the necessary files. Form class LogEntryFilterForm(forms.Form): user = ModelChoiceField( queryset=PimUser.objects.all(), widget=autocomplete.ModelSelect2( url='accounts_autocomplete', attrs={ 'theme': 'bootstrap4', 'data-minimum-input-length': 2, } ) ) def __init__(self, *args, **kwargs): request = CrequestMiddleware.get_request() self.helper = FormHelper() self.helper.form_method = 'get' self.helper.form_action = '.' self.helper.form_class = 'form-filter-vertical form-bordered' self.helper.layout = self.__get_layout() super().__init__(*args, **kwargs) self.fields['ip'].widget.attrs['placeholder'] = request.META.get('REMOTE_ADDR') Media Output <link href="/static/vendor/select2/dist/css/select2.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/admin/css/autocomplete.css" type="text/css" media="screen" rel="stylesheet"> <link href="/static/autocomplete_light/select2.css" type="text/css" media="screen" rel="stylesheet"> <script type="text/javascript" src="/static/admin/js/vendor/jquery/jquery.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.init.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/select2.full.js"></script> <script type="text/javascript" src="/static/vendor/select2/dist/js/i18n/de.js"></script> <script type="text/javascript" src="/static/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/autocomplete_light/forward.js"></script> <script type="text/javascript" src="/static/autocomplete_light/select2.js"></script> <script type="text/javascript" src="/static/autocomplete_light/jquery.post-setup.js"></script> -
Django rest url routers on class based views
I would like to get the details of my submodules on a route with multiple parameters. My existing routes right now are: http://localhost:8000/api/module/ - Gets all modules http://localhost:8000/api/module/1/ - Gets all modules and connected submodules I would like to do http://localhost:8000/api/module/1/submodules/1 which will get the details of the submodules. How should i do this using class based views? Below is my existing code: Views.py class CourseModuleViewSet(viewsets.ModelViewSet): queryset = CourseModule.objects.all() serializer_class = CourseModuleSerializer def retrieve(self, request, pk=None): coursemodule = CourseModule.objects.get(id=pk) submodule = SubModule.objects.filter(submodule_module_id=pk) serializer = SubModuleSerializer(submodule, many=True) response = {'message': 'Sucess!', 'result': serializer.data} return Response(serializer.data, status=status.HTTP_200_OK) Serializers.py class CourseModuleSerializer(serializers.ModelSerializer): class Meta: model = CourseModule fields = ['class_id', 'coursemodule_title', 'coursemodule_date_created', 'coursemodule_last_modified', 'coursemodule_created_by'] class SubModuleSerializer(serializers.ModelSerializer): submodule_module_id = CourseModuleSerializer(many=False) class Meta: model = SubModule fields = ['submodule_module_id','submodule_title', 'submodule_date_created', 'submodule_last_modified', 'submodule_created_by'] urls.py router = routers.DefaultRouter() router.register('module', CourseModuleViewSet) urlpatterns = [ path('', include(router.urls)), ] -
How can I make my tags go to a new line whenever they go outside the div django-taggit
So for starters I am using django-taggit for a tagging system on my site. Everything was going well until I decided to try really long strings and many of them. It turns out it spills out of the div. I would like to know how can I make it go to a new line in the div whenever this happens, or even to limit the max characters allowed for each tag/limit the amount of tags allowed. Here is the relevant models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to='post_images',blank=True,null=True) file = models.FileField(upload_to='post_files',blank=True,null=True) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) comments_disabled = models.BooleanField(default=False) NSFW = models.BooleanField(default=False) spoiler = models.BooleanField(default=False) tags = TaggableManager() And here is the relevant HTML file {% for tag in post.tags.all %} <li class="tag-list-box"><a class="tag-list-style" href="{% url 'mainapp:tagged' tag.slug %}">{{ tag.name }}</a></li>&nbsp;&nbsp; {% empty %} <li>No tags</li> {% endfor %} So how would I go about breaking a line when the tags start spilling out of the div or even how to limit the actual number of allowed tags -
Nginx (proxy_pass) + Gunicorn can’t be reached
I want to run django with gunicorn and nginx as a proxy server on Ubuntu. The site works with djangos dev server: python manage.py runserver 0.0.0.0:8000 The site works with gunicorns server (even static files don't work): gunicorn my_project.wsgi --bind 0.0.0.0:8000 But with nginx on top I get the following error: This site can’t be reached ... refused to connect. ERR_CONNECTION_REFUSED Also both nginx log files error.log & access.log are empty. Here is how I configured nginx: server { listen 80; server_name my_ip_address; location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Scheme $scheme; } } In this case gunicorn runs with --bind 127.0.0.1:8001 of course. Status check (service nginx status) returns: ● nginx.service - A high performance web server and a reverse proxy server Active: active (running) since Fri 2019-09-20 07:41:00 UTC; 1min 19s ago Starting A high performance web server and a reverse proxy server... nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument Started A high performance web server and a reverse proxy server. -
Post filter on the basis of tags in django taggit(package)
I just installed django taggit by following official documentation. Every things work fine but when i click on the tags it doesn't filter post containing that tags here is my code. Code containing models.py file .............. from taggit.managers import TaggableManager .................. class Post(models.Model): STATUS_CHOICES = ((DRAFT, _('draft')), (PUBLISHED, _('published'))) author = models.ForeignKey(get_user_model(), verbose_name=_( "Author"), on_delete=models.CASCADE, related_name='blog_posts') title = models.CharField(_("Title"), max_length=200, unique=True) slug = models.SlugField(_("Slug"), unique_for_date='publish') status = models.IntegerField( _('status'), db_index=True, choices=STATUS_CHOICES, default=DRAFT) tags = TaggableManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("blog:post_detail", kwargs={ "pk": self.pk }) code contain views.py file from django.views.generic import ListView class PostListView(ListView): model = Post queryset = Post.published.all().order_by('-publish') context_object_name = 'post_list' template_name = "client/pages/blog_list.html" paginate_by = 7 urls.py file from .views import PostListView, .......... path('tag/<slug:tag_slug>/', PostListView.as_view(), name='post_list_by_tag'), .......... and in the templates file <ul class="tags-inline"> <li>Tags:</li> {% for tag in post_detail.tags.all %} <li> <a href="{% url 'blog:post_list_by_tag' tag.slug %}">{{ tag.name }}</a> , </li> {% endfor %} </ul> -
Django: Translation only works for some strings
I'm trying to translate my django project from English into German. It currently consists of two apps. The mainapp is translated correctly. The other app is fully translated in the django.po file but only a few translated strings will be shown and the other ones still remain in English. For compilation of my language files (one for each of the currently two apps) I always execute the following commands in the root directory of my project: django-admin makemessages -l de # Now doing some translations django-admin compilemessages When I change any translation string and execute makemessage and compilemessage, django will still use the old translation and not the new one. So it looks like it worked some time ago but not something is going wrong with compiling/using the translations. In this template for example the "Log in" and the "Sign up" string are translated correctly, but the "Need an account?" string is not because it was added when the translations didn't work anymore. But unfortunately I have no idea what changed and why it's not working anymore. {% extends "mainapp/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} … -
I'm trying to update nested serializer it's giving me an error paper_description with this id already exists?
Django Rest Framework inserting and updating writable nested serializer I trying to insert and update a writable nested serializer with Django Rest Framework, following examples like this. But it doesn't work. What could I having doing wrong? Controller class JobCardViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = JobCardSerializer http_method_names = ('get', 'post', 'put', 'patch') def get_queryset(self): if 'key' in self.request.GET: key = self.request.GET['key'] return JobCard.objects.filter(models.Q(job_order_no__icontains=key) | models.Q(job_name__icontains=key)) if 'party' in self.request.GET: return JobCard.objects.filter(party_name__name__icontains=self.request.GET['party']) else: return JobCard.objects.all() def create(self, request, *args, **kwargs): self.serializer_class = JobCardPostSerializer return super(JobCardViewSet, self).create(request, *args, **kwargs) def update(self, request, *args, **kwargs): self.serializer_class = JobCardPostSerializer return super(JobCardViewSet, self).update(request, *args, **kwargs) Serializer My serializer class PaperDescriptionPostSerializer(ModelSerializer): class Meta: model = PaperDescription fields = '__all__' class JobCardPostSerializer(ModelSerializer): paper_description = PaperDescriptionPostSerializer(many=True) class Meta: model = JobCard fields = '__all__' def create(self, validated_data): paper_description_list = validated_data.pop('paper_description') job_card = JobCard.objects.create(**validated_data) for paper in paper_description_list: paper.update({"party_name": job_card.party_name}) paper.update({"job_order_no": job_card.job_order_no}) paper.update({"job_name": job_card.job_name}) paper.update({"job_date": job_card.job_date}) paper.update({"job_type": job_card.job_type}) job_card.paper_description.add(PaperDescription.objects.create(**paper)) return job_card def update(self, instance, validated_data): paper_description = validated_data.pop('paper_description') instance.job_name = validated_data.get("job_name", instance.job_name) instance.job_date = validated_data.get("job_date", instance.job_date) instance.delivery_date = validated_data.get("delivery_date", instance.delivery_date) instance.job_created_by = validated_data.get("job_created_by", instance.job_created_by) instance.die_no = validated_data.get("die_no", instance.die_no) instance.job_re_print = validated_data.get("job_re_print", instance.job_re_print) instance.remarks = validated_data.get("remarks", instance.remarks) instance.update_reason = validated_data.get("update_reason", instance.update_reason) instance.job_details = validated_data.get("job_details", instance.job_details) instance.party_name = … -
How to post an image with other data in the json file using angularjs form
I'm trying to create multiple form under tabs with previous tab data been used in the next tab and each form has a save button which saves the data for the next tab using angularjs. Everything is working fine with code. All of the form data is added to single field in the model which is a JSONField. Except I have a form which has a file field usually images I am stuck with the upload of these images to the json field. var app = angular.module('app', []); app.controller('enviromentController', function ($scope, $http) { $scope.saveEnvironment = function () { $http({ method: 'PUT', "url": "{% url 'core:api:edit-environement' env_id=env_id %}", "data": angular.copy($scope.env), "headers": { "accept": "application/json", "content-type": "application/json", "Authorization": "Token " + localStorage.getItem('token') } }).then(function () { inform("Saved", "Published data"); }); this is my form <div class="tab-content" id="myTabContent" style="min-height:375px"> <div class="tab-pane active" id="environment" role="tabpanel" aria-labelledby="environment-tab"> <div class="form-group col-lg-5"> <label class="form-control-label">Title </label> <input type="text" class="form-control" ng-model="env.title" required /> </div> <div class="form-group col-lg-5"> <label class="form-control-label">Department</label> <select class="form-control" ng-model="env.department" ng-options="c.id as c.name for c in departments" required> </select> </div> <div class="form-group col-lg-5"> <label class="form-control-label" for="appname">App Name</label> <select class="form-control" ng-model="env.app_name" ng-options="c.id as c.name for c in app_name" required> </select> </div> </div> <div class="tab-pane" id="room" role="tabpanel" aria-labelledby="room-tab"> <div … -
DRF serializer field renamed to it's source in validated data
I have a drf serializer with a field I would like to rename: class UserBulkUploadSerializer(serializers.Serializer): ... is_admin = serializers.BooleanField(required=False, source='administrator') However, in validated_data attribute it's got renamed back to the source attribute value. I'm doing this: serializer = UserBulkUploadSerializer(data=data) serializer.is_valid() return serializer.validated_data And there's no is_admin key in there, it's administrator. Is there a way to overcome this and make it is_admin in validated_data? -
How do i make many to many field as a chekbox items in template.?
I have 3 models one is Category(Fields = category_name) and another one is SubSategory(Fields = category(ForeignKey to Category),sub_category).and another model is DummyModel. # Model class DummyModel(models.Model): name = models.CharField(max_length=20) email = models.EmailField() category = models.ManyToManyField(Category) sub_category = models.ManyToManyField(SubCategory) This is my view #view class StartProjectView(View): template_name = 'start-project.html' def get(self, request): form = StartProjectForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = StartProjectForm(request.POST) if form.is_valid(): form.save() form = StartProjectForm() return render(request, self.template_name, {'form':form}) return HttpResponse("<h2>Done</h2>") This is my Template # Template <form method="post"> {% csrf_token %} <p>name: <input type="text" name="name"></p> <p>Email: <input type="text" name="email"></p> {% for form in form %} <input type="checkbox" name="category">{{ form.category }} {% endfor %} <br> {% for form in form %} <input type="checkbox" name="sub_category">{{ form.sub_category }} {% endfor %} <button type="submit">Start Now</button> </form> I want category and subcategory in my template as checkbox items. How do I do that.? -
Browser shows variable refered before assign
I am new to python and hardly tried to figure out the problem of usese of variable from another if statement in the same function here is my code: def post(self, request, **kwargs): selected_membership_type = request.POST.get('membership_type') user_membership = get_user_membership(request) user_subscription = get_user_subscription(request) selected_membership_qs = Membership.objects.filter( membership_type=selected_membership_type) if selected_membership_qs.exists(): selected_membership = selected_membership_qs.first() ''' ========== VALIDATION ========== ''' # selected_membership = selected_membership_qs.first() if user_membership.membership == selected_membership: if user_subscription == None: messages.info(request,"You already have this membership.Your \ next payment is due {}".format('get this value from stripe')) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Fetching Child Category Objects django python
I am trying to get child listing with category . serializers.py: class ChildSerializer(serializers.HyperlinkedModelSerializer): category_id = serializers.PrimaryKeyRelatedField(queryset = Category.objects.all(), source = 'category.id') class Meta: model = SubCategory fields = ('url','id', 'sub_category_name', 'category_id') def create(self, validate_data): #subject = SubCategory.objects.create subject = SubCategory.objects.create(Category=validated_data['category']['id'], sub_category_name=validated_data['sub_category_name']) return SubCategory class CategorySerializers(serializers.ModelSerializer): children = ChildSerializer(many=True, read_only=True) class Meta: model = Category fields = ('id','name','slug','children') views.py: class CategoryView(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = serializers.CategorySerializers this is the api output: { "id": 30, "name": "akera", "slug": "akera", "children": [] }, { "id": 31, "name": "sda", "slug": "sd", "children": [] }, { "id": 6, "name": "Technology", "slug": "12", "children": [ 29, 30, 31 ] }, { "id": 7, "name": "Festival", "slug": "12", "children": [] }, currently its getting only category id of subcategory i want to fetch the subcategory name and id with category................................................... -
python django web application issue - windows 10 issue
I using window 10 pro and when I learning python - web application pip install django django-admin startproject mysite cd mysite py manage.py runserver This is issue, pls help me enter image description here -
How to dynamically add field in django form?
Suppose i made a form with fields name and email id and then i execute the code and page opens with the fields - name and email id and then i want to add contact field to that form without going back to add that contact field to models and form and without doing migrations. Can this is possible in django? -
Using Django or JS to turn on camera and scan QR-code
I am now working on a project that can scan QR-code which contains ID of a good. Is there any method that I can have my website to switch on iPhone camera for scanning? Please give me some information about this or link. -
Why doesn't djangorestframework template load on heroku?
I have a Django app meant to host a backend API using djangorestframework. Everything works fine save that the drf template refuses to load in production. The screenshot below is what I get no matter how many times I run python manage.py collectstatic. The app url is https://ethodoxy.herokuapp.com/api/v1/ -
Trigger an email to admin when new user registers in a Django app
I'd like to trigger a simple plaintext email to admin(s) when a new user registers for my Django app. What's the cleanest way to do this? -
Email sending CronJobs not working in Django
This is very little issue. My email sending cronjobs is not working from django_cron import CronJobBase, Schedule class MyCronJob(CronJobBase): RUN_EVERY_MINS = 1 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'my_app.my_cron_job' def do(self): email = EmailMessage('hi', 'message', to=['test@gmail.com']) email.send() please tell me what is wrong with this code or what are the alternates I can use? -
How to render context values in generic list and detail views
I have a base template file (shared.html) contains Header and Footer, using on every page. I have some dynamic values from database in shared.html (e.g: Phone number, address, logos) and showing perfectly on index view page, but not showing on any of the generic views page. Please guide me how to do this to show all the dynamic values on every generic view page. Index view: def index(request): # Display all the Dynamic values form models num = TopBar.objects.get() addressISD = AddressIslamabad.objects.all() addressRWP = AddressRawalpindi.objects.all() alt = Logo.objects.all() YLP7Text = WhyLP7Text.objects.all() PMBG = BGimages.objects.all() lp7Features = LP7features.objects.all() locate = Locations.objects.all() events = Events.objects.all() memberLogo = LP7MembersLogo.objects.all() testi = LP7Testimonials.objects.all() promo = Promotions.objects.all() c = context = ({ 'topBarNumber': num, 'addressISD': addressISD, 'addressRWP': addressRWP, 'altText': alt, 'YLP7Text': YLP7Text, 'BG': PMBG, 'featuresLP7': lp7Features, 'LC': locate, 'evt': events, 'memLogo': memberLogo, 'testi': testi, 'promo': promo }) # Render the HTML template index.html return render(request, 'index.html', c ) Generic View: # Display the detail and generic views class EventListView(generic.ListView): model = Events class EventDetailView(generic.DetailView): model = Events class PromotionListView(generic.ListView): model = Promotions class PromotionDetailView(generic.DetailView): model = Promotions -
Should Important Metric be tracked in separate BooleanField, or is a CharField enough?
I want to track stats on messages in my application. An important metric is "initial message" as this means a new conversation started. Is it better to have the initial message as a separate BooleanField, or is it enough to have "initial message" being tracked as a string in the message category CharField. Please specify whether you recommend Model A, Model B, or another approach, and why. I want to use this model to power charts that I show in the user dashboard of my application. # Model A class Data(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) message = models.CharField(max_length=20) message_channel= models.CharField(max_length=20) #Facebook, Twitter, SMS message_category = models.CharField(max_length=20) #initial message, reply, feedback_reply initial_message = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) # Model B class Data(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) message = models.CharField(max_length=20) message_channel= models.CharField(max_length=20) #Facebook, Twitter, SMS message_category = models.CharField(max_length=20) #initial message, reply, feedback reply created_at = models.DateTimeField(auto_now_add=True) -
How to combine queryset via ManyToManyField in django
I'm trying to build an Instagram clone. I need to pass user's posts and follow's to the dashboard. I don't know how to combine a user with follow which is manytomanyfield of the user because ordering posts by created_at models.py class Insta(models.Model): title = models.CharField(max_length=255) body = models.TextField() image = models.ImageField(upload_to='images/', blank=True) video = models.FileField(upload_to='videos/', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='likes', blank=True, default='') owner = models.ForeignKey(User, on_delete=models.CASCADE) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=100, unique=True) user_fullname = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) thumbnail = models.ImageField(upload_to='thumbnail/') follows = models.ManyToManyField('self', related_name='followers', symmetrical=False) views.py def list(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('insta:signup') else: user = request.user response = Insta.objects.filter(owner=user.id) return Response({'posts': response, 'user': user}) Thank you in advance. -
User group is not creating?
Here I made a form for taking the group name from the user and then tried to create group name with that name entered by user but it is not giving me the expected result.It is neither throwing any error nor saving the data in the database. When i used group_name = request.POST['name'] instead of cleaned_data it throws: django.utils.datastructures.MultiValueDictKeyError: 'name' What I am doing wrong here ? forms.py class AddUserGroupForm(forms.Form): name = forms.CharField(max_length=255) views.py def add_user_groups(request): form = AddUserGroupForm() #group_name = request.POST['name'] #print(group_name,'group_name') if form.is_valid(): group_name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') new_group = Group.objects.create(name=group_name) new_group.permissions.add(permissions) messages.success(request,'New group added.') return redirect('organization:view_groups') return render(request,'organization/add_user_groups.html',{'user_permissions':user_permissions,'form':form}) template <form action="{% url 'organization:add_user_group' %}" method="post"> {% csrf_token %} <label> Group Name : </label> <input type="text" class="form-control required" placeholder="Enter group name" name="name"> <label>Permissions:</label> {% for permission in user_permissions %} <input name="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}"> <label for="permission-{{permission.id}}"> {{permission.name}}</label> </div> {% endfor %} <button type="submit" class="btn btn-info">Submit</button> </div> </form> -
Is possible to get media_id from Instagram url?
I have an Instagram url: https://www.instagram.com/p/B2EtjT9hgvG/ and I need to obtain media_id of this url; something like: 1238578393243739028_1408429375 There is a way?