Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I call and use variables from a class method in another (views.py) function?
Using a class 'ConfigurationView()', I am able to render a form and print the value from the POST request (at the click of a button) within of the class' methods; 'def post()'. However, I will like to use the variable text(which I'm currently able to print in console), in another function 'views.py', as one of the parameters needed in the function. When I imported the class, I tried to refer to the methods within the class and then pick up the value that I need, i.e., 'text', print it in the console to see what I have before I proceed with the rest of the function. But I got None. Below is the class (with its methods) and the view function respectively. ** the class ** class ConfigurationView(TemplateView): template_name = 'projects/configuretest.html' def get(self, request): form = MaturityForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = MaturityForm(request.POST) if form.is_valid(): text = form.cleaned_data['datum_temp'] args = {'form': form, 'text': text} print(text*2) return render(request, self.template_name, args, text) ** views.py function (on a separate page)** def maturity_data(request, pk): b = ConfigurationView() b.get value = b.post #get the same value as 'text' tim = [] temp = [0, 2.5] hum = [0] output = … -
Poor Performance when trigram similarity and full-text-search were combined with Q ind django using postgres
I'm creating a web application to search people with their properties such as education, experience, etc. I can't use full-text-search for all the fields, because, some has to be a fuzzy match. (Eg: if we search for biotech, it should pick bio tech, biotech and also bio-tech). My database has about 200 entries in the profile model, which is to appear in the search results. Other models like education and experience are connected to profile through foreign key Therefore, I decided to be selective on what method to use on what field. For shorter fields like degree name (In the Education model) I want to use trigram similarity. For fields like education description, I use Full-text search. However, Since I have to do this in multiple fields, I used simple lookups instead of using search vectors. Profile.objects.filter( Q(first_name__trigram_similar=search_term) | Q(last_name__trigram_similar=search_term) | Q(vision_expertise__search=search_term) | Q(educations__degree__trigram_similar=search_term) | Q(educations__field_of_study__trigram_similar=search_term) | Q(educations__school__trigram_similar=search_term) | Q(educations__description__search=search_term) | Q(experiences__title__trigram_similar=search_term) | Q(experiences__company__trigram_similar=search_term) | Q(experiences__description__search=search_term) | Q(publications__title__trigram_similar=search_term) | Q(publications__description__search=search_term) | Q(certification__certification_name__trigram_similar=search_term) | Q(certification__certification_authority__trigram_similar=search_term) | Q(bio_description__search=search_term) | ) I get the expected results on every search. However, the time it takes to get it is ridiculously slow. I can't figure it out how to make this faster. -
get data from queryset and use that data in ploting highcharts in django
I'm taking data from a queryset and data is of type Datetime stamp. I want to extract data of months from queryset and use it to plot my highcharts. Where dataset is a queryset. '''def chart_data1 (request): dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate( c=Sum('total_trucks')).values('month', 'c') print(dataset) showData= DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')) print(showData) chart = {'chart': {'type': 'column', 'height': 400, }, 'title': {'text': 'Total Trucks Dispatched by Months'}, 'series': [{'name': 'Months', 'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]}]} return JsonResponse(chart) ''' -
Context manager to keep Django views clean?
I have already asked similar question, but that was too broad and not Django-specific. Is a good practice to keep Django views clean with context managers to make a code DRY? This is example of code (a bit pseudocode): class DjangoViewset(): @action(method=['GET']) def custom_action1(request): a = get_data_from_somewhere1() b = get_data_from_somewhere2() if a<b: raise 400 if a==1: raise 404 if a==2: raise 403 result = some_complicated_logic(a, b) return Response(result) @action(method=['GET']) def custom_action2(request): a = get_data_from_somewhere1() b = get_data_from_somewhere2() if a<b: raise 400 if a==1: raise 404 if a==2: raise 403 result = some_complicated_logic_another(a, b) return Response(result) Can I refactor it with something like this or this is bad using of context manager? @contextmanager def validate_data(a, b): if a<b: raise 400 if a==1: raise 404 if a==2: raise 403 yield class DjangoViewset(): @action(method=['GET']) def custom_action1(request): a = get_data_from_somewhere1() b = get_data_from_somewhere2() with validate_data(a, b): result = some_complicated_logic(a, b) return Response(result) @action(method=['GET']) def custom_action2(request): a = get_data_from_somewhere1() b = get_data_from_somewhere2() with validate_data(a, b): result = some_complicated_logic_another(a, b) return Response(result) With this refactor code looks much simpler, but I can't find information if I can use context manager this way, but is it not forbidden style? -
"How to implement Channels-2.x in DRF?"
"I'm implementing real-time notification to users or client in my Django-project. For example, the case where actual notification comes is that, when a project-manager assigns developers to a project, the developers should get a notification in the developers view with-out any delay or without refreshing page (notifying as, you have been added to _____ this project). I don't get a clear understand from channels official docs https://channels.readthedocs.io/en/latest/. My requirement is that can someone share any document related implementing channels in Django-rest-framework Front-end i'm using is Angular. " -
How to have docker container access remote database via host SSH connection?
I have a VM instance where I run the following Docker containers: django nginx postgres redis My project is structured as thus: project_root | |--- production.yml |--- .envs | | | |---.production | | | |---.postgres | |---... more Django apps | |--- compose | |---production | |---- django | |---- Dockerfile | |---- entrypoint | |---- start | |---- postgres |---- Dockerfile The /compose/production/django/Dockerfile is as follows: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # git && apk add --no-cache git RUN addgroup -S django \ && adduser -S -G django django # Requirements are installed here to ensure they will be cached. COPY ./requirements /requirements RUN pip install --no-cache-dir -r /requirements/project.production.txt \ && rm -rf /requirements COPY ./compose/production/django/entrypoint /entrypoint RUN sed -i 's/\r//' /entrypoint RUN chmod +x /entrypoint RUN chown django /entrypoint COPY ./compose/production/django/start /start RUN sed -i 's/\r//' /start RUN chmod +x /start RUN chown django /start COPY . /app RUN chown -R django … -
How to deploy symlinked react javascript files to appear in the Docker container
I have a Django as backend and React as frontend project running inside Docker containers. Currently, I have all the Django and react code all in the same repo. And the project works as expected when testing at http://localhost:8000/frontend which will hit the template (index.html under the /frontend/templates/frontend which in turn will reference /frontend/static/dist/main.js) So as it is right now, the project works with Docker. The project is structured as thus: project_root | |---frontend (this is a Django app which contains the react files) | |--- static | | |--- dist | | |--- main.js | | | |--- templates | |--- frontend | |--- index.html (this references the static/dist/main.js) | | |---... more Django apps | |--- compose | |---local | |---- django |---- Dockerfile |---- start Currently, my Dockerfile under the /compose/local/django looks like this: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add … -
How to perform two step reverse relation in django query?
These are my models: class Group1(models.Model): group_name = models.CharField(max_length=32) master = models.ForeignKey("self",on_delete=models.CASCADE,related_name='master_group',null=True) class Ledger1(models.Model): name = models.CharField(max_length=32) group1_name = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups') closing_balance = models.DecimalField(default=0.00,max_digits=20,decimal_places=2,blank=True) class Journal(models.Model): date = models.DateField(default=datetime.date.today) by = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers') to = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers') debit = models.DecimalField(max_digits=20,decimal_places=2,null=True) credit = models.DecimalField(max_digits=20,decimal_places=2,null=True) As you can see the the Group1 model is connected to Ledger1 model which is further connected to Journal model. I want to make a query in django views that It will calculate the closing_balance of each Group in respect to the date of Journal passed. I tried the below: group_closing = Group1.objects.filter(ledgergroups__Debitledgers__date__gte=Start_date,ledgergroups__Debitledgers__date__lt=End_date).aggregate(the_sum=Coalesce(Sum('ledgergroups__Closing_balance'), Value(0)))['the_sum'] Start_date and End_date cointains some date for test purpose. But the results is showing None.. Can anyone tell me what is worng in my query. Thank you -
Saving the image in Models.ImageField using a url(Profile picture image url) obtained from FacebookAPI
I have succesfully obtained the profile picture url from facebook api.But want to save in a a image feild. I tried some code from stack overflow , but the stored image contains nothing.Help me with it? here's my code Models.py class Userinfo (models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length = 200) email = models.CharField(max_length = 200) city = models.CharField(max_length = 100, null = True) headline = models.CharField(max_length = 200, null= True) contact_number = models.CharField(max_length = 200,null = True) gender = models.IntegerField(null = True) image_url = models.CharField(max_length = 500, null = True) image_file = models.ImageField(upload_to='media/profile_pics/',blank =True) interests = models.CharField(max_length = 400,null = True) about = models.CharField(max_length = 400, null = True) fb_link = models.CharField(max_length = 400, null = True) linkedin_link = models.CharField(max_length = 400, null = True) headline = models.CharField(max_length = 100, null = True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.image_url and not self.image_file: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(self.image_url).read()) img_temp.flush() self.image_file.save(f"image_{self.pk}", File(img_temp)) super(Userinfo, self).save(*args, **kwargs) and here is my view views.py def login(request): if request.method == 'POST': res = json.loads(request.body) user = Userinfo.objects.filter(email = res['email']) if user : userinfo = Userinfo.objects.all().filter(email = res['email']) else : userinfo = Userinfo.objects.all().filter(email = res['email']) if not userinfo: userinfo = Userinfo() usr … -
Updating model field in django not working properly at runtime
I have a model Product and another model Damaged. In the Damaged model I add the number of damaged quantity of a certain product. Now, I need that damaged_quantity to be reduced from the stock field in the Product model when the foreign key matches. The code works when I have added a damaged_quantity in the Damaged model but when there is no damaged_quantity of a certain product it throws type error so I tried like this in template but it is not working. models.py class Product(models.Model): name = models.CharField(max_length=250) quantity = models.IntegerField() @property def current_quantity(self): return self.quantity - self.damaged_set.all().aggregate(sum=Sum('damaged_quantity')).get('sum', 0) class Damaged(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) damaged_quantity = models.IntegerField(default=0) template <td> {% for damage in damaged %} {% if damage.product_id == product.id %} {{product.current_quantity}} {% else %} {{ product.quantity }} # else part not working properly. {% endif %} {% endfor %} </td> -
Is there a way to render a formset in Django without for loop?
I'd like to know if there's a way to reference the individual forms of a formset in Django without using a for loop. This is what all the docs search results point to: {% for form in formset %} {{ form }} {% endfor %} I'd like to know if there's anyway to do this: {{ form[0].field }} {{ form[1].field }} {{ form[2].field }} I can't find anything that does it and beginning to think it's not possible. -
Check if key contain text in django with postgres JsonField
I've created the next entries: Dog.objects.create(name='Rufus', data={'F.12': 'labrador'}) Dog.objects.create(name='Firulais', data={'M.34': 'labrador'}) Dog.objects.create(name='Toby', data={'F.14': 'labrador'}) How can I get all entries with keys that contains: 'F.' ? I can do: Dog.objects.filter(data__has_any_keys=['F.12', 'F.14']) But I would like get elements that contains part of keys. -
how to implement vue.js and django
here i am trying to do some simple calculation with vue.js and django but it is not giving me the result i wanted.This vue.js code was doing perfect before implementing in django. Here i made the array in the vue.js dynamic and this is displaying me only the image of the product perfectly but not product.name and product.sell_price and also ' @click.prevent="addToCart(product)" 'this function is not doing anything?? How can i pass the dynamic django variables into the vue.js and use the vue.js calculation here? vue.js <script src="{% static 'js/vue.js' %}"></script> <script type="text/javascript" src="{% static '/js/vue-resource.js' %}"></script> new Vue({ el: '#posApp', data: { total: 0, discount: 0, products: [ {% for product in products %} { "id": {{product.id}}, "name": "{{product.name}}", "image": "/media/{{product.image}}", "price": {{product.sell_price}} }, {% endfor %} ], cart: [], search: "" }, methods: { addToCart: function(product){ var found = false; for (var i = 0; i < this.cart.length; i++){ if (this.cart[i].id === product.id){ this.cart[i].quantity++; found = true; } } if (!found) { this.cart.push({ id: product.id, name: product.name, sell_price: product.sell_price, quantity: 1 }); } this.total += product.sell_price; }, inc: function(item){ item.quantity++; this.total += item.sell_price; }, dec: function(item){ item.quantity--; this.total -= item.sell_price; if (item.quantity <= 0){ var i = this.cart.indexOf(item); … -
Perform arithmetic operation in Jinja2
I want to find the difference between two different values. But, I am getting a Jinja2 error. I am not sure about how to find the difference in this template. I tried using "-" operator but this did not work. So, I used 'sub' to find the difference between actual and predicted score. {% for e in question.essays %} <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{loop.index}}</h3> </div> <div class="panel-body"> <div class="actual-score">Actual score: {% if e.actual_score %} {{e.actual_score|round(1)}}/5{% endif %}</div> <div class="predicted-score">Predicted score: {% if e.predicted_score %}{{e.predicted_score|round(1)}}/5{% endif %}</div> <p class="essay-text">Text: {{e.text}}</p> <div class="diff">Difference: {{ e.actual_score|sub(e.predicted_score)}} </div> </div> I am getting this error: TemplateAssertionError: no filter named 'sub' -
is the best way to regrouping the results and counting them from queryset?
this is my results from my queryset after grouping, i want to regrouping the same value of times and then counting the totals, [{'times': 5, 'total': 1}, {'times': 60, 'total': 1}, {'times': 60, 'total': 1}, {'times': 55, 'total': 1}, {'times': 55, 'total': 1}, {'times': 50, 'total': 1}, {'times': 50, 'total': 1}, {'times': 45, 'total': 1}, {'times': 40, 'total': 2}, {'times': 30, 'total': 1}, {'times': 25, 'total': 1}, {'times': 25, 'total': 1}, {'times': 25, 'total': 1}, {'times': 20, 'total': 1}, {'times': 15, 'total': 1}, {'times': 15, 'total': 1}, {'times': 15, 'total': 2}, {'times': 15, 'total': 1}] i've tried using for in but actually didn't work properly, using Counter unhashable type: 'slice', indices type , etc -
Django Error: The QuerySet value for an exact lookup must be limited to one result using slicing
I'm trying to make records for my database of a web-based course planning application in an institution. My concern is that of not being able to make recordings in the intermediary table resulting from the relation M2M in views.py but it works in shell models.py class Departement(models.Model): code_departement=models.CharField("code du département", max_length=100, unique=True) libelle_departement=models.CharField("Libellé du département", max_length=100) faculte=models.ForeignKey("Faculte", on_delete=models.CASCADE) cursus=models.ManyToManyField("Cursus", through="AvoirCursus") class Cursus(models.Model): code_cursus=models.CharField("Code du cursus", max_length=10, unique=True) libelle_cursus=models.CharField("Libellé du cursus", max_length=100) class AvoirCursus(models.Model): cursus=models.ForeignKey("Cursus", on_delete=models.CASCADE) departement=models.ForeignKey("Departement", on_delete=models.CASCADE) views.py if request.method == 'POST': f=forms.Departement_Form(request.POST) if f.is_valid(): dept=f.save(commit=False) code_departement=f.cleaned_data['code_departement'].upper() dept.code_departement=code_departement cursus=f.cleaned_data['cursus'] dept.save() dept=models.Departement.objects.get(code_departement=code_departement) cursus=models.Cursus.objects.get(code_cursus=cursus) avoircursus=models.AvoirCursus.objects.create(cursus=cursus, departemnent=dept) -
Python: Push Notifications to Node.js Socket.io using Redis PubSub
Now my project use Django as API and NodeJs (SocketIO) as server which require Realtime for pushing Notifications I try pushing Notifications to Node.js Socket.io using Redis PubSub but not success. Please check out my code error: My Python code. I publish to myChannel sample message: def test_vew(request): REDIS_SERVER = redis.Redis(host='localhost', port=6379, db=0) REDIS_SERVER.publish("myChannel", "Demo Message") return Response({ "success": True }, status=200) My NodeJS Code: var app = require('http').createServer() const PORT = process.env.PORT || 3000; var redis = require('redis').createClient(); const server = app.listen(3000, () => console.log('listening on port 3000')) //sockets const io = require('socket.io').listen(app) redis.subscribe('myChannel', (message) => { console.log(`Got message ` + message) }) io.sockets.on("connection", function(socket) { console.log("A User Connected to SocketIO"); redis.on("pmessage", function(pattern, channel, message) { console.log(channel, message); }); }); When I run function in Django, My NodeJS Socket Subcribe can't grab message (Nothing log in console). I dont know the reason. Please help me about this issue! -
django-resized // When upload png file, it's extension changed to .apng
I am using the django-resized package to resize the image. When I upload a PNG file using this package, the extension is changed to apng. I don't want this extension to change.. Other image files are normally uploaded. What should I fix it? Background - django==2.1.5 - django-resized==0.3.9 When use Django's default model.ImageField, the extension of png does not change. # models.py def upload_to(instance, filename): return 'vip/{username}/{filename}'.format( username=instance.whose.whose.username, filename=filename) class VipIndex(models.Model): whose = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='vipindex') main_big_image = ResizedImageField(crop=['middle', 'center'], size=[500, 300], quality=50, blank=True, upload_to=upload_to) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] # forms.py class VipMainForm(forms.ModelForm): class Meta: model = VipIndex fields = ( 'main_big_image', ) def __init__(self, *args, **kwargs): super(VipMainForm, self).__init__(*args, **kwargs) self.fields['main_big_image'].widget.attrs = {'autocomplete': 'off', 'class': 'form-control'} # views.py @login_required def profile_2(request): if request.method == 'POST': form_main = VipMainForm(request.POST, request.FILES) if form_main.is_valid(): nav = form_main.save(commit=False) nav.whose = request.user.profiles nav.save() return redirect('profile_2') else: form_main = VipMainForm() return render(request, 'accounts/profile_2.html', { 'form_main':form_main, }) Are there specific settings to keep the extension of the png file? -
What is the use of related names and through in django models
What is the use of " related names" and "through" in django models? I can see it is being used in many to many field. -
OSError: dlopen() failed to load a library: cairo / cairo-2
i am getting the above OS error when i tried to run the code in visual studio the code was in github https://github.com/shuup/shuup -
Can anyone help using M2M and the template properly?
I need to show the name of menu and the quantity of it. But this webpage doesn't show even when the client's address and their name is working out right. I've got these models in my Django project: class Order(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) address = models.CharField( max_length=100, ) created_at = models.DateTimeField(auto_now_add=True) items = models.ManyToManyField( Menu, through='OrderItem', through_fields=('order', 'menu'), ) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) menu = models.ForeignKey(Menu, on_delete=models.CASCADE) count = models.PositiveSmallIntegerField() and the template page like below. {% for order in order_set %} <tr> <td>{{ order.client.name }}</td> <td>{{ order.address }}</td> <td>{% for item in order.items_set.all %}{{ item }}{% endfor %}</td> <td>{{ order.item_set.all.count }}</td> </tr> {% endfor %} </table> Can anyone help? -
How to load NTU rgbd dataset?
We are working on early action prediction but we are unable to understand the dataset itself NTU rgbd dataset is 1.3 tb.my laptop Hard disk is 931 GB .first problem : how to deal with such a big dataset? Second problem : how to understand dataset? Third problem: how to load dataset ? Thanks for the help -
How can I make unique user "sessions" for my Django web application running on heroku?
I made a web application using Django, that stores information in python arrays that are accessed by the user via the front-end. My problem now is that since I have deployed it via heroku, you can't use the website on more than one device, or else options selected from one device affects the website data for all devices. How would I be able to make it so that user experiences are different / unrelated? How can I alter the views.py (or other components) so that the web application has a "session" for each user? This is for a django web application running on heroku. The application is for my school, and it's akin to a battle-royal type site. Users can select people displayed on the site, which in turn removes them from a python dictionary that's stored in memory and puts them in another dictionary for later. The problem is, if more than one person is using the site at one time, they access the same dictionary. I haven't a clue what to try to solve this. "processor.py" names, accepted = list(), list() # names contains many names of people, accepted is empty def accept_person(person): if person in names: accepted.append(person) … -
Is this the right way to do dependency injection in Django?
I'm trying to inject dependencies into my Django view (controller?). Here's some background. Normally, the urls.py file is what handles the routing. It is usually something like this: urlpatterns = [ path("", views.get_all_posts, name="get_all_posts"), path("<int:post_id>", views.get_post, name="get_post"), path("create", views.create_post, name="create_post"), ] The problem with this, is that once you get to create_post for instance, you might have a dependency on a service that creates posts: # views.py ... def create_post(self): svc = PostCreationService() svc.create_post() This kind of pattern is difficult to test. While I know python testing libraries have tools to mock this sort of thing, I'd rather inject the dependency into the view. Here's what I came up with. A Controller class that has a static method, export(deps) that takes in a list of dependencies and returns a list of url pattern objects: class ApiController(object): @staticmethod def export(**deps): ctrl = ApiController(**deps) return [ path("", ctrl.get_all_posts, name="get_all_posts"), path("<int:post_id>", ctrl.get_post, name="get_post"), path("create", ctrl.create_post, name="create_post"), ] def __init__(self, **deps): self.deps = deps def get_all_posts(): pass ... This looks janky, but I'm not aware of any other way to do what I'm trying to do. The controller needs to return a list of url patterns, and it also needs to take in a … -
Django object that allows a user to see how many times they played a specific track. (Python)
User purchases a unique song. Each time they play the song, their unique song count for that song increases. Does Django allow this? I was told to read the django documentation on foreign keys and m2m using through. I'm not getting the results I want. Would kindly appreciate being pointed i the right direction. class Plays(models.Model): plays = models.IntegerField(default = 0) class Song(models.Model): title = models.CharField(max_length=40) plays = models.ManyToManyField(Plays, through='profile',) def __str__(self): return self.title class profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete = models.CASCADE) ## songs = models.ForeignKey(Song, models.SET_NULL, blank=True,null=True) plays = models.ForeignKey(Plays, models.SET_NULL, blank=True,null=True) I just want the user to see how many times they played a song and be able to change the song count each time by one increment. I want to be able to see u1 = profile.objects.get(user = user) print(u1."Song_One".plays) output 4. (u1."Song_Two".plays) output 1. Have another user u2 do the same thing u2."Song_One".plays output = 10 and etc. I hope I explained this correctly.