Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework request as parameter
I'm learning Django rest Framework. I know how to use Class Based Views. Why methods GET, PUT, DELETE, ETC needs the "request" parameter even if the object itself contains the same request attribute? For example, in this code: class ArticleDetailViewAPIView(APIView): def get_object(self, pk): object = get_object_or_404(Article, pk=pk) return object def get(self, request, pk): object = self.get_object(pk=pk) serializer = SerializerArticle(object) return Response(serializer.data) For example, if in the get method I put the line: print("Equal: ", self.request is request) In the console, the output is TRUE -
Django form won't submit
I got a user-based dropdown working but now the form does not submit. here are my files MODEL.PY user= models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) FORMS.PY class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ('name', ) def __init__(self, user, *args, **kwargs): self.user = user super(MyForm, self).__init__(*args, **kwargs) self.fields['name'].queryset = OtherModel.objects.filter(user=self.user) VIEWS.PY class MyView(CreateView): model = MyModel form_class = MyFrom template_name = 'users/form.html' success_url = reverse_lazy('index') def get_form_kwargs(self): kwargs = {'user' : self.request.user , } return kwargs NOTE: Without the def get_form_kwargs(self): in the views, the form filter grabs everything but with it does not submit. What I'm I missing? -
How do i get a nested field to be read_only in modelserializer?
currently when i send a get request i get what i want. But when i do a Post it throws an error saying {"user": ["This field is required."]} even though i put 'user' in read_only_fields. heres the code: serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email'] class SaleHistorySerializier(serializers.ModelSerializer): user = UserSerializer() class Meta: model = SaleHistory fields =['id', 'user', 'product', 'date_bought'] read_only_fields = ('user',) depth = 1 models.py class SaleHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') product = models.ForeignKey(SaleItems, on_delete=models.RESTRICT, default=None) date_bought = models.DateTimeField(auto_now_add=True) def __str__(self): return f' {self.product}, {self.user}, {self.id}' api.py create part class SaleHistoryVS(viewsets.ViewSet): permission_classes = [permissions.IsAuthenticated] def create(self, request): serializer = SaleHistorySerializier(data=request.data, many=True) if serializer.is_valid(): serializer.save(user = request.user) return Response(serializer.data, status= status.HTTP_201_CREATED) return Response(serializer.errors, status= status.HTTP_400_BAD_REQUEST) how do i make it so that i get to create post request without having to user in my post data. -
Why can't i uplod image in React js and Django?
I am trying to upload image in django backend but it all the time image not uploading its shows image:{} in request and also its shows always file upload succesfully and image is null ,Please Guide me how to resolve this error here codesandbox link https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1313 and here is code so what i did. Thanks import React, { useState } from "react"; import "./styles.css"; export default function App() { const [product, setProduct] = useState({ image: null }); const handleInputChange = (event) => { setProduct({ ...product, [event.target.name]: event.target.files[0] }); }; const handleSubmit = (e) => { e.preventDefault(); fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, { method: "POST", headers: { Accept: "application/json, text/plain, */*", "Content-Type": "multipart/form-data", "Accept-Language": window.localStorage.i18nextLng, Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw" }, body: JSON.stringify(product) }) .then((response) => { if (response.ok) { alert("Success"); } else { alert("error"); } }) .catch((err) => { console.log(err); }); }; return ( <div className="App"> <div id="other" className=""> <p className="mod" style={{ marginTop: "10px" }}> Upload image </p> <hr></hr> <form onSubmit={handleSubmit}> <input type="file" name="image" onChange={handleInputChange} /> <button>Submit</button> </form> </div> </div> ); } -
multiple instance of django-crontab project on same server , cronjob not adding
i am using 2 clone/copy of same django projects(dev/prod) in same system. when i am addings cron jobs to dev crontab file it worked but then when i tried to add same cron jobs for prod . it removed cron jobs of dev env and overwritten bu prod env cron jobs. settings.py (dev) CRONJOBS_LOG_DIR = r"/var/log/celery3" INBOX_JOB_LOG_FILE = "inbox_mail_cronjob.log" FAILED_JOB_LOG_FILE = "failed_mail_cronjob.log" FOREX_JOB_LOG_FILE = "forex_mail_cronjob.log" CRONJOBS_ERR_LOG = "cronjob_beat.log" CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/60 * * * *', 'integrations.cron_inbox_mail.trigger_updates_inbox_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ('*/15 * * * *', 'integrations.cron_failed_mail.trigger_updates_failed_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ('*/15 * * * *', 'integrations.cron_forex_mail.trigger_failed_forex_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ] settings.py (prod) CRONJOBS_LOG_DIR = r"/var/log/celery3" INBOX_JOB_LOG_FILE = "inbox_mail_cronjob_prod.log" FAILED_JOB_LOG_FILE = "failed_mail_cronjob_prod.log" FOREX_JOB_LOG_FILE = "forex_mail_cronjob_prod.log" CRONJOBS_ERR_LOG = "cronjob_beat_prod.log" CRONTAB_COMMAND_SUFFIX = '2>&1' CRONJOBS = [ ('*/60 * * * *', 'integrations.cron_inbox_mail.trigger_updates_inbox_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ('*/15 * * * *', 'integrations.cron_failed_mail.trigger_updates_failed_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ('*/15 * * * *', 'integrations.cron_forex_mail.trigger_failed_forex_task', '>> {} 2>&1'.format(os.path.join(CRONJOBS_LOG_DIR, CRONJOBS_ERR_LOG))), ] then on executing below cmd on dev $ python manage.py crontab add # cron jobs got added to crontab file $ python3 manage.py crontab show Currently active jobs in crontab: ff1cfe0b3c32005848f14c377f1de674 -> ('*/60 * * * *', 'integrations.cron_inbox_mail.trigger_updates_inbox_task', '>> /var/log/celery/cronjob_beat.log 2>&1') … -
Django how to write custom authenication that works for anonymos user?
I have a problem, becouse I have my django app, and whole logic related to permissions is combined in my custom permissions class - something like this: class MyPermissions(permissions.BasePermission): def has_permission(self, request, view): endpoint = get_object_or_404(DataSetApiEndpoint, pk=view.kwargs["pk"]) user_is_author = False can_read = False can_write = False if request.user.is_authenticated: is_author = endpoint.author == request.user can_read = ... can_write = ... user_can_read = ( is_author or can_read or endpoint.is_public ) user_can_write = is_author or can_write if request.method in permissions.SAFE_METHODS: if user_can_read: return True elif user_can_write: return True return False As you can see, if endpoint is public, even anonymous user can read from it. It works on localhost, but when I deployed it to server and tried to access public endpoint without logging in, I got: "detail": "Invalid username/password." If I was logged in, everything worked fine. As I found out, this message comes from rest BasicAuthentication. My question is, if I have permission class that takes care of whole permissions staff, is simple authentication without any checking enought? And do you have some example of authentication class tahtg would work for unathorized user when endpoint is public (all I've found worked only for logged in user)? -
How to user git in vue.js?
I use Vue.js like this in my html head, and my project is use django here is the question, when I simplely load the page by file:///C:/Users/86182/Desktop/mysite/polls/templates/polls/teastu.html, the data can show in this page; but when I "pythin manage.py runserver", the data is gone, however, it seems that it still can know this data, but just can not show on the page; here is my axios in Vue: please help me, I will be greatful! -
Pycharm, Django HTML template is not working for me after did all settings
I already added a Django template on setting-Languages&Frameworks-Template language and added HTML. Also, I set up Django in Languages&Frameworks too however, it's not supporting my HTML, I just did simple code {{hello}} and It is not working. from . import models def all_rooms(request): all_rooms = models.Room.objects.all() return render(request, "all_rooms.html", context={"rooms", all_rooms}) <h1>{{rooms}}</h1> Also, if, for things not show on HTML file ({% if %} Things cannot find declaration) -
Page reloading not working after get request
I have two forms to submit with Ajax , after the forms submitted django redirect to another page , i can see the GET request in the browser network tab but nothing happened to the url ?? views.py : if request.method == 'POST' and request.is_ajax: nadjib = modelformset_factory(Commande_Designation, form=Commande_D_Form, extra=1, can_delete=True) form = nadjib(request.POST) if form.is_valid(): commandes = Commande.objects.latest('id') res = 0 for x in form: data = x.cleaned_data commande = get_object_or_404(Commande,id=commandes.id) # print(data.get('Prix_Unitaire')) res = res + (float(Decimal(data.get('Prix_Unitaire'))) * float(Decimal(int(data.get('Quantite'))))) if res != commande.Montant_HT: er = 'la somme des prix doit etre égale au montant ht de la commande ! ' + ' ' + str(commande.Montant_HT) dat = dict() dat['errors'] = er print(er) return JsonResponse(dat) form.save() print('before redirect') return HttpResponseRedirect(reverse('update2', args=[commande.id])) // redirecting here ! else: comm = Commande.objects.last() comm.delete() data = dict() data['errors'] = json.dumps(form.errors) return JsonResponse(data) return redirect('test') -
Django - Method Not Allowed: (POST)
Im new to Django. I am trying to create product archvisation, but when i click on the button to archive i've got error ,,Method Not Allowed (POST)". Dunno how to deal with it. Here is my code views.py def to_archive(request): if request.method == 'POST': product = request.POST['to_archive'] product_archive = Product.objects.get(id=product) if not product_archive.is_active: product_archive.is_active = True product_archive.archived_date = timezone.now product_archive.save() models.py class Product(models.Model): is_archived = models.BooleanField(_('Archive'), default=False) archived_date = models.DateTimeField(_('Date Archived'), blank=True, null=True) form in html file <form action="{% url 'to_archive' %}" method="POST"> {% csrf_token %} <input type="hidden" name="to_archive" value="{{ object }}"> <input id="disactive_button" type="submit" class="btn btn-primary" value="To archive"> </form> urls.py urlpatterns = [ path('', IndexView.as_view(), name='home'), path('to_archive/', to_archive, name='to_archive'), ] -
how to exclude certain column from filters made using Django filters?
Hello i want to exclude certain columns from my table made from django table2- previously i used it like this - my tables .py is class ATable(tables.Table): class Meta: model = A exclude = ('aid',) per_page = 2 i want to make it user specific so that i can only see data entered from myuserid not all my filter.py code is class AFilter(df.FilterSet): class Meta: model = A exclude = ('aid','aaddress','acodenumber',) forms.py - from crispy_forms.helper import FormHelper class CustomerListFormHelper(FormHelper): model = A form_tag = False in this its actually excluding id column(from table and filters both) but not address and name column( i want it to be present in table but not in filters) but with such code i am unable to remove those fields kindly help. -
Computational complexity of reversed Foreign Key lookup
I got such models in Django: class Artist(models.Model): name = models.CharField(max_length=128) class Sons(models.Model): title = models.CharField(max_length=128) artist = models.ForeignKey(Artist, on_delete=models.DO_NOTHING) Let's say there are 1000 songs in total, while Artist1 has just 10 songs. When I do basic ORM query like Artist.objects.first().songs.all(), does it need to check every of 1000 songs if it is related to the Artist1 or it "knows" which 10 to get? In other words, does the cost of retrieving those 10 songs increase as the next songs get created? -
Django - handle more than one form request in view
I got a Model (called Module) where the admin can add new modules. In the template the user can move the modules to different positions which I handle with gridstack.js. I got a save button so the user can save the layout but there comes an error. The views.py only handle one request What I did was adding multiple forms to the views.py def index(request): modules = Module.objects.filter(active=True) module1 = Module.objects.get(id=1) module2 = Module.objects.get(id=2) form = Module_form(instance=module1) form2 = Module_form(instance=module2) if request.method == 'POST': form = Module_form(request.POST, instance=module1) form2 = Module_form(request.POST, instance=module2) if form.is_valid() and form2.is_valid(): form.save() form2.save() return render(request, 'main/index.html', { 'modules': modules, 'form': form, 'form2': form2, }) If I submit the form the first form gets the same values as form2. How can I send multiple requests in one view? Result should look like this: index.html ... <form action="" method="POST"> {% csrf_token %} {{ form }} <br> <br> {{ form2 }} <div class="grid-stack"> {% for data in modules %} <div class="grid-stack-item" data-gs-x="{{ data.x }}" data-gs-y="{{ data.y }}" data-gs-min-width="{{ data.min_width}}" data-gs-min-height="{{ data.min_height}}" data-gs-width="{{ data.width }}" data-gs-height="{{ data.height }}" id="{{ data.id }}"> <div class="grid-stack-item-content">{{ data.content|safe }}</div> </div> {% endfor %} </div> <input onclick="saveData()" type="submit" value="Einstellungen"> </form> The Javascript function saveData() … -
How to use email service of another parallel running django project in the first project?
I have a django project (Project 1) running on my system. Project 1 has multiple apps. Among them is an app (App 1). App 1 send emails for various tasks in it. I also have another django project (Project 2) running on my system. Project 2 has an almost similar app as App 1 in Project 1. Project 2 app name is App 2. The case is that for App 2, many emails have to be sent for situations similar to those in App 1 as these App 1 and App 2 are mostly similar. One way is that I can create an API in Project 1 for accepting data from Project 2 and whenever App 2 in Project 2 has to send email I can just hit the API of Project 1 and send the payload with it. Project 1 will then handle the part of sending email from the email system built within it. My question is: Are there other ways for achieving the same? -
Django models : format address to long / lat - not saving (infinite loading)
I have a question. I'm trying to create a model with address and format it into GPS point. The issue is when I try to save from admin, nothing is saved (page is loading infinitively). On the dashboard of my API, I don't have any request. I don't understand what's wrong here. shop/models.py from opencage.geocoder import OpenCageGeocode class Supermarket(models.Model): name = models.CharField(null=True,blank=True,max_length=300) street = models.CharField(null=True,blank=True,max_length=300) number_street = models.CharField(null=True,blank=True,max_length=20) town = models.CharField(null=True,blank=True,max_length=60) zipcode = models.CharField(null=True,blank=True,max_length=20) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') slug = models.SlugField(editable=False) def __str__(self): return self.name def save(self, *args,**kwargs): self.slug = slugify(self.name) address = " ".join([self.number_street, self.street, self.zipcode, self.town]) key = 'xxxx' geocoder = OpenCageGeocode(key) result = geocoder.geocode(address, no_annotations='1') if result: self.longitude = result[0]['geometry']['lng'] self.latitude = result[0]['geometry']['lat'] self.save() super().save(*args, **kwargs) -
ValueError at /update/2 The view postjobs.views.updateemp didn't return an HttpResponse object. It returned None instead
def editemp(request, id): cust = Customer.objects.get(id=id) return render(request, 'edit.html', {'Customer':cust}) def updateemp(request, id): updateemp = Customer.objects.get(id=id) print(updateemp) form = empforms(request.POST,instance=updateemp) if form.is_valid(): form.save() messages.success(request,"Record update successfully") return render(request, "edit.html", {"Customer":cust}) -
Separating translated Django URL patterns in apps
This is Django's way of translating URL patterns: https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translating-url-patterns The example works, however, it seems to go against one of Django's main design principles, i.e., keeping apps as reusable and independent as possible from the project in which they are. How can I take the news_patterns variable from the example above and decentralize it in an app/urls.py file? -
How to return two different error messages when querying the same model in Django
Take a look at the following: def mutate(self, info, first_id, second_id): try: first = Model.objects.get(pk=first_id) second = Model.objects.get(pk=second_id) except Model.DoesNotExist: return Exception('Object does not exist.') else: ... How can I return a custom error message depending on which of the ids actually does not exist? It's be nice to have something like: {first_id} does not exist I can't have two different except blocks because it's the same Model. What to do? -
how to get the status of running tasks with TaskResult
I have a running celery task. I want to get the status of the task with django_celery_results. But I noticed that the model only gets updated once the task completes running. How do I get the status of a running task with TaskResult? Example views def test(request): task_id = test_task.delay() status = TaskResult.objects.filter(task_id=task_id) print(status) When I run the above view this is the result I get <QuerySet []> -
Pyinstaller django Issue
Please, I have an issue with Pyinstaller and Django App (Django 3) with mongodb as database. the Exe is generated with a manage.spec file but when I run manage.exe runserver "settings.pyc" file is unfound.. It seems that settings.py is not detected . Please could you help me? Here is my manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import django.test from django.conf import settings def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Test_Project.settings') print(settings.GDAL_LIBRARY_PATH) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() and here is my manage.spec # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['test_project\\manage.py'], pathex=['C:\\Users\\SFadili\\Documents\\\\Django\\help\\Test_Project'], binaries=[], datas=[ ('test_project/test_app/templates', 'templates'), ], hiddenimports=[ 'test_app.apps', 'test_app.urls', ], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='test', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True ) -
compare database table rows in Django
I want to populate data from a database in a table. And each row will have a checkbox, And on the top a compare button. So basically i want to compare all the fields of the selected row with other selected rows on a new page -
Django 3 update value of a ManyToMany field Boolean
I'm creating an exam app Many Questions to Many Exams. One of the parameters is 'is_correct', which is a bool. for some reason, when i save the 'is_correct' on a question, the field changes globally (on the Question model) and become 'True' / 'False' to every one. How can i update the specific question for the specific exam only? Current code: exam_data = Exam.objects.get(exam_token=exam_token) if request.method == 'POST': choice = request.POST.get('answer') question_id = request.POST.get('question_id') correct_answer = exam_data.questions.get(id=question_id).answer if choice == correct_answer: question = exam_data.questions.get(id=question_id) question.is_correct = True # Change to True question.save() # After saving here, it changes for the model globally else: ...same but for False... -
Django Apscheduler execute at specific time each day
I would like to execute some code at a 11:59 PM each day (Africa/Johannesburg) time. from apscheduler.schedulers.background import BackgroundScheduler from updateRoot import updateApi scheduler = BackgroundScheduler() scheduler.add_job(updateApi.main, 'interval', days=1) scheduler.start() The code only executes a day after I start the server, which is not what I want to accomplish. Any ideas how to include the functionality into this code snippet? Thanks -
How to create Object in Django based on MySQL query conditions?
For single "id" in table there are multiple "companyid's", want to create an object, for these group of multiple companyid for single id. Q. How can i write similar conditions shown in below query (condition in where clause)into Object shown below. Below is the MySQL query: SELECT ID, company, group_concat(companyid), count() FROM organization where comapany in ("ABC") and ID is not null group by comapany, ID having count() > 1; This is how i tried to create object:(please correct this object according to above MySQL query conditions) Idmap_Obj = organization.objects.using("default").filter(comapany="ABC").values('id','comapany').annotate(Sum('companyid')).filter(cnt__gte=2) Note: organization is table name, default is database name -
Why can't i display my model foreign key instance in Django?
This worked just fine in my other project but now it doesn't work. Is there something wrong with my code? I followed these but nothing worked for me: How to display Foreign key Data in Django view page?, How to access foreign key in a django template? (DetailView), Django foreign key query, why it returns None? models.py class Author(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author_name') description = models.TextField(blank=True, null=True) class Post(models.Model): author_info = models.ForeignKey(Author, on_delete=models.SET_NULL, related_name='author_info', default=None, null=True) html template (this one is a generic.DetailView) {{ post.author_info.description }} EDIT: views.py class PostDetail(generic.DetailView): model = Post template_name = 'blog/blog_detail.html'