Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting total pv created for all of User's Django
I have a simple models: class Pv(models.Model): accounts =( ('Sub CF','Sub CF'), ('Special','Special'), ('Directors','Directors'), ('Operations','Operations'), ('LSGDP','LSGDP'), ('DWAP','DWAP'), ('Capacity(USD)','Capacity(USD)') ) acc =( ('Yes','Yes'), ('No', 'No') ) source =( ('GOG','GOG'), ('Others', 'Others') ) pv =( ('General','General'), ('Honorarium','Honorarium') ) center=( ('Cost Center 1','Cost Center 1'), ('Cost Center 2','Cost Center 2'), ('Cost Center 3','Cost Center 3'), ('Cost Center 4','Cost Center 4'), ('Cost Center 5','Cost Center 5') ) stat =( ('Completed','Completed'), ('Returned','Returned'), ('Cancelled','Cancelled') ) IA_System_Code = models.AutoField(primary_key = True) IA_code = models.CharField(max_length = 150) Date_recieved = models.DateField() Pv_reference = models.CharField(unique = True, max_length = 120) Source_of_Funding = models.CharField(max_length=50, choices = source) Cost_center = models.CharField(max_length=50, choices = center) Payee = models.CharField(max_length=500) Description = models.CharField(max_length = 500) Account_code = models.CharField(max_length=350) Gross_amount = models.DecimalField(max_digits=19, decimal_places=2) Withholding_tax = models.DecimalField(max_digits=19, decimal_places=2) Net_amount = models.DecimalField(max_digits=19, decimal_places=2) Status = models.CharField(max_length = 60, choices = stat ) Remarks =models.CharField(max_length = 500, blank = True) Acc_Impress = models.CharField(max_length = 350,choices=acc) Date_returned =models.DateField(null=True,blank = True) Type_of_accounts= models.CharField(max_length = 100, choices = accounts) Type_of_pv = models.CharField(max_length = 20, choices = pv) returned_to_chest = models.DecimalField(max_digits=19, decimal_places=2) created = models.DateTimeField(null=True) created_by = models.ForeignKey('auth.User', blank=True, null=True, default=None,on_delete=models.CASCADE,related_name='create') modified = models.DateTimeField(null=True) modified_by = models.ForeignKey('auth.User', blank=True, null=True,default=None ,on_delete=models.CASCADE,related_name='modified') class Meta(): ordering = ["IA_System_Code"] def __str__(self): return self.Description def save(self, *args, **kwargs): … -
Is there any way to use ansible python api in django web app?
I want to use Ansible Python API in django app to create and execute playbooks dynamically. I already tried Ansible Python API example in a view of my django app but the local server running the app is not able to import the 'ansible' package. File view.py from django.shortcuts import render from ansible.module_utils.common.collections import ImmutableDict from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager Terminal Output -
request.data in DRF v/s serializers.data in DRF
What is the difference between request.data in DRF and serializers.data in DRF. When I write function based view in DRF, I use both of them like - elif request.method == 'POST': serializer = datesSerializer(data=request.data) if serializer.is_valid(): serializer.save() and, startdate = serializer.data['startdate'] enddate = serializer.data['enddate'] But couldn't find the difference about them and difference on using them in the code. -
How would I render a Boolean field into a template with each radio choice
As said, how would I render a Boolean field into a template with each radio choice rendering separately for which I can have a control over every individual choices. This is what had been done so far. models.py First = 0 Business = 1 Economy = 2 CLASS = ( ('First', 'First'), ('Business', 'Business'), ('Economy', 'Economy'), ) class Lead(models.Model): .... class_type = models.BooleanField(null=True, blank=True, choices = CLASS) form.py class Lead_form(ModelForm): class Meta: model = Lead fields = ['class_type'] widgets = { ... 'class_type' : forms.RadioSelect( attrs={'class': 'form-control', 'name': 'ClasstypeRadios' }), ... } html <div class="col-md-6"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Class Type</label> <div class="col-sm-4"> <div class="form-check"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="ClasstypeRadios" id="ClasstypeRadios1" value="0" checked=""> First<i class="input-helper"></i> </label> </div> </div> <div class="col-sm-5"> <div class="form-check"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="ClasstypeRadios" id="ClasstypeRadios2" value="1"> Business <i class="input-helper"></i> </label> </div> </div> </div> </div> .... This is so far I've tried but there is still something missing. As can be seen, the radio buttons are dealing differently but not as a "li" tag which is the default way to render by django into templates via {{ form.class_type }} but rather, I would like to render them individually to have a control over every one … -
Url for swagger in django
urls.py from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title="XYZ") urlpatterns = [ path('api_doc/', schema_view), path('admin/', admin.site.urls), # regex for swagger creation path('?tag={id}&order_by={name}', views.QuestionList.as_view()), #url in swagger path('', views.QuestionList.as_view()) I am trying it in swagger and i am getting 404 response, what will be right url to get the response ? -
Kubernetes Pod communication through services
In the case that an app and database are in different containers/pods (each a separate deployment yaml) how do you get them to communicate? For example, a Django app requires the host name of the database in it's config/environment variables (along with the database name and a few other things) in order to connect to the database. You should be able to specify the service as follows (assuming the database has a service called db-service in the default namespace): Inside Django app demployment.yaml file: env: - name: SQL_HOST value: "db-service.default" or you could do some hackery with the HOSTNAME for the database container (if it's similar to the app name) for example: Inside Django app demployment.yaml file: env: - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: SQL_HOST value: $(POD_NAME)-db Inside Postgres demployment.yaml file: spec: replicas: 1 selector: matchLabels: app: sitename-db-container template: metadata: labels: app: sitename-db-container spec: hostname: sitename-db But what happens when you have multiple deployments inside a service for the same app (each having their app - database container pair)? How will the service know which app pod will communicate with what database pod? Does there now need to be a separate service for every app and database … -
How to display a message to the user when the website is loaded by clicking the hyperlink provided in email is clicked
Hi I have the code below: view.py try: url = "associateid="+assoc_id+"&quarter="+quarter+"&manager="+mgr_id #print(url) encoded=base64.b64encode(bytes(str(url),'utf-8')) urle = 'http://localhost:8000/index/file?enc_url='+encoded.decode("utf-8") #print(urle) vals = {'emailapproved':str(urle)} response_dict["data"].append(vals) except Exception as e: print(str(e)) index.html <table border='0' cellspacing='0' cellpadding='2'> <tr><td ><a href="{{emailapproved}}" target="blank" id="accessLink"> Click here To launch the webpage</a><font color='#0d94d2'></font></td></tr></table> How to display a message when the user clicks on the link which is provided in the email and once the website launches. Thanks for the help in advance! -
In Django 2.2.4, can hyperlinked model serializer generate https URLs instead of http?
I am using hyperlinked model serializer. It only generating http url. But I want to generate https urls. How to achieve this?Is it possible to do that? I have tried including below config in my settings.py. SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Security middleware is also there. Still getting error- blocked mixed content because of insecure http over https. Kindly let me know. Thank you -
django.db.utils.ProgrammingError: type "raster" does not exist
my models: I have created 3 models here and When I migrate then I get the error. from django.contrib.gis.db import models from django.contrib.gis.db.models.fields import RasterField class WorldBorder(models.Model): # Regular Django fields corresponding to the attributes in the # world borders shapefile. name = models.CharField(max_length=50) area = models.IntegerField() pop2005 = models.IntegerField('Population 2005') fips = models.CharField('FIPS Code', max_length=2) iso2 = models.CharField('2 Digit ISO', max_length=2) iso3 = models.CharField('3 Digit ISO', max_length=3) un = models.IntegerField('United Nations Code') region = models.IntegerField('Region Code') subregion = models.IntegerField('Sub-Region Code') lon = models.FloatField() lat = models.FloatField() # GeoDjango-specific: a geometry field (MultiPolygonField) mpoly = models.MultiPolygonField() # Returns the string representation of the model. def __str__(self): return self.name class Zipcode(models.Model): code = models.CharField(max_length=5) poly= models.PolygonField() class Elevation(models.Model): name = models.CharField(max_length=100,blank=True, null=True) rast = RasterField(srid=2346) my settings .. The database I used is Postgres so that I can use postgis for geodjango DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "django_course", "USER": "postgres", "PASSWORD": "**************", "HOST": "localhost", "PORT": "5432", } } -
Filtering Prefetch object using OuterRef and SubQuery
Background Let say I have this kind of structure: models.py class Location(models.Model): pass class Service(models.Model): location = models.ForeignKey(Location, related_name="services",on_delete=models.CASCADE) class Staff(models.Model): service = models.ForeignKey(Service, related_name="staffs",on_delete=models.CASCADE) class Performance(models.Model): content = models.CharField("content", max_lenght=50) staff=models.ForeignKey(Staff, related_name="performances",on_delete=models.CASCADE) @property def location(self): return self.staff.service.location I want to expose my data through a rest API. serializers.py class StaffSerializer(serializers.ModelSerializer): class Meta: model = Staff fields = ['id', 'service'] class ServiceSerializer(serializers.ModelSerializer): staffs = StaffSerializer(many=True) class Meta: model = Service fields = ['id', 'staffs'] class LocationSerializer(serializers.ModelSerializer): services = ServiceSerializer(many=True) class Meta: model = Location fields = ['id',] Data structure So... a serialized Location instance will look like: { "id":"some_location_id", "services":[ { "id":"some_service", "staffs":[ {"id":"some_staff_id"}, {"id":"some_other_staff_id"} ] } // ... Repeated for eah services ] } Now, for some reason, I need to expose Performance data through a scheme which looks like: { "id":"some_perfomance_id", "content":"Foo", "location":{ "id":"performance_staff__service__location_id", "services":[ { "id":"performance_staff__service_id", "staffs":[ {"id":"performance_staff_id"} // ... Only one staff! ] } // ... Only one service! ] } } Investigated solutions I did manage to make this work tweaking around serializers and passing data through some private attributes, but I expect some really odd behaviors. What I'm looking for is a way to do this using Prefetch managers.py Focusing "only" on services first, … -
'Template' object has no attribute 'replace'
Whenever I run the code, error is show: 'Template' object has no attribute 'replace' I am unsure how to fix this. Error show problem line is: html_result = render_template(template, {"itest": item.cart,},) and return Template(value.replace("[[", "{{").replace("]]", "}}")).render( Context(context) ) My code: utils.py def render_template(value, context): return Template(value.replace("[[", "{{").replace("]]", "}}")).render( Context(context) ) My code: views.py def ticket_print(request, cartitem_id): item = get_object_or_404(CartItem, object_id=cartitem_id) template = get_template("user/ticket_print.html") html_result = render_template(template, {"itest": item.cart,},) return html_to_pdf(html_result, name=f"Ticket_Print{item}") Any help would be nice. Thanks! -
ImportError: No module named dm.xmlsec.binding
I am trying to implement SAML2.0 in my django(version 1.7) application in Python 2.7 by using oneLogin python-saml library (https://github.com/onelogin/python-saml), but I am getting an error mentioned below: import dm.xmlsec.binding as xmlsec ImportError: No module named dm.xmlsec.binding When I tried to install this specific library on my machine I am geting below error: Collecting dm.xmlsec.binding Using cached https://files.pythonhosted.org/packages/56/30/7d19e02398b46593c7a72589c767c50f1ff4a96845f5bc6c61c3183fb213/dm.xmlsec.binding-2.0.tar.gz Complete output from command python setup.py egg_info: Error: cannot get XMLSec1 pre-processor and compiler flags; do you have the `libxmlsec1` development package installed? ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-W3sKpb/dm.xmlsec.binding/ Please, let me know what libraries should I use to implement SAML2 in python2. Thanks in advance. -
Django Testing Tools
I am a Django starter and after having finished some books and video/text tutorials, I got a question: What is the best testing tool for Django? The question arose because many sources use different technologies: some use a pytest with pytest-django and others use native django.test module and so on. I wandered about in search of the answer on the internet, but got stuck - most of answers are out-dated. So I decided to ask it here :). What testing tools do you use? What is the advantage of one over others? -
Time series graph data
I am task with creating a function that fetches and return data to be consumed by a time series graph, all the required data is stored on a single model. Currently my function will query and fetch data based on the set dates, Then call a function at the end to group repititive data below are the two separate functions def get_system_endpoint_response_time(system_id, start_date, end_date): """ Returns the response time of every endpoint for a specific system @param end_date: End date of the period of which the data is to be extracted @type:str @param start_date: Start point of the data to be presented @type: str @param: system_id: Id of the system @type system_id: str @return: Response code indicating status and response time graph data """ try: system = SystemService().get(pk = system_id, state__name = 'Active') if not system: return {'code': '800.400.200'} now = timezone.now() start_date = dateutil.parser.parse(start_date) end_date = dateutil.parser.parse(end_date) period = start_date - end_date labels = [] label = [] dataset = [] if period.days <= 31: for i in range(0, 31): current_day = now - timedelta(days = i, hours = 0, minutes = 0) past_day = current_day + timedelta(days = 1) response_times = list(SystemMonitorService().filter( system = system, date_created__lte = past_day, … -
DjangoRestFramework_JWT
I created this custom jwt_payload_handler for jwt so that it can be password aware. If a user changes their password, I want previous tokens to expire. But even though I have a custom handler, for some reason drf jwt ignores the changes and still accepts past tokens after I change the user password or change the password_last_change string value. Am I missing another configuration? jwt_payload_handler: def jwt_payload_handler(user): username_field = get_username_field() username = get_username(user) password_last_change = user.password_last_change # getting json not serializable error. constant string for now warnings.warn( 'The following fields will be removed in the future: ' '`email` and `user_id`. ', DeprecationWarning ) payload = { 'user_id': user.pk, 'username': username, 'password': user.password, 'exp': (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA) , 'password_last_change': 'test1', } if hasattr(user, 'email'): payload['email'] = user.email if isinstance(user.pk, uuid.UUID): payload['user_id'] = str(user.pk) payload[username_field] = username # Include original issued at time for a brand new token, # to allow token refresh if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) if api_settings.JWT_AUDIENCE is not None: payload['aud'] = api_settings.JWT_AUDIENCE if api_settings.JWT_ISSUER is not None: payload['iss'] = api_settings.JWT_ISSUER return payload -
How to change nested serializer based on DEBUG?
I have nested serializer like this class UserProfileSerializer(...): image1 = ImageSerializer() image2 = ImageSerializer() image3 = ImageSerializer() When I need to comply with ISO and my feature is carrying on sensitive data So I have to use short term MEDIA_URL. The solution is here Problem: I use DEBUG=True to do local development and serializer is using one another nested class Question: 1. What is the best practice to change nested serializer based on settings.DEBUG? Workaround: Refactor with Mixin and use .get_serializer_class in the ViewSet to pick serializer_class based on DEBUG value -
Time Series as a Django Model
I'm pretty new to Django and its Rest Framework. I have that an api (third party) that output this pandas dataframe. I understand that I have to do a Many-to-One relationship for my models. The first model is just a list of all stocks and the second model should be the one holding the prices history (linked by a Foreign Key). How can I model the second table to store this data? Date 2019-12-30 291.519989 2019-12-31 293.649994 2020-01-02 300.350006 2020-01-03 297.429993 2020-01-06 299.799988 2020-01-07 298.390015 2020-01-08 303.190002 2020-01-09 309.630005 2020-01-10 310.329987 -
How to access Many-to-Many field data?
I have the following models: class Work_Music(MPTTModel, Work): name = models.CharField(max_length=10, null=True, blank=True) key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) class WorkCast(models.Model): work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT) cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True) order = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True) class Cast(models.Model): name = models.CharField(max_length=100, null=True, blank=True) In view.py, I send the following in template context: work_cast = WorkCast.objects.get(work=self.kwargs['pk']) How do I display in the template, Cast #1, Cast #2, Cast #3, Cast #4 How to I grab all of the cast members? Is it? work.cast.cast.all() doesn't yield any output. How do I display it as a list with commas in between? -
Successful Django Deploy Through AWS Elastic Beanstalk, But Getting 500 ERROR
I've been stuck on this for the last week and I'm fairly lost as to what do for next steps. I have a Django application that uses a MySQL database. I've deployed it using AWS Elastic Beanstalk using the following tutorial : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html It successfully deployed. However, I keep getting 500 errors when trying to access the site. I've also updated the host value as well. Here's the error_log, but I'm not able to deduce much from it. [Tue Jan 28 08:05:34.444677 2020] [suexec:notice] [pid 3125] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Tue Jan 28 08:05:34.460731 2020] [http2:warn] [pid 3125] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Tue Jan 28 08:05:34.460743 2020] [http2:warn] [pid 3125] AH02951: mod_ssl does not seem to be enabled [Tue Jan 28 08:05:34.461206 2020] [lbmethod_heartbeat:notice] [pid 3125] AH02282: No slotmem from mod_heartmonitor [Tue Jan 28 08:05:34.461249 2020] [:warn] [pid 3125] mod_wsgi: Compiled for Python/3.6.2. [Tue Jan 28 08:05:34.461253 2020] … -
Bitbucket error logs when trying to git push
Trying to push new changes to Bitbucket and suddenly I received this error. The push was successful though. I was initially confused if the error came from my code since I also used Django, and was paranoid of some weird rare cases that I don't know. But thought at the same time that it's totally different stuff that would not be possible to cross paths. So I guess there was an error in Bitbucket internally? I was just surprised users are able to see their error logs. -
Django App Failing Trying To Use S3 Boto Storage
I am trying to use the s3 boto storage. I have downloaded what needed to be downloaded: boto3 django-storages The AWS credentials I am using in my settings.py file look like the following: AWS_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY') AWS_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME=os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Now I know it is that last line that is causing the problem because I have run it with each line commented out, uncommenting them, one at a time. All the lines 'AWS' uncommented, the app ran fine. As soon as I uncommented that last line 'DEFAULT_FILE_STORAGE', the app crashed. And I got the following error: ValueError at /auctionitem/auctionitem/22/ Required parameter name not set Request Method: GET Request URL: http://localhost:8000/auctionitem/auctionitem/22/ Django Version: 3.0.1 Exception Type: ValueError Exception Value: Required parameter name not set Exception Location: C:\Users\Sir Chris Mazzochi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\boto3\resources\base.py in __init__, line 118 Python Executable: C:\Users\Sir Chris Mazzochi\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.1 Python Path: ['C:\\Users\\Sir Chris Mazzochi\\Desktop\\mazzo_django_app', 'C:\\Users\\Sir Chris ' 'Mazzochi\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\Sir Chris ' 'Mazzochi\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\Sir Chris ' 'Mazzochi\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\Sir Chris Mazzochi\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\Sir Chris ' 'Mazzochi\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages'] What's wrong with that default storage line? Thanks, Ironman -
How to add the feature to display video formats with the resolution of user's choice to download
The below code is in views.py .I want to take a variable from the user instead of the '360p' after user pastes the video link. Is there a way to show how to get the resolution from the user.I have to take input from the user. The full code looks something like the below webpage https://www.hexascholars.com/code-snippet/youtube-video-download-using-django-and-python/ def get_download(request): if request.method == 'GET': if(request.GET.get('url')): url = request.GET['url'] try: yt = YouTube(url) title = yt.title stream = yt.streams.filter(res='360p').first() path = download_path() stream.download(path) message = "Download Complete!" video = Video()``` -
Editing django-rest-auth verify email template
Good day, for the past 3 days I have been trying to figure out how to edit the verify email that I get and apply some styling and it hasn't been successful one bit. Please, can anyone share a detailed description of how they have solved this issue? The posts of this on other stack overflow posts have not been successful, and I doubt it will be okay just directly going to edit the allauth installed files. -
Is there a way I can update a detail view for Django dymanically once I make a change to the model outside of views.py?
Here is what I have currently. views.py class MultipleModelView(generic.TemplateView): template_name = 'upload/home.html' # @login_required(redirect_field_name='notloggedin.html') def get_context_data(self, **kwargs): if self.request.user.is_authenticated: context = super(MultipleModelView, self).get_context_data(**kwargs) context['jobs'] = Job.objects.filter(author=self.request.user).order_by('-created_at') context['posts'] = devpost.objects.all().order_by('-created_at') context['subcounter'] = SubCounter() context['inprogcounter'] = InProgCounter() context['fincounter'] = FinCounter() return context else: context = super(MultipleModelView, self).get_context_data(**kwargs) # context['jobs'] = Job.objects.filter(author=self.request.user).order_by('-created_at') context['posts'] = devpost.objects.all().order_by('-created_at') return context class PostCreateView(LoginRequiredMixin,generic.CreateView): model = Job fields = ['patient_name', 'location'] def form_valid(self, form): form.instance.author = self.request.user id = randomStringDigits(5) form.instance.identifier = id sleepy.delay(id=id) return super().form_valid(form) The reason why it looks like this is because I have a page where I have multiple models on it. The job model is updated in this file once it is created. tasks.py @shared_task def sleepy(id=None): MyModel = apps.get_model('upload','Job') working_with = MyModel.objects.get(identifier=id) working_with.status = "In Progress" sleep(30) working_with.status = "Finished" return None Essentially, once a user makes a post, it gets sent to an asynchronous task where I change an attribute in the model. The model is updated properly, but I want the detail view to change once the database updates. Is this possible? -
Django multiple Project using same database tables
I've been reading through related articles regarding using same database for multiple django projects however, I have not been able to come up with a fix yet. I've tried relative and absolute pathing when importing but it gives "attempted relative import beyond top-level package" error when I try to access parent directory. Project 1 gets the users to write to database by filling in a form and Project 2 retrieves data written in by users from database. I'm using Postgresql for database. I've tried writing exactly same models.py for both projects but it seems like in database they appear as separate relations/tables. E.g. for table named school in both models.py, it would look like project1_school and project2_school in Postgres database. Is there a way to write to and read from same tables of same database? Thank you so much in advance.