Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to make Follow button dynamic. Follow, Unfollow feature addition
If we click, follow button it should update followers then show unfollow and if clicked again it should show follow, decrementing followers. urls.py urlpatterns = [ path('',views.index, name = 'index'), path('signup',views.signup, name = 'signup'), path('signin',views.signin, name = 'signin'), path('logout',views.logout, name = 'logout'), path('settings',views.settings, name = 'settings'), path('profile/<str:pk>',views.profile, name = 'profile'), path('like-post',views.like_post, name = 'like-post'), path('upload',views.upload, name = 'upload'), path('follow',views.follow, name = 'follow'), ] profile.html <span style="color: white; font-size: 27px;"><b>{{user_followers}} followers</b></span> <span style="color: white; font-size: 27px;"><b>{{user_following}} following</b></span> <input type="hidden" value="{{user.username}}" name="follower"> <input type="hidden" value="{{user_objects.username}}" name="user"> {% if user_object.username == user.username%} <a href = "/settings" data-ripple="">Account Settings</a> {% else %} <a data-ripple="">{{button_text}}</a> {% endif %} views.py @login_required(login_url='signin') def profile(request, pk): user_object = User.objects.get(username=pk) user_profile = Profile.objects.get(user=user_object) user_posts = Post.objects.filter(user=pk) user_post_length = len(user_posts) follower = request.user.username user=pk if FollowersCount.objects.filter(follower = follower, user = user).first(): button_text = 'Unfollow' else: button_text = 'Follow' user_followers = len(FollowersCount.objects.filter(user=pk)) user_following = len(FollowersCount.objects.filter(follower=pk)) context = { 'user_object': user_object, 'user_profile': user_profile, 'user_posts':user_posts, 'user_post_length':user_post_length, 'button_text': button_text, 'user_followers': user_followers, 'user_following': user_following } return render(request, 'profile.html', context) models.py class FollowersCount(models.Model): follower = models.CharField(max_length=100) user = models.CharField(max_length=100) def __str__(self): return self.user admin.py from django.contrib import admin from .models import Profile, Post, LikePost, FollowersCount # Register your models here. admin.site.register(Profile) admin.site.register(Post) admin.site.register(LikePost) admin.site.register(FollowersCount) I have … -
(Many to one relation) not forwarding sub-fields of child object when creating parent object
I am creating a Project object, with a milestone child object as a field of project, using ForeignKey and nested-serializers. first i wrote the test for creating milestone(s) on creating a new project : PROJECTS_URL = reverse('project:project-list') def test_create_project_with_new_milestones(self): """Test creating project with milestones""" payload = { 'title': 'Test', 'time_hours': 10, 'milestones': [ { 'title': 'FirstMilestone', 'hierarchycal_order': 1, 'order': 1 }, { 'title': 'FirstMilestoneSub', 'hierarchycal_order': 1, 'order': 2 }, { 'title': 'SecondMilestone', 'hierarchycal_order': 2, 'order': 1 }, ], } res = self.client.post(PROJECTS_URL, payload, format='json') """ ... + rest of the test ...""" Then updated serializers.py adding function to create milestones and updating the create function adding creation of milestones in a similar way as i did for tags(working for tags but tags is many to many relation ship and has only a name field): class ProjectSerializer(serializers.ModelSerializer): """Serializer for projects""" tags = TagSerializer(many=True, required=False) milestones = MilestoneSerializer(many=True, required=False) class Meta: model = Project fields = ['id', 'title', 'time_hours', 'link', 'tags', 'milestones'] read_only_fields = ['id'] ... def _create_milestones(self, milestones, project): """Handle creating milestones as needed.""" auth_user = self.context['request'].user for milestone in milestones: milestone_obj, created = Milestone.objects.create( user=auth_user, project=project, **milestone, ) project.milestones.add(milestone_obj) def create(self, validated_data): """Create a project.""" tags = validated_data.pop('tags', []) milestones … -
The view "../{api}" didn't return an HttpResponse object. It returned None instead. Unable to make api fetch request due to following error?:
I have a views.py containing an api. I am calling a function that does a fetch request. I get an error relating to my code not returning a specific object type. Setup: vuejs frontend, django backend Function in methods: add_auction_item(){ console.log('testing..'); if (this.item_name.length > 0){ var auc_item = { 'item_name': this.item_name, 'item_condition': this.item_condition, 'posted_by': this.posted_by, 'created_at': this.created_at }; this.auction_items.unshift(auc_item) fetch('/add_auction_item_api/', { method:'POST', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRFToken':'{{ csrf_token }}', 'Content-Type':'application/json' }, body: JSON.stringify(auc_item) }) } Api in views.py: @login_required @csrf_exempt def add_auction_item_api(request): if request.method=='POST': data = json.loads(request.body) item_nme = data['item_name'] item_cond = data['item_condition'] item_pstd_by = data['posted_by'] Item.objects.create(item_name=item_nme, item_condition=item_cond,posted_by=item_pstd_by) return JsonResponse({'new':'updated'}) -
How can I access Django model fields in form via JavaScript to auto calculate fa ield?
I would like to auto-calculate my deposit amount height in a form. Therefore, I included JavaScript to make it happen. The idea: After entering the net into the form, the suitable deposit height will be displayed in the amount field. And there is nothing to do for the user here. I really appreciate any suggestions since I am total beginner with Django. I tried to access the field via known methods like netObj.fishing_type and ['fishing_type'] but I feel like this is not the issue. Somehow I can't access the model fields of the triggered record. html file {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content%} <p> </p> <div class ="form-group"> <form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data"> {% csrf_token %} {{form|crispy}} <script> // Get the input elements by targeting their id: const net_input = document.getElementById('id_net'); const vessel_input = document.getElementById('id_vessel'); const amount = document.getElementById('id_amount'); // Create variables for what the user inputs, and the output: let netObj = 0; let vesselObj = 0; let height = 0; // Add an event listener to 'listen' to what the user types into the inputs: net_input.addEventListener('input', e => { netObj = e.target.value; console.log(netObj); updateAmount() }); // Update the value of net … -
How to test file upload in pytest?
How to serializer a file object while using json.dumps ? I 'm using pytest for testing file upload in django and I 've this function def test_file_upload(self): # file_content is a bytest object request = client.patch( "/fake-url/", json.dumps({"file" : file_content}), content_type="application/json", ) I 've tried to set the file_content as a bytes object but I 'm getting this error TypeError: Object of type bytes is not JSON serializable I need to send the whole file to my endpoint as json serialized -
How to rollback changes if error into chain celery django task?
The scheme is: chain(group | result_task). How can I rollback changes in database if error? Is it possible to use database transactions in this situation? -
my static folder where I place my js ans css files is not at the root of my django project. How to call these satic files in the template?
Here is the configuration of my static_root variable: STATIC_ROOT = [os.path.join(BASE_DIR,'vol/web/static')] My templates are at the root of the project. TEMPLATES={ ... 'DIRS':[os.path.join(BASE_DIR, 'templates')], ... } This is how I call my bootstrap.min.css file in a project template: <link rel="stylesheet" href="{% static 'assets/plugins/bootstrap/css/bootstrap.min.css' %}"> But it doesn't work because the file is not loaded. What's the right way to do it? -
Receiving an Operation Error when accessing Django Admin page
While in the admin page of my django project, I get an error relating to an ID having no column. Method type is GET. The error I get is: OperationalError at /admin/../item/ no such column: app_item.written_by_id So I attempt to create for the column it does not have and I get an error about the two clashing. So what exactly should I do to resolve this as I am merely trying to access a subheading in my admin page? class Item(models.Model): written by = models.ForeignKey(CustomUser, on_delete=models.CASCADE) # written_by_id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) -
Sending a variable to a Django backend for processing
I am working on a payment processing script. The front end is a javascript module and the backend is a Django app. I seem to be missing something with my code and I can't pinpoint it. Here are the parts of the app: {% extends 'dash.html' %} {% load static %} {% block 'title' %} Subscription | Simpledocs {% endblock %} {% block extra_title %}<h2>Subscription</h2>{% endblock %} {% block paymentInfo %} {% endblock %} {% block content %} <div class="columns is-centered"> <div class="column is-5 box"> {% if company.paid_till < today %} <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="content"> <h1 class="title is-4"> <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Account is not active </h1> Your company <strong>{{user_organization.organization}}</strong> is not active. Please renew the subscription.<br> </div> {% else %} <p class="label">We have great subcription options for you. Choose from our list either for monthly or annual plans</p><br> {% endif %} <h2>Subscription Packages</h2><br> <div class="select"> <select name="search" onchange="updateButtonDataAmount(event)" > <option value="select-a-plan">Select A Plan</option> <option value="7.99">Starter - Monthly ($7.99/Month)</option> <option value="79.00">Starter - Annually ($79.00/Year)</option> <option value="49.00">Business - Monthly ($49.90/Month)</option> <option value="499.00">Business - Annually ($499.00/Year)</option> </select> </form> </div><br><br> <div id="searched-subs"></div><br><br> <button class="intaSendPayButton button is-btn-mycolor is-fullwidth" data-amount="10" data-currency="KES" data-email="joe@doe.com" data-first_name="JOE" data-last_name="DOE" data-country="KE"> Pay Now </button><br> </div> </div> … -
Django Ordering by a specific ManyToMany Field
the following structure is given: `python class MovieTranslation: lang=CharField() title=CharField() class Movie: key = CharField() movie_translations = ManyToManyField(MovieTranslation) ` Now for example, for english users I want to sort by the english MovieTranslation of a Movie? I want to use it in a ViewSet as a Filterset class. I think it should be something like order_by(movie_translations__name='en'__title). The last part of course doesn't work. I found solutions, for filtering before, but I do not think filtering for english Translations work, since then I get a list of Movie Objects who have an english Title, but could still have other languages. I want to sort specifically by the field of a manytomany field. So is there a way to order by a specific ManyToMany Instance (i.e. all MovieTranslations where the name is 'en' ) ? I was thinking about annotate, but had the same problems I am thinking now that maybe joining with a specific ManyToMany field could work. -
Show the total value of an order using django shopping cart
in my e-commerce project. Here I am using the django shopping cart module. I would like to display the order total at the bottom, i.e. the sum of the prices. Example output: name quantity Price Price Total chocolat 2 150 300 milk 1 500 500 Total commande 800 How to get the Order Total line? command.html {% for key,value in request.session.cart.items %} <tr> <td>{{value.name}}</td> <td>{{value.quantity}}</td> <td>{{value.price}}</td> <td>{{value.price|multiply:value.quantity}}</td> <td> Total commande : ??????? </td> </tr> {% endfor %} -
How to test(TDD) for django icontains
views.py def SearchResult(request): search_post = request.GET.get('search/') if search_post: conts = Content.objects.filter(Q(content_meta__icontains=search_post) & Q(content_meta__icontains=search_post)& Q(tags__icontains=search_post)) else: conts = Content.objects.all().order_by() return conts test.py class SearchResult(TestCase): def test(self): response = request.get('search/?q=pdf') #response.status_code == 500 print(response) ret = getattr(SearchResult, response) response = SearchResult(response) assert response.status_code == 500 How to write TDD for above code, so that it will hit views.py line. I know its bad, to ask for tdd after writing code, so sorry. -
post_generation hook won't be called while using FactoryBoy for ManyToManyField generation
I have model Product: class Product(models.Model): .. category = TreeManyToManyField(Category) ... def __str__(self): return self.name As you see, I have a many to many relation to Category. The following model: Category: class Category(MPTTModel): ... parent = TreeForeignKey( "self", on_delete=models.PROTECT, related_name="children", null=True, blank=True, verbose_name=_("parent of category"), help_text=_("format: not required"), ) ... to generate the category field using FactoryBoy i did the following: class ProductFactory(factory.django.DjangoModelFactory): class Meta: model = models.Product slug = faker.lexify(text="prod_slug_??????") name = faker.lexify(text="prod_name_??????") @factory.post_generation def category(self, create, extracted, **kwargs): if not create: return if extracted: for cat in extracted: self.category.add(cat) and my test is: @pytest.mark.dbfixture def test_inventory_db_product_insert_data( db, product_factory, ): new_product = product_factory.create(category=(1, 2, 3, 4, 5, 6)) ... But I get the following error: TypeError: Direct assignment to the forward side of a many-to-many set i s prohibited. Use category.set() instead. What's wrong with it? -
How to solve an ImportError: Module "django.middleware.csrf" does not define a "Cs‚rfViewMiddleware" attribute/class
I am working on a django project. After I successfully did the registration and login form, I have logged into the admin panel and shortly after that somehow I got this error: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django_filters', 'startup', 'vereinsapp', 'users', #'users.apps.UsersConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.Cs‚rfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'startup.wsgi.application' LOGIN_REDIRECT_URL = '/' Anyone know what I could try to fix it? I also tried deleting the apps.py file of 'users'. That is the structure of my project: -
localhost:8000 not accessible using physical IP
I'm trying to access my server on localhost:8000 from my LAN network using my physical IP address: 192.168.1.5:8000 but it's saying 192.168.1.5 refused to connect. The django server has already ALLOWED_HOSTS = ['*'] And the IP is correct (got it from ipconfig) My network is set on Private on both computers by the way I can't access that from my own computer too. I'm not using a VPN The firewalls are all disabled. I even allowed the port 8000 using the rule in Inbound rules. I tried this but didn't work netsh advfirewall firewall add rule name="TCP Port 8000" dir=in localport=8000 protocol=TCP action=allow I'm out of ideas, I'm confused. I used to do it before, I'm not a begginer. -
How do I view objects per Foreign Key in one HTML (Django)?
I am using Django Framework and creating a notification. I would like to create a notification that can filter by id of the foreign key. But when i tried it, i got all the results, i am not sure how to filter by id so that per id I can view the flow of the incidents. View def user_reports(request): profile = get_object_or_404(UserProfile, user=request.user) incidentReports = IncidentGeneral.objects.all().order_by('-updated_at') # incident_general = IncidentGeneral.objects.filter(pk=request.id) notifications = Notification.objects.all().order_by('-date') paginator = Paginator(incidentReports, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if request.method == 'POST': for i in incidentReports: x = request.POST.get(str(i.id)) print(x) if str(x) == 'on': b = IncidentGeneral.objects.get(id=i.id) b.soft_delete() # b.is_deleted = True # b.deleted_at = timezone.now() messages.success(request, 'User Report successfully deleted') context = { 'profile': profile, 'incidentReports': page_obj, 'notifications': notifications, # 'IncidentGeneral': IncidentGeneral } return render(request, 'pages/user_report.html', context) Model - Notification class Notification(models.Model): TYPES = ((1, 'Reports'), (2, 'User Accounts'), (3, 'Inbox'), (4, 'Attributes Builder')) incident_report = models.ForeignKey('incidentreport.IncidentGeneral', on_delete=models.CASCADE, blank=True, null=True) sender = models.ForeignKey('accounts.User', on_delete=models.CASCADE, blank=True, null=True, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_user") notification_type = models.IntegerField(choices=TYPES) remarks = models.CharField(max_length=90, blank=True) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) Model - IncidentGeneral class IncidentGeneral(SoftDeleteModel): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS … -
import model from another project Django
I have two Django projects Those projects use same database.Project1 needs import from one for the Project2's views. They are models in each project which is usable by both projects. How can I import the model views both ? iam using virtual env -
GuardTek API - Refernce Issue
I am using GuardTek APIs which are in SOUP. I am using their Docs but I am having issues understanding them. https://s3.guardtek.net/Report/WebServices/SettingsService.asmx I want to use https://s3.guardtek.net/Report/WebServices/SettingsService.asmx?op=GetShiftDetails GetShiftInfo API but I am unable to understand what is meant by Reference and where I can find it . Below is my code. url = "https://s3.guardtek.net/Report/WebServices/SettingsService.asmx" payload = """ <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetShiftDetails xmlns="http://www.alphasystem.fr/WebServices/GuardTek/Settings"> <apiKey>XXX-XXX-XXX</apiKey> <startDateUtc>1670232908</startDateUtc> <endDateUtc>1670243708</endDateUtc> <includeBreakList>false</includeBreakList> <userReference>salman</userReference> <guardroomReference>NADEEM Muhammad</guardroomReference> <shiftReference>salman</shiftReference> </GetShiftDetails> </soap:Body> </soap:Envelope> """ headers = { 'Content-Type': 'text/xml; charset=utf-8' } response = requests.request("POST", url, headers=headers, data=payload) In Response I am getting this . An empty data. <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetShiftDetailsResponse xmlns="http://www.alphasystem.fr/WebServices/GuardTek/Settings" /></soap:Body></soap:Envelope> I want to know What is meant by reference here and how can I find it I have tried giving fake names in reference parameters and getting 200 response. But data is empty. -
With start_time and end_time in Django models, how to print a series of times in an html page
My model is: DAYS_OF_WEEK = ( (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday'), ) class Teacher(models.Model): name = models.CharField(max_length=64) start_time = models.TimeField(blank=False) end_time = models.TimeField(blank=False) day = models.IntegerField(choices=DAYS_OF_WEEK) One instance would be like: Sally 17:00 18:00 0 I want to output an HTML page using start_time and end_time in an 15-minute interval, something like this: Sally 17:00 17:15 17:30 17:45 18:00 -
How to restrict AuthenticateCallbackView in django-microsoft-auth only to registered accounts?
I am using django-microsoft-auth in my Django project. I am trying to restrict this option only to registered users so only people who have already registered themselves are allowed to use Log in with Microsoft button. I found in AuthenticateCallbackView method called _authenticate. Code below: def _authenticate(self, code): if "error" not in self.context["message"]: if code is None: self.context["message"] = {"error": "missing_code"} else: # authenticate user using Microsoft code user = authenticate(self.request, code=code) if user is None: # this should not fail at this point except for network # error while retrieving profile or database error # adding new user self.context["message"] = {"error": "login_failed"} else: login(self.request, user) I am wondering how can I restrict authentication only to those who have accounts. In case someone doesn't have an account it would send a message: Please register your account first. -
django how to fetch upload folder path
I know how to upload multiple files through Django, but I have a problem when uploading a folder if there are subfolders in it. So I want the user to upload the folder and I get the root, dirs, and files of that folder the user upload. HTML code: <input type="file" name="file_name" multiple = "true" webkitdirectory="true" directory = "true"/> python code: def uploader_folder(request): data = {} if request.method == 'POST': file = request.FILES.getlist('file_name') for i in file: print(i) and here I received only file names. but I want to know the dir, or root path also -
Unable to submit the regitrations form in django
enter image description here while clicking register, the details not saving to database and the page is not redirected to the index page. views.py from django.shortcuts import render,redirect from django.views.generic import View from Angram.forms import RegistrationForm # Create your views here. class IndexView(View): def get(self,request,*args,**kwargs): return render(request,"index.html") class RegistrationView(View): def get(self,request,*args,**kwargs): form=RegistrationForm() return render(request,"register.html",{"form":form}) def post(self,request,*args,**kwargs): form=RegistrationForm(request.POST) if form.is_valid(): User.objects.create_user(**form.cleaned_data) return redirect("index-main") else: return render(request,"register.html",{"form":form}) forms.py from django import forms from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): class Meta: model=User fields=["first_name","last_name","username","email","password"] urls.py from django.contrib import admin from django.urls import path from Angram import views urlpatterns = [ path('admin/', admin.site.urls), path("index/",views.IndexView.as_view(),name="index-main"), path("accounts/register/",views.RegistrationView.as_view(),name="signup"), ] -
Django Send Email ( Add logo on mail)
I would like to send an email in Django by add the logo of the website I am sending from something the user will know that this mail is coming from me just like LinkedIn or any platform where you see the company logo before clicking on the mai Example -
Allow Celery Worker to consumes messages from non task queue
I have a django backend which is running Celery for distributed tasks. I have created a Service bus queue which stores temperature data coming from hundred of frontend devices. I am running Celery periodic task every 5 seconds to consume those messages. But the problem is the tasks will be scheduled even if there are no messages in the TEMPERATURE queue. Is there a way I can set up a Celery worker that can listen to the this queue and operate on it when there is a new task available? Keep in mind this queue is not a tasks queue. -
How to pass params using fetch API in vuejs vuex store action
I am trying to pass a dict using fetch API to django views but unable to get it in request dict of views. I have tried below steps fetch(`/api/getnames`, [{'a': name, 'b': name}]) .then() .catch((err) => { console.log('Fetch Error :-S', err); }); def getnames(request): print(request.__dict__) I am trying to get the dict passed in params while calling the url but dict is not present. Kindly suggest a solution to resolve this issue.