Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django overwrite model save method to check if a many to many field has changed
so I have a model for which I need to overwrite the save property to check if a many to many relation has changed. Normally for like a char field you could do something like the below, but for many to many it works differently. class Interest(TimestampedModel): subjects = models.ManyToManyField('genre.Subject', blank=True) def save(self, *args, **kwargs): if self.id: old_subjects = Interest.objects.filter(pk=self.pk).first().subjects.all() subjects = self.subjects.all() if subjects != old_subjects: # Do stuff Any idea how to make something like this for a many to many field? -
user search engine with tags - Django - Python
I want to make a user search engine with profile tags. The search engine will show users and tags models.py class UserProfile(models.Model): objects = None user = models.OneToOneField(User, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30, blank=True, null=True) bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) location = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField(upload_to='uploads/profile_pictures/', default='uploads/profile_pictures/default.png', blank=True) followers = models.ManyToManyField(User, blank=True, related_name='followers') tag_i = TagsField(max_length=1000, default='non') views.py class UserSearch(View): def get(self, request, *args, **kwargs): query = self.request.GET.get('query') profile_list = UserProfile.objects.filter(Q(tag_i__icontains=query) | Q(user__username__icontains=query)) field_name = 'tag_i' obj = UserProfile.objects.first() field_object = UserProfile._meta.get_field(field_name) field_value = field_object.value_from_objects(obj) field_value = "".join(field_value) field_value = field_value.split(",") context = { 'profile_list': profile_list, "tags": field_value, } the current code assigns the same tags to everyone. How to assign tags to each person? what should I use instead.. obj = UserProfile.objects.first() to make tags suitable for individual users -
Django Rest Framework ordering by count of filtered pre-fetched related objects
I'm hoping someone might be able to help me. I am working with Django Rest Framework, and attempting to create an API that allows users to search for Providers that provide specific Procedures in particular Regions, and only return the relevant details. Set up I have these models (heavily simplified): # models.py from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Region(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ["name"] class Procedure(models.Model): description = models.CharField(max_length=100) class Meta: ordering = ["description"] class Provider(models.Model): provider_name = models.CharField(max_length=200) class Meta: ordering = ["provider_name"] class Provision(models.Model): fk_procedure = models.ForeignKey( Procedure, related_name="providers", on_delete=models.RESTRICT, ) fk_provider = models.ForeignKey( Provider, related_name="services", on_delete=models.CASCADE, ) discount = models.FloatField( validators=[MaxValueValidator(100), MinValueValidator(0)], default=0, ) class Meta: ordering = ["-discount"] unique_together = ["fk_procedure", "fk_provider"] class ProvisionLinkRegion(models.Model): fk_provision = models.ForeignKey( Provision, related_name="regions", on_delete=models.CASCADE, ) fk_region = models.ForeignKey( Region, related_name="services", on_delete=models.RESTRICT, ) location = models.BooleanField(default=False) As you can see, there is a ManyToMany link between Provision and Region via ProvisionLinkRegion. I haven't defined this as a ManyToMany field though, as I need to store additional details (location) about the pairing. I have defined the following serializers on these models: # serializers.py from rest_framework import serializers from models import ( Provider, Region, Procedure, ProvisionLinkRegion, … -
I've got authentication error with Alpaca broker api
Want some help from you. I am working in Django/React project with Alpaca Broker APi https://alpaca.markets/broker https://prnt.sc/1sfzv9k I am trying to get relationship ID. Btw I am getting the error like screenshot Please help me if you have an expertise with Alpaca API Thanks -
How do I show the output of a shell command in Django using channels?
I want to display the content of an install command executed by the user on my webpage. The commands are typically slow, so I wanted to display a live output of their logs. I want the output of this command to be used inside a template. I know that I may need to write a websocket to do this, but I hear that django channel can help me with this. Can someone provide me with a simple example of how to do this? All I need is simple websocket code(websocket.py), django views(views.py), and the template(template.html). Of course, if settings.py needs changed, please let me know. Thanks, Jacob -
How to have common query in django for notification system?
I have an "bell" icon on nav bar - which shows notification for each users ! As of now, all the nav bars are made common layouts and included into blocks of each page in django. Now the problem is when ever i go to a screen, its needs to make query all on notification model to display the notifications ! And i have 24 pages, and which means notification needs to be fetched for 24 times. How to make this effeciently, so that i just query once and show notification on each page when user visits there Please guide, i dont know what code to show. If you need any code please mention on comment -
data in a formset passed by a form
hi I have this error in inserting a data in a formset passed by a form this is the error that appears in my browser: NOT NULL constraint failed: devtest_datigruppi.gruppi_scheda_id it practically fails to see this change: groups.gruppi_scheda = Schede.objects.get (tab_name = tabName) but via print the right thing appears to me schedaName = schede_form.cleaned_data['nome_scheda'] scheda = schede_form.save(commit = False) scheda.utente = request.user scheda.save() #gruppi if gruppi_formset.is_valid(): for gruppi in gruppi_formset: gruppi.save(commit = False) gruppi.gruppi_scheda = Schede.objects.get(nome_scheda = schedaName) print(gruppi.gruppi_scheda) gruppi.save() -
Arrangind models names according to our wish in Django admin dashboard
Django admin dashboard image ( click here) In the above django admin panel , the model names are arranged according to ascending order. Can i arrange them in my own wish ? If yes , can u suggest me how? -
Django don't send email message with attached zip file
everyone! I have a problem with sending an email with Django smtp email backend and SendGrid. My view is below. It makes batch of pdf files with pyppeteer, zip them to archive, attaches to the message and then send it to the email. It should be, but it doesn't work! I checked it with other view for email sending(a little bit diff logic without zip or something.) and it worked but this means that it's not the problem with sendgrid and any other stuff like secret keys in uwsgi configuration. The fact is, emails don't stuck in send grid list. I tried to put some dummy bites instead of pdf file like pdf_file = b'some bytes' and it worked on my local machine but didn't work on server. I got the size of zip-archive from a response. Please explain to me where I'm wrong. ### views.py @csrf_exempt @require_POST def generate_batch_pdf(request, blueprint): try: payload = json.loads(request.body) email = payload.get('email') uuids = payload.get('uuids') zip_buffer = io.BytesIO() compression = zipfile.ZIP_DEFLATED with zipfile.ZipFile(zip_buffer, 'a', compression, False) as f: for uuid in uuids: report_name = _report_name(uuid, blueprint) pdf_file = async_to_sync(generate_pdf_file)( request.get_host(), uuid, blueprint, report_name, ) f.writestr( zinfo_or_arcname='{0}'.format(report_name), data=pdf_file, ) msg = EmailMessage( subject='Отчеты Тест', body='Архив … -
Django app crash after pytesseract reads autogenerated image from pdf
When a user uploads files to my system, I start a new thread that scan them in order to find a specific pattern, while the view that handles the upload returns and the app is redirected to the main page. thread = threading.Thread(target=fucn1, args=(arg1,)) thread.start() In func1(), if the file is a PDF, I divide it into pages and then save and analize each of them, as below: def func1(uuid): documents = Document.objects.filter(model_uuid=uuid) result = set() for document in documents: if extension == 'pdf': pages = convert_from_path(filepath,500) for i in range(len(pages)): page = pages[i] img_filepath = local_directory + 'page_' + str(i) + '.jpg' page.save(img_filepath, 'JPEG') values = analize(img_filepath) result = set.union(result, values) else: values = analize(filepath) result = set.union(result, values) def analize(filepath): pattern = "xxxxxxxxxxxx" # Load image img = cv2.imread(filepath) # Extract text from image sret = pytesseract.image_to_string(img) return re.findall(pattern, sret) If the input file is already an image (png, jpg, jpeg), the division by pages is omitted, and everything works good. However, if the file is a PDF, the system crashes here: sret = pytesseract.image_to_string(img) Which leads me to think that there is an issue regarding pdf2image or poppler-utils. However, this function also gets executes when the input … -
Adding multiple parameters to a JS script from HTML
I would like to pass some data from my Python view function to a JS script using HTML. That's my view function def home(request): if request.method == 'POST': params = GameOfLifeForm(request.POST) if params.is_valid(): starting_grid = get_starting_grid(params.cleaned_data) to_html = { 'animation': True, 'gameoflifeform': params, 'start_grid': starting_grid, } else: to_html = { 'animation': False, 'warning_msg': 'Something went wrong. Try once again.' } return render(request, 'get_animations/home.html', to_html) else: form = GameOfLifeForm() return render(request, 'get_animations/home.html', {'gameoflifeform': form}) My form contains four parameters, one of them is called iterations and that is the one I would like to pass to JS script. Moreover I would like to pass start_grid. I tried to do it in the following way in my HTML file {{ start_grid | json_script:"start-grid" }} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> Then in my JS script I wrote var startGrid = JSON.parse(document.getElementById("start-grid").textContent); console.log(startGrid); Worked perfectly, I got the grid printed out in my console. Similar I could grab iterations from HTML {{ gameoflifeform.iterations.value | json_script:"iterations"}} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> When I tried to add both variables into my JS script it didn't work. {{ gameoflifeform.iterations.value | json_script:"iterations"}} {{ start_grid | json_script:"start-grid" }} <script type="text/javascript" src="{% static 'js/runGameOfLife.js' %}" ></script> … -
Cannot connect to celery signals from django
I have the default django integration from the celery docs. Also just added @before_task_publish.connect(weak=False) def before_task_publish_handler(*args, **kwargs): logger.error(f'Args {args}') logger.error(f'Kwargs {kwargs}') Running in the shell: debug_task.delay() There is no logging or breakpoint catching in pycharm. I do not think it connects to celery, but I do not know how to check. What am I missing? -
Using kong api gateway jwt plugin with django microservices
I am currently playing around with the Kong API Gateway and I would like to use it to validate the authentication and the authorization of users at the gateway and restrict access to services if the user is not logged in properly. I have already an existing authentication django microservice which issues JWTs whenever a user logs in but i cant share this tokens with the other microservices because each one of them have his own database. So i would now like to know if i can share the JWT secret produced by django and use it for jwt plugin of kong api and also do i need to create a consumer for every users and what is the right steps to achieve that ? Any hint would be highly appreciated. -
unable to create recs via foreign key association in django
I am completely new to django and python need your insights here I am trying to parse a list of csv files from a directory, storing the name and row_count in Files model and the content of the csv in Work model(associated with Files) I have two queries The recs are created in Files model , but no recs being created in Work model, below is my code and no error message is thrown Models class Files(models.Model): filename = models.CharField(max_length=100) work_count = models.IntegerField(default=0) class Work(models.Model): proprietary_id = models.IntegerField(default=0) iswc = models.CharField(max_length=1000) source = models.CharField(max_length=1000) title = models.CharField(max_length=1000) contributors = JSONField() file = models.ForeignKey(Files,on_delete = models.CASCADE) View root_dir="D:/Django/siva/files" for file in os.listdir(root_dir): with open(f'{root_dir}/{file}','r') as csv_file: csv_reader= csv.DictReader(csv_file,delimiter=',') Files.objects.create(filename=file, work_count=len(list(csv_reader))) for row in csv_reader: file_obj=Files.objects.get(filename=file) print(file_obj) Work.objects.create(proprietary_id=row['proprietary_id'],iswc=row['iswc'],source=row['source'],title=row['title'],contributors=row['contributors'],file_=file_obj) sample csv file title,contributors,iswc,source,proprietary_id Shape of You,Edward Christopher Sheeran,T9204649558,sony,1 Je ne sais pas,Obispo Pascal Michel|Florence Lionel Jacques,T0046951705,sony,3 And also is there any specific method to set the root_dir , so I don't need to change the filepath structure across OS's -
How to change the `frontend_domain` port in `GRAPHQL_AUTH` in the verification mail?
I'm working on a Docker-Django-Graphene-React stack where Django is the backend which receive GraphQL queries through Graphene from React which acts as the frontend. Everything runs in docker containers. Django on port 8000 and React on 3000. I'm currently working on the authentication with the python's django-graqhql-auth package. When a user register itself on the frontend form, the register mutation is correctly made to the backend and the account is created. A mail is sent at the same time to the user's registered mail address containing a verification link with a token that must be used with the veryifyToken mutation in order to flag the account as verified. Here is an example of the link: http://localhost:8000/activate/eyJ1c2VybmFtZSI6IkpvaG5zb2ZuZiIsImFjdGlvbiI6ImFjdGl2YXRpb24ifQ:1mQr0R:Wh25LJ6A1PRVCQT730kXXIk4i2QJgz1a4aNDe7RoZM0 The problem is that the port on the link is 8000, which redirects to the backend (Django). I would like to redirect the user on port 3000 which is the frontend (React). According to the documentation, I should be able to change the frontend_domain which I did. I also changed the path and the protocol values to see if it works: Here is what I put in my backend's settings.py file: GRAPHQL_AUTH = { "EMAIL_TEMPLATE_VARIABLES": { "protocol": "https", "frontend_domain": "localhost:3000", "path": "verify", } } … -
Django calculate sum of column after multiplying each row with a different value
I have three Django models defined as: class User(models.Model): name=models.CharField income=models.DecimalField expenditure=models.DecimalField group=models.DecimalField country = models.ForeignKey(Country) class Country(models.Model): name=models.CharField currency = models.ForeignKey(Currency) class Currency(models.Model): name=models.CharField value=models.DecimalField Users can be from different countries. Each country has a currency whose value is the exchange rate with USD. I am trying to calculate the sum of all the column after multiplying each value with the respective currency exchange rate. For example, for 3 Users: John:2:10:1:2 Jame:10:11:1:1 Mark:5:11:1:1 Country 1:USA:1 2:UK:2 Currency: 1:USD:1 2:GBP:1.5 I would like to print the sum after calculating income: (2*1.5) + (10*1) + (5*1) expenditure: (10*1.5) + (11*1) + (11*1) Final output: income: 18 expenditure: 37 I am thinking something like this might work but I could not quite get it: user=User.objects.filter(group=1).aggregate((Sum('income')*(country_currency_value),(Sum('expenditure')*(country_currency_value)) Any help is much appreciated -
Profiling database queries and latency of ordinary functions in django
We need some tool for analyzing non view functions of our django project particularly the celery-beat tasks. So, is there any tool for profiling queries and latency of running ordinary functions (not views) in a django app? Preferably, is there any decorators (or any other mechanism) that can add results of profiling an ordinary function to the output of tools like django-silk or django-debug-toolbar? -
What is this random key in Django form ? And how to get rid of it?
I am trying to create a form page but have no idea about this random key showing up below Enter details. Could anyone explain me about it and how do I get rid of it ? -
Django forms ValueError with HiddenInput widget
I have a weird problem. I have my model GameTask with fields like: activity = models.ForeignKey(Activity, verbose_name='Activity', related_name='activities', null=True, blank=True, on_delete=models.SET_NULL) distance = models.IntegerField(verbose_name='Distance [m]', default=0) I want to create form for this model and display activity and distance field only in specific category(field in GameTask) like: form.fields['activity'] = forms.CharField(widget=forms.HiddenInput(), required=False) form.fields['distance'] = forms.CharField(widget=forms.HiddenInput(), required=False) if category_slug == settings.GAME_TASK_SPORT_CATEGORY_NAME: form.fields['activity'] = forms.ModelChoiceField( required=False, queryset=Activity.objects.all(), widget=forms.Select( attrs={'placeholder': 'Aktywności', 'class': 'form-control'} ) ) and it works. These 2 fields display only with specific category.But when I want to save form I get error: Cannot assign "''": "GameTask.activity" must be a "Activity" instance. In addition I have defined structure like this: MODEL_PARAMS_TASK = { 'model': GameTask, 'fields': ['name', 'teams', 'activity', 'distance', 'description', 'button_text', 'cycle_type', 'self_confirm', 'confirm_attachment', 'attachment_options', 'points', 'max_points', 'image', 'multi_task_image', 'priority', 'attrs', 'private_attrs'], 'template_name': 'master/task_form.html', 'success_url': 'master_task_item', } I was thinking about refactoring this and create 2 forms (1 for specific category and 1 default), but maybe there is other solution to solve this problem. If something is not clear I will explain it more specific -
Django CK editor images not displaying, a quick F12 shows that images are comming from backend but not displaying, please help me to fix this
Hello , I am trying to develop a blog application using react and django and for description section i choose django ckeditor. when i upload a image using ck editor it's showing in adminpanel section no warnings because i double checked every path of django ckeditor . but those images are not dispalying in the front end it's just showing a blank image field. but it's working on a simple html file not working with React . images are totally blank where i am missing ? if i do a quick F12 to check if the image is coming from backend or not . it is coming there but just not showing, Text is showing just not image import React,{useState,useEffect} from 'react'; import {Link} from 'react-router-dom'; import axios from 'axios'; const BlogDetail =(props)=>{ const [blog,setBlog]=useState({}); useEffect(()=>{ const slug=props.match.params.id; const fetchFata=async()=>{ try{ const res=await axios.get(`${process.env.REACT_APP_API_URL}/api/blog/${slug}`); setBlog(res.data); } catch (err){ } }; fetchFata(); },[props.match.params.id]); const createBlog = () => { return {__html: blog.content} }; const capitalizeFirstLetter = (word) => { if (word) return word.charAt(0).toUpperCase() + word.slice(1); return ''; }; return( <div className='container'> <h1 className="display-2">{blog.title}</h1> <h2 className='text-muted mt-3'>Category: {capitalizeFirstLetter(blog.category)}</h2> <h4>Last commit {blog.updated}</h4> <div className='mt-5 mb-5' dangerouslySetInnerHTML={createBlog()}/> <hr/> <p className='lead mb-5'><Link to='/blog' className='font-weight-bold'>Back</Link></p> </div> … -
Forms and other component don't work with swup.js or barba.js
I'm currently coding a mobile app with a header and a footer common to all pages. I'm trying to add page transition to make the app smoother and avoid static reload each time an user move from one page to another. This is running on Django, and I only have a basic knowledge in javascript. So, I tried both swup and barba which work really great without so much complication except a specific point which simply kill the app functionalities. The main problem concern all my forms which doesn't work anymore if I go back to the concerned page without entirely refreshing the page. The be more precise, admitting I am on the 'home' page and moving to 'settings' page, if I now go back on 'home' none of the forms work anymore, including some other part of my html depending on css or javascript. I tried moving all css and javascript link tags in each swup/barba container of each page to get them reloaded each time but it doesn't work. Does anyone could tell me why is this not working ? Thank you in advance for your help ! -
How to get correct user?
How i can take a correct user? Let's assume I have a model named "MUSIC" in which it is located owner = models.ForeignKey(Profil, on_delete=models.CASCADE) I have a page on which i want display everything that is in the model "MUSIC". Views m = Music.objects.all() Okay i know that this display all project music. But the problem is how to assign the specific user from model named "Profile" to model named 'Music" Url path('profil_user/<int:pk>/',ShowProfilPage.as_view(), name='profil_user'), When i try: {% for x in m %} {{x}} <a href="{% url 'profil_user' x.pk %}> CLICK </a> {% endfor %} This take not a correct user profile but it doesn't get to the model called 'Profile' but to 'Music' http://127.0.0.1:8000/profile/profil_user/2/ it is http://127.0.0.1:8000/profile/profil_user/10/ http://127.0.0.1:8000/profile/profil_user/11/ -
celery autoscaling - determine optimum number of pool processes required
I need to determine the best possible combination of minimum and a maximum number of pool processes. Is there a way of testing and getting the optimum values? I'm using rabbitmq as a broker and this process is running on a machine with 8 cores -
Can't do a GET request using email as the primary key - "detail": "Not found."
I'm trying to do a GET request on an API that returns the relevant entry but keep getting not found. If I call: http://127.0.0.1:8000/bookings/booking/ I can GET all the entries but when I try GETing one entry based on the primary key (which is an email address (nested object) - yes I have considered changing this as I've read it's bad practice for many reasons). It just returns detail not found. Other endpoints where the primary key is ID work just fine. http://127.0.0.1:8000/bookings/booking/2customer%40business2.com/ Can someone explain to me why the email doesn't return an entry.` but I keep getting: "detail": "Not found." models.py class CustomerBookings(models.Model): completed = models.BooleanField() booking_startdate_time = models.DateTimeField() dynamic_slot = models.ForeignKey(DynamicSlot, blank=True, null= True, on_delete = models.SET_NULL, related_name="%(class)s_dynamicslot") customer = models.OneToOneField(Customer, primary_key=True, blank=True, on_delete = models.CASCADE, related_name="%(class)s_customer") views.py class BookingAPIViewSet(viewsets.ModelViewSet): # permission_classes= [DjangoModelPermissions] - disabled for testing serializer_class = CustomerBookingsSerializer queryset = CustomerBookings.objects.all() serializer.py class BookingSerializer(serializers.ModelSerializer): class Meta: model = CustomerBookings fields = ('__all__') -
Access model instance inside model field
I have a model (Event) that has a ForeignKey to the User model (the owner of the Event). This User can invite other Users, using the following ManyToManyField: invites = models.ManyToManyField( User, related_name="invited_users", verbose_name=_("Invited Users"), blank=True ) This invite field generates a simple table, containing the ID, event_id and user_id. In case the Event owner deletes his profile, I don't want the Event to be deleted, but instead to pass the ownership to the first user that was invited. So I came up with this function: def get_new_owner(): try: invited_users = Event.objects.get(id=id).invites.order_by("-id").filter(is_active=True) if invited_users.exists(): return invited_users.first() else: Event.objects.get(id=id).delete() except ObjectDoesNotExist: pass This finds the Event instance, and returns the active invited users ordered by the Invite table ID, so I can get the first item of this queryset, which corresponds to the first user invited. In order to run the function when a User gets deleted, I used on_delete=models.SET: owner = models.ForeignKey(User, related_name='evemt_owner', verbose_name=_("Owner"), on_delete=models.SET(get_new_owner())) Then I ran into some problems: It can't access the ID of the field I'm passing I could'n find a way to use it as a classmethod or something, so I had to put the function above the model. Obviously this meant that it could …