Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django channels function call not working
I am trying to implement a user notification feature. I update the user's status after he has connected to a room, but when I call self.update_user_incr(self,self.user,1) or self.update_user_decr(self.user,0) nothing happens. Why can't I call any function? What am I missing? consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope["user"] print('connect') self.update_user_incr(self,self.user,1)// not working ?? # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): print('disconnect') self.update_user_decr(self.user,0)// not working ?? # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': str(self.user), 'time' : str(localtime().now().strftime("%I:%M%p")), } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['user'] time = event['time'] print(self.user.username) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username' : username, 'time' : str(time), })) @database_sync_to_async def update_user_incr(self,user,num): print('increment') Profile.objects.filter(pk=user.pk).update(status=num) @database_sync_to_async def update_user_decr(self,user,num): Profile.objects.filter(pk=user.pk).update(status=num) -
How to connect Kafka consumer to Django app? Should I use a new thread for consumer or new process or new docker container?
I have Django app which should consume Kafka messages and handle it with my handlers and existing models. I use https://kafka-python.readthedocs.io/en/master/usage.html library. What is the right way to connect KafkaConsumer to Django app. Should I user a new daemon thread? Or a new process? Or a separate docker container maybe? Where to place the code (new Django app?) and how to start it automatically when Django app is ready. And how to update topics which it listen dynamically: should I kill old consumer and start new one each time in new thread? -
How to get an image from the server with django and graphql?
I already managed to make the mutations to upload, update and print the images. But how can I get the images files on in base64 in the query? class Image(models.Model): image = models.ImageField(blank=True, null=True, upload_to="uploads/images") product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) -
Django, Assigning FileField value without saving
I am trying to assign a file from URL in django without automatically save after i initialize the object "household_profile" import urllib.request #___________________________________________________________________ # to hold all unsaved collection "household_profile" #____________________________________________________________________ of_household_profile_collection = []; for per in data["results"]: download_url = per['_attachments'][0]['download_url']; opener = urllib.request.build_opener() opener.addheaders = [('Authorization', Authorization)] urllib.request.install_opener(opener) attachment = urllib.request.urlretrieve(download_url); attachment_fname = os.path.basename(download_url) of_household_profile = household_profile( kobo_user_id=per['_id'], first_name=per['First_Name'], last_name=per['Name'], middle_name=per['Middle_Name'], phone_number=per['Mobile_Number'], email=per['Email'], purok=per['Purok'], barangay=per['Barangay'], qr_id=per['_uuid'] ); of_file = open(attachment[0]); #___________________________________________________________________ # i just want to assign it for a purpose not to save it automatically #____________________________________________________________________ of_household_profile\ .verification_file\ .save(attachment_fname, File(of_file)) Is there way that i should know ? -
Django admin not working on server after adding 'django.contrib.sites'
Site was working fine on local server. But the same thing when deployed on server. Admin CSS misbehaves Admin panel screenshot on server admin panel site also working fine on mobile responsive view -
How can i create multiple django project on pycharm without one conflicting with other port
I create a django project called Polls and i have one project called registration but anytime i run my polls server it always go to the registration server and display things there also my migrations doesnt go to the polls server -
Deleting values connected to each other in the database
My database models.py looks like this: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField(unique=True) description = models.TextField() quantity = models.IntegerField(default=1) class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) image = models.ImageField(upload_to='bikes') When I am deleting an entry in the table Item it also deletes everything that is associated in the table Bike. But when I am deleting an entry in the Bike table it doesn't delete any data in the Item table. Is there any possible way to delete all data in the Item table, when you delete an entry in the Bike table? -
How to check if field is unique in models of Django?
I'm new to Django. In car/models.py, I'm creating a new class: class Car(models.Model): name = models.CharField(max_length=100) This is being created in the admin section of Django. I want name to be unique. How can I verify that this name was not already used? -
Access Django API via Heroku returns "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in request."
I deployed my Django project on Heroku with gunicorn. It's basically only the api (no templates). When I deploy heroku and access <heroku url>/api/login for example in the browser and post login data already in json format, it always returns "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in request." But when I do the same on localhost, the user gets authenticated and I receive a response with user data... post data example for login: { "email": "ana@test.com", "password": "ana1234567890" } The parser_classes = [JSONParser] is added on every view where I don't have images or files (there I am using FileUploadParser). I deployed on Heroku with gunicorn, because on localhost I permanently received "Unauthorized" from backend ( Permission Class is "isAuthenticated" for most of my views). After some research I figured out that probably the authorization header is not sent (here the APACHE WSGIPassAuthorization On would be a solution) but I don't have an apache server running and I don't want no webserver running on my machine. I thought if I would deploy it on heroku with gunicorn, I could continue with the development without the "Unautorized" header but instead I run in other errors, like "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in … -
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})