Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Difference between cached session vs simple cache?
I have a Django application using Redis as a cached session backend (not persistent). If I am say storing only one value in a user's session, is there any storage difference between say - request.session['value'] = value and cache.set(user_identifier, value) apart from timeout/logout? Is there any con in using only cache with keys related to user_identifier vs storing values in user's session? -
How to run two methods inside django models in parallel manner?
I'm incrementing two different fields in User models which are the number of likes given to user's post and number of likes received by the user's post. I did this through adding two methods in class model. It is working when I'm liking other posts but however, if I liked my own post it is not working. Anyone know how to solve this problem? Code snippet for user models class User(models.Model): username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) datetime_joined = models.DateTimeField(auto_now_add=True) num_likes_received = models.IntegerField(default=0) num_dislikes_received = models.IntegerField(default=0) num_likes_given = models.IntegerField(default=0) num_dislikes_given = models.IntegerField(default=0) total_votes = models.IntegerField(default=0) prediction = models.BooleanField(default=True) def add_total_votes(self, vote): self.total_votes += vote self.save() def inc_num_likes_received(self): self.num_likes_received += 1 print("1 like received") self.save() def inc_num_likes_given(self): self.num_likes_given += 1 print("1 like given") self.save() Function for submitting like to certain post and at the same time this is where I executed the created two method from the models. (inc_num_likes_received and inc_num_likes_given) def submit_like(request): User_PK = User.objects.get(username=request.user) User_Give_Like = get_object_or_404(User, pk=User_PK.id) pk = request.POST.get('Status', None) post = get_object_or_404(Post, pk=pk) post.add_num_likes() User_PK_Receive = User.objects.get(id=post.username.id) User_Receive_Like = get_object_or_404(User, pk=User_PK_Receive.id) LikeObject = Likes(username = User_Give_Like, post = post, liked=True, disliked=False) LikeObject.save() User_Give_Like.inc_num_likes_given() User_Receive_Like.inc_num_likes_received() return HttpResponse(200) … -
Implementing filters using dictionary packaging
I am trying to optimize my filter code using dictionary packaging, bt i am getting the following error: filter_queryset() missing 3 required positional arguments: 'industry', 'instructor', and 'mediaType' views.py class CourseList(generics.ListCreateAPIView): serializer_class = CourseSerializer def get_queryset(self): queryset = Course.objects.all() if(self.request.query_params): queryParams = self.request.query_params filterParams= queryParams.dict() queryset = self.filter_queryset(queryset, **filterParams) # if(queryParams.get('industry', None)): # queryset = queryset.filter(industry=queryParams.get('industry', None)) # if(queryParams.get('instructor', None)): # queryset = queryset.filter(instructor=queryParams.get('instructor', None)) # if(queryParams.get('mediaType', None)): # queryset = queryset.filter(course_media__media_type=queryParams.get('mediaType', None)) return queryset def filter_queryset(self, queryset, industry, instructor, mediaType): queryset.filter(industry=industry).filter(instructor=instructor).filter(course_media__media_type=mediaType) return queryset url: http://127.0.0.1:8000/authenticator/course/?industry=IT&instructor=5&mediaType=mp4 What am i missing here, bcoz when i debug into the filter_queryset method i can see that all the the three filter values are being populated well -
How to update status on sub section of django template
I have django app where user need to select some options, based on selected options there is flow broadly includes 3 steps including running some exe, comparing and finally we render a page with result table. I need to update the status of each stage completed on django template /frontend view till we complete all stages and print result table. Execution of above steps happen of submit button and currently till we have final results it stays on same page. -
celery error in connection with postgresql while django can
i used celery in my django project .django can connect with postgresql well but it's seem that celery can't connect to postgresql : Traceback (most recent call last): File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/classgram/www/env/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "hamclassy" FATAL: password authentication failed for user "hamclassy" i'm working on host now and host OS is Ubuntu 18.04 . thank you -
Reverse for 'index' not found. 'index' is not a valid view function or pattern name. PasswordChangeView and PasswordChangeForm
I am trying to implement a functionality of changing the password of the current user in Django . But no matter what I use, I always get this everse for 'index' not found. 'index' is not a valid view function or pattern name error and a Template showing these lines of codes. Error during template rendering In template /home/squad-minds/PycharmProjects/squad-services/Admin_interface/venv/lib/python3.7/site-packages/django/contrib/admin/templates/admin/base.html, error at line 3 1 {% load i18n static %}<!DOCTYPE html> 2 {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> 4 <head> where }" {% if LANGUAGE_BIDI is in Red Colour. I have implemented this using the CBV from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class PasswordChange(UserPassesTestMixin, PasswordChangeView): form_class = PasswordChangeForm success_url = '/' def test_func(self): return self.request.user.is_superuser path('password/change', views.PasswordChange.as_view(), name='change_password'), What is this Index thing and why am I getting this? -
How to add value in db django?
I'm writing a new application,where in standart Djangos table auth_user i need to add new value in column. I would like to ask how i can make it? views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] money = 0 user = authenticate(username=username, password=password,money=money) login(request, user) return redirect('index') else: form = UserCreationForm() context = {'form' : form} return render(request, 'registration/register.html',context) for example here i woulf like to add 5 in new column money of table auth_user -
How to add object level permission in django admin
I have a Building model and in that i have a field notes which has GenericRelation to GeneralNote. In Building admin added GeneralNotes as Inlines. Now I want that the GeneralNotes is editable for the user who is owner of general note. class Building(TimeStampedModel): name = models.CharField( unique=True, max_length=100, verbose_name=_("Building Name"), help_text=_("This is the name of your building") ) notes = GenericRelation(GeneralNote) class GeneralNote(TimeStampedModel): owner = models.ForeignKey( CompanyEmployee, blank=True, null=True, # related_name='noteOwner', on_delete=models.SET_NULL, verbose_name="Note Owner", ) content = models.TextField(max_length=400, null=True ) date_of_action = models.DateField(null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() attached_to = GenericForeignKey() In admin.py class BuildingAdmin(ImportMixin, GeneralNotesIncludedAdmin): inlines = (GeneralNoteInLine,) class GeneralNotesIncludedAdmin(CoreBaseAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: if not instance.owner: instance.owner = request.user.companyemployee instance.save() super().save_formset(request, form, formset, change) class CoreBaseAdmin(admin.ModelAdmin): save_on_top = True -
How to call a class based generic API view from a custom function based view
I am having some problems and doubts about how to call my own API within my app. So I have an API to which I can send data. What I want to do in a different view is calling this sent data so I can visualize it in a template. First I was trying to call the API with the library requests inside of my view. Even though that works I am having problems with authentication. So I was thinking I could call my class based API view from my custom function based view. But I don't know if that is possible, nor do I know if that is recommendable. I was also thinking that it might be better to do that with javascript? I don't know.... So my question is twofold: a) What is the best practice to call an API view/get API data from my own app so that I can manipulate and visualize it b) If this is good practice, how can I call my class based generic API view from my custom function based view? Here is what I am trying so far: my generic view class BuildingGroupRetrieveAPIView(RetrieveAPIView): """Retrieve detail view API. Display all information on … -
can i start to learn flask or Django after python learnt python basics?
I learnt python basics but still, I can't solve problems and exercises which r given in tutorials. I want to make a website. so is it ok to start to learn flask or Django after knowing some basic of python? -
error when rendering through get_object_or_404 django
The following code in my views.py throws an error if I don't use "else" conditional statement specifying "detail = None" Is there any better way to simplify the code without using "else" statement? (just in case you don't understand the structure of my app, it only has detail, and list templates. list.html only shows the list of name record in model, and detail only shows the each name in detail page.) def SimpleView(request, sluggy=None): s = Simple.objects.all() if sluggy: detail = get_object_or_404(Simple, slug=sluggy) else: detail=None return render(request,'simple_app/list.html',{'s':s,'d':detail}) def detaily(request,sluggy): sluggys = get_object_or_404(Simple,slug=sluggy) return render(request, 'simple_app/detail.html',{'sluggy':sluggys}) -
Python: How to pass command-line arg as string instead of tuple?
In my Django site, I'm writing a management command to generate sample data in fixtures for all models, or the specified model. The first (and only) positional arg should specify the app.model to process, or "all" to do all models. The problem I'm having is that the arg is a tuple, and when I print it, it shows individual characters as each element of the tuple. Here's my code (as far as showing the arg): def add_arguments(self, parser): parser.add_argument( 'args', type=str, metavar='app.model', nargs='?', default='all', help='Model in the form: app.model (example: clients.client)') def handle(self, *args, **kwargs): self.model = args print('args-type:', type(args)) print('model-type:', type(self.model)) print('model:', self.model) Note that I've specified type=str as an add_argument option. When I try this command line: docker-compose exec api python manage.py gen_fixtures ...I get this output: args-type: <class 'tuple'> model-type: <class 'tuple'> model: ('a', 'l', 'l') It's the same if I specify "all" on the command line. And if I try this one: docker-compose exec api python manage.py gen_fixtures clients.client ...I get this output: args-type: <class 'tuple'> model-type: <class 'tuple'> model: ('c', 'l', 'i', 'e', 'n', 't', 's', '.', 'c', 'l', 'i', 'e', 'n', 't') I know that if I'm initializing a tuple in my code with … -
How to show balance to user in html page which is saved in database?
I have given balance to each user who have signed up and saved that balance in database but I am not able to show them in html page. Maybe I have made some mistakes in python files also. In views.py I have commented some code values which I used also but still didn't get the results. How to do it? models.py class Payment(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py from django.db.models import Sum from decimal import Decimal def payment(request): total_amount = Payment.objects.filter( owner=request.user) # ).aggregate( # total_amount=Sum('amount') # )['total_amount'] or Decimal('0.00') for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'index.html', context) HTML page <li style="float: right;">Your Balance: Rs. {{total_amount}}</li> Python Shell >>> from users.models import Payment >>> Payment.objects.all() <QuerySet [<Payment: Payment object (1)>, <Payment: Payment object (2)>]> Images of database which contains content https://ibb.co/481nzqv https://ibb.co/B4M1NTk -
how to insert multiple record in Django admin model
I want to insert multiple records of student marks but, Django provides by default one by one student insert marks. class ODE_Registation_Model(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) subject = models.ForeignKey(SubjectMaster,on_delete=models.CASCADE) ode = models.ForeignKey(ODE_List_Model,on_delete = models.CASCADE,verbose_name="which ode") exam_date = models.DateField() registration_date = models.DateField() def __str__(self): return self.student.username class ODE_Marks_Model(models.Model): ode_registered = models.OneToOneField(ODE_Registation_Model,on_delete=models.CASCADE) marks = models.SmallIntegerField() verified_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return str(self.marks) my expectation: display all student name and marks(as input field) which are a register in "ODE_Registation_Model" ie:- student marks stu1 [input type=number] stu2 [input type=number] stu3 [input type=number] ... ... -
How to debug scrapy using django-item in vscode?
I am going to debug the scrapy in vscode. So I made the runner.py file. runner.py import scrapy from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from sports_scrapy.spiders.player_spider import AtpPlayerSpider process = CrawlerProcess(get_project_settings()) process.crawl(AtpPlayerSpider) process.start() # the script will block here until the crawling is finished And here is items.py import scrapy from scrapy_djangoitem import DjangoItem from players.models import ATPPlayer class AtpPlayerItem(DjangoItem): django_model = ATPPlayer pipline.py from players.models import ATPPlayer class AtpPlayerScrapyPipeline(object): def process_item(self, item, spider): try: player = ATPPlayer.objects.get(name=item["name"]) print (player.name + " already exist") return item except ATPPlayer.DoesNotExist: pass item.save() return item I added following code to settings.py ort os import sys import django sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "..")) sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "..")) os.environ['DJANGO_SETTINGS_MODULE'] = 'betting.settings' django.setup() ANd here is player_spider.py import scrapy import re from sports_scrapy.items import AtpPlayerItem #Beatiful Soup - To parse the html from bs4 import BeautifulSoup from time import sleep import time class AtpPlayerSpider(scrapy.Spider): name = 'atpplayers' start_urls = [ 'https://live-tennis.eu/fr/classement-atp-live', ] def parse(self, response): player_rows = response.xpath('//table[@id="u868"]/tbody/tr[@bgcolor and @class]') for player_item in player_rows: #rank rank_txt = player_item.xpath('./td[1]/text()').extract_first().strip() if rank_txt == '': rank = 1000 else: rank = int(player_item.xpath('./td[1]/text()').extract_first().strip(), 10) #max_rank mc = player_item.xpath('./td[2]/b[2]/text()').extract_first().strip() if bool(re.match('^(?=.*[a-zA-Z-])', mc)) != True: max_rank = int(mc,10) elif mc.find('CH') != -1 or mc.find('MC') … -
Getting Pylint Error For No Reason: invalid syntax (<unknown>, line 59)
Trying to define a clear method for my shopping cart app. But I am getting this error for no reason. My code seems ok. This is where I am getting the error. On commenting this line, the error moves to the next line which is blank def clear(self): del self.session[settings.CART_SESSION_ID]self.session.modified = True The error is invalid syntax (<unknown>, line 59) My whole code: from django.conf import settings from ecom.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # update the session cart self.session[settings.CART_SESSION_ID] = self.cart # mark the session as "modified" to make sure it is saved self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart.session[product_id] self.save() #iterate over cart items and add them from database def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in … -
Turn on webcam at client side and process the captured image(django)
I am working on a django web application and I want to add a function to scan barcode using webcam. I tried using openCv together with pyzbar to scan barcode but the problem is it only works on the localhost computer. Now i am trying to use html5 getUserMedia to capture the barcode image and send that image to django view function for processing. How can i write the view function and is there a way to detect and process the barcode right away from the webcam livestream using getUserMedia? video.onclick = function() { canvas.width = video.videoWidth; canvas.height = video.videoHeight; img.src = canvas.toDataURL('image/jpeg'); var source = img.src; $.ajax({ url: "{% url 'recordmgnts:barcode_scanner' %}", data: { 'image': source }, success: function(data){ $("#id_container_serial_number").attr("value",data); } }); }; from pyzbar import pyzbar import base64 def barcode_scanner(request): image = request.GET.get('image') #image sent from browser decode_image = base64.b64decode(image) barcode = pyzbar.decode(decode_image) barcode_data = barcode.data.decode("utf-8") return HttpResponse(barcode_data) -
How to create the one to many relationship based file upload using serialization
Only save the Project model fields doesn't create the project documents model fields Models.py class Project(BaseModel): name = models.CharField(max_length=100, blank=True, null=True) class Meta: db_table = 'project_details' ordering = ['is_active'] class ProjectDocuments(BaseModel): file = models.FileField(upload_to="files/%Y/%m/%d") project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='projectdocuments') class Meta: db_table = 'project_document_details' ordering = ['is_active'] views.py: def post(self, request, format=None): user_id = request.user.id current_date = datetime.now() data = copy.deepcopy(request.data) file_fields = list(request.FILES.values()) # list to be passed to the serializer data['is_active'] = True data['created_by'] = user_id data['created_date'] = current_date data['modified_by'] = user_id data['modified_date'] = current_date serializer = ProjectSerializer(data=data, file_fields=file_fields) if serializer.is_valid(): serializer.save() serializer.py: class ProjectSerializer(serializers.ModelSerializer): def init(self, *args, **kwargs): file_fields = kwargs.pop('file_fields', None) super(ProjectSerializer, self).__init__(*args, **kwargs) if file_fields: field_update_dict = {str(field): serializers.FileField(required=False, write_only=True) for field in file_fields} print "FILE UPDATE DICT ------------>",field_update_dict self.fields.update(**field_update_dict) def create(self, validated_data): validated_data_copy = validated_data.copy() validated_files = [] for key, value in validated_data_copy.items(): if isinstance(value, InMemoryUploadedFile): validated_files.append(value) validated_data.pop(key) submission_instance = super(ProjectSerializer, self).create(validated_data) for file in validated_files: ProjectDocuments.objects.create(submission=submission_instance, file=file) return submission_instance class Meta: model = Project fields = '__all__' -
Django intersection based on common field
I have chat and participant models. class Chat(models.Model): ... class Participant(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE, related_name='participants') participant = models.ForeignKey(CustomUser, on_delete=models.CASCADE) ... I'm looking for a way to check if there exists a single chat with two specified users. I can think of doing an intersection of two separate querysets but am unsure how to combine them based on identical chat id. qs = Participant.objects.filter(participant=user_a).intersection(Participant.objects.filter(participant=user_b)) -
Django dev server not recognizing new files after directory modification
I have a Django project with 2 apps and was writing some functions in a utils.py file in one of the apps. I wanted to break this up into two separate files in their own subdirectory so I created a new directory 'utils' a level below the app directory and placed the two utils1.py and utils2.py files in there. I had some issues with importing something from the other app so I ended up scrapping this idea and moving everything back into one file in the base directory of the original app, exactly like it was before. Now when I runserver it is not picking up any new files that are created within apps. Not just the ones that I recreated but any new files. Files that were created prior to the change are running just fine. So, in summary new utils.py files that I recreated in the app directory are not running when the dev server is started, and when I try to run one of them manually they run like any other python file, but imports from other locations in the project are not being recognized. No other changes were made and new files were running perfectly fine … -
Integrating TinyMCE to Django
So i have been trying to use tinymce on my django project but i kept getting: ImportError: cannot import name 'TinyMCE' from 'tinymce' and Cannot find reference TinyMCE in init.py The very few articles online talks about integrating tinymce with django admin but i'm trying to integrate it with my django forms. pip installed django-tinymce ----settings.py---- INSTALLED_APPS = [ 'tinymce',] ----urls.py---- path('tinymce/', include('tinymce.urls')), ---models.py--- from tinymce.models import HTMLField container_description = HTMLField() ----forms.py---- from tinymce import TinyMCE class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class ContainerForm(forms.ModelForm): container_serial_number = forms.CharField(widget=forms.TextInput(attrs= {'placeholder': 'Enter serial number'})) container_description = forms.CharField(required=False, widget=TinyMCEWidget(attrs={'placeholder': 'Enter description'}), max_length=100) Followed instructions online for setting up but i still got ImportError. And what else am i supposed to do to set TinyMCE up? -
Django 4-way join
I'm trying to join tables in Django. These are my models: class Venture(models.Model): tug = models.ForeignKey(TugVessel, on_delete=models.CASCADE) start_port = models.ForeignKey(Port, on_delete=models.CASCADE, related_name='start') end_port = models.ForeignKey(Port, on_delete=models.CASCADE, related_name='end') # more fields class Port(models.Model): lat = models.DecimalField(max_digits=9, decimal_places=6) lon = models.DecimalField(max_digits=9, decimal_places=6) name = models.CharField(max_length=255) class UnmatchedRequest(models.Model): who = models.ForeignKey(CustomUser,on_delete=models.CASCADE) start_lat = models.DecimalField(max_digits=9, decimal_places=6) start_lon = models.DecimalField(max_digits=9, decimal_places=6) end_lat = models.DecimalField(max_digits=9, decimal_places=6) end_lon = models.DecimalField(max_digits=9, decimal_places=6) # more fields Now I want to get all the requests for a user, say where UnmatchedRequest.who = 1, then join twice with the Ports database so I can get the start port and end port, then use that to find a matching venture. I think the SQL query would be: SELECT * FROM Port P1, Port P2, UnmatchedRequest, Venture WHERE UnmatchedRequest=1 AND UnmatchedRequest.start_lat=P1.lat AND UnmatchedRequest.start_lon=P1.lon AND UnmatchedRequest.end_lat=P2.lat AND UnmatchedRequest.end_lon=P2.lon AND P1.id=Venture.start_port AND P2.id=Venture.end_port I was thinking something like this: UnmatchedRequest.objects.get(id=1).filter( start_lat=F('port__lat'), start_lon=F('port__lat'), end_lat=F('port__lat'), end_lon=F('port__lon'), port__id=F('Venture.start_port'), port__id=F('Venture.end_port') ) but I'm not clear on whether each of these ports refer to the same or different tables and I can't seem to find how I could alias them like in the SQL query to have one start port and one end port. Any ideas for how to implement … -
Django datetime strftime() return wrong timezone
I'm current trying to return a DateTimeField format by hour, minutes , second in the model: start = models.DateTimeField(auto_now_add=True) My settings.py: LANGUAGE_CODE = 'vi' TIME_ZONE = 'Asia/Saigon' USE_I18N = True USE_L10N = True USE_TZ = True When i try to format the DateTimeField current_ws.start.strftime('%H:%M:%S') # return 09:34:01 which is a wrong time , the correct should be 16:34:01 How do i fix this ? -
bad interpreter: Permission denied
I can not install psycopg2. I try to change the DB from sqlite to postgesql but get always the same error. I also tried to install it via the project interpreter instead of my terminal but get : python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. (venv) localhost:mysite Sergio$ pip install psycopg2 bash: /Users/Sergio/PycharmProjects/#WE_GRAPPLE/venv/bin/pip: /Users/Sergio/PycharmProjects/#WE_GRAPPLE/venv/bin/python: bad interpreter: Permission denied (venv) localhost:mysite Sergio$ -
Best way to import data into Django
I am currently working on a project for scraping flight data from websites using python and storing that data in a database using Django. I was just wondering what is the best way to take the scraped data and import it into the Django models. thanks in advance for any help.