Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models and UniqueConstraint
That's my first project in Django and all those database modeling are new concept to me. Sorry if i'm all wrong. I did had a previous model that was working. A region has multiple depot, and a depot has multiple route. They are legacy table that I cannot change. class region(models.Model): regionnumber = models.IntegerField(db_column='RegionNumber', primary_key=True) engname = models.CharField(db_column='EngName', max_length=15, blank=True, null=True) def __str__(self): return self.engname class depot(models.Model): region = models.ForeignKey(Tblregionnames, on_delete=models.SET_NULL, null=True) depotcode = models.CharField(db_column='DEPOTCODE', primary_key=True) depotname = models.CharField(db_column='DEPOTNAME', max_length=50, blank=True, null=True) def __str__(self): return self.depotcode + " " + self.depotname class route(models.Model): reg_no = models.ForeignKey(Tblregionnames, on_delete=models.SET_NULL, null=True) off_no = models.ForeignKey(Tbldepotimplementation, on_delete=models.SET_NULL, null=True,) res_route = models.CharField(db_column='res_route', max_length=9) Now I got to add to this model a date to keep track of change in time (ex.: in 2020 some depot will be created or closed, same thing with route in depot). Something like this. class EvaluationDate(models.Model): ev_date = models.DateField(db_column='ev_date', primary_key=True) # Field name made lowercase. def __str__(self): return str(self.ev_date) class region(models.Model): regionnumber = models.IntegerField(db_column='RegionNumber', primary_key=True) engname = models.CharField(db_column='EngName', max_length=15, blank=True, null=True) def __str__(self): return self.engname class depot(models.Model): region = models.ForeignKey(Tblregionnames, on_delete=models.SET_NULL, null=True) depotcode = models.CharField(db_column='DEPOTCODE', max_length=5, blank=True, null=True) # Field name made lowercase. depotname = models.CharField(db_column='DEPOTNAME', max_length=50, blank=True, null=True) eval_date = … -
Send data to a Django view using request
I'm using an ordinary Python script to send a request to a Django view. I would like my view to print the Json data as soon as it is received by the other Python script, but i keep gettin a error. Here is what i tried: This is how i send the request: req = requests.post('http://127.0.0.1:8000/', json={"test": "Ok!"}) And here is what i tried in the view: def TestView(request): data = request.get_json() print(data) return JsonResponse(data) Here is the error i'm getting: 'WSGIRequest' object has no attribute 'get_json'. What is happening here? Am i missing some import? Any advice is appreciated. -
Django - ManyToManyField - Display Admin form
I started to learn Django at school, I have a question about a manytomany relation between two tables. A movie can have more than one review, the admin form only highlighted the reviews both for this record, but I would like to see both content, not as a list with all reviews id. Thanks for your help. class Reviews(models.Model): content = models.TextField(null=True) url = models.TextField(null=True) class Meta: verbose_name = "Critiques" ordering = ['content'] class Movies(models.Model): title = models.CharField(max_length=45) release_date = models.DateField(blank=True, null=True) categories = models.ForeignKey(Categories, on_delete=models.CASCADE) image = models.ImageField(upload_to='bms/photos', null=True) synopsis = models.TextField(blank=True, null=True) duration = models.IntegerField(blank=True, null=True) is_available_in_theaters = models.BooleanField(default=0) reviews_list = models.ManyToManyField(Reviews) Admin form -
Django CKEditor doesnt respond in Jquery form wizard
I want to put my Django CKEditor into jQuery wizard. The problem is that CKEditor Widget doesn't respond. How can I add CKEEditor Widget safely to this wizard? CKEditor respond everywhere on page despite jQuery wizard. This is my template: {% extends 'base.html' %} {% load static %} {% block style %} <link href="{% static '/assets/plugins/jquery-steps/jquery.steps.css' %}" rel="stylesheet"> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> {% endblock %} {% block content %} <!-- Page Content--> <div class="container-fluid"> <!-- Page-Title --> <div class="row"> <div class="col-sm-12"> <div class="page-title-box"> <h4 class="page-title">Stwórz wydarzenie</h4> </div><!--end page-title-box--> </div><!--end col--> </div><!--end row--> <!-- end page title end breadcrumb --> <div class="row"> <div class="col-sm-12"> <div class="card"> <div class="card-body"> <h4 class="mt-0 header-title">Jquery Steps Wizard</h4> <p class="text-muted mb-3">A powerful jQuery wizard plugin that supports accessibility and HTML5</p> <form id="form-horizontal" class="form-horizontal form-wizard-wrapper"> <h3>Company Document</h3> <fieldset> <div class="row"> <div class="col-md-6"> <div class="form-group row"> <label class="col-lg-3 col-form-label">PAN Card</label> <div class="col-lg-9"> {{ form.media }} {{ form.as_p }} </div> </div><!--end form-group--> </div><!--end col--> {% endblock %} {% block scripts %} <script src="{% static '/assets/plugins/jquery-steps/jquery.steps.min.js' %}"></script> <script src="{% static '/assets/pages/jquery.form-wizard.init.js' %}"></script> {% endblock %} -
Configuring a StaticLiveServerTestCase Inside A Docker Container
I am able to spawn a separate live development server process for a selenium test which inherits from LiveServerTestCase with the following - #globals HTTP = "http://" # ip address of host machine on the default docker network LOCALHOST = settings.HOST_LOCALHOST # port number on host the docker selenium remote server is exposed on SEL_PORT = 4444 class SignUpViewFunctionalTests(LiveServerTestCase): port = 9000 host = '0.0.0.0' live_server_url = HTTP + LOCALHOST + ":" + "9000" def setUp(self): settings.DEBUG = True self.driver = webdriver.Remote( HTTP + LOCALHOST + ":" + str(SEL_PORT) + "/wd/hub", DesiredCapabilities.CHROME ) This causes two parallel processes to run in the web docker container; the default, waiting for requests on 0.0.0.0:8000 and the process spawned when running the test which is listening on 0.0.0.0:9000. Via the selenium remote server which I connect to via RealVNC I see the Chrome browser start up at '172.0.17.1:9000/accounts/signup' and during the test everything works fine - the signed up user is created which confirms that the test running process is using a separate test database. The only thing I did notice was my static files weren't pulling through - I was using white-noise locally, which works fine on the default web process waiting … -
why firestore storage is not showing the image when uploading to server python?
My problem is when I upload the image to firestore storage it is getting uploaded but when I open the image its showing 404 error. The requested URL was not found on the server. Below i m attaching the code . Have tried upload_from_file(),upload_from_string(),upload_from_filename() But nothing works. views.py import PIL from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings @login_required def create_event(request): form = EventForm() if request.method == "POST": form = EventForm(request.POST , request.FILES) if form.is_valid(): print("my form dynamic details ", request.POST) print("my files " , request.FILES['cover_image']) path = default_storage.save('tmp/'+request.FILES['cover_image'].name, ContentFile(request.FILES['cover_image'].read())) of = open('media/tmp/'+request.FILES['cover_image'].name, 'rb') print("my of " , of) Have tried all methods below but doesnt work at all . blob = bucket.blob(request.FILES['cover_image'].name) blob.upload_from_file(of, content_type="image/jpeg") # blob.upload_from_string(request.FILES['cover_image'].name, content_type="image/jpeg") # blob.upload_from_filename(filename='media/tmp/'+request.FILES['cover_image'].name) print( "File {} uploaded to {}.".format( request.FILES['cover_image'].name, "jigarfile.jpg" ) ) return redirect('create_event') else: print("my erros ", form.errors) return render(request, 'user/events.html') Below i m attaching the image here is the link to image https://ibb.co/Yk0sWpk -
Displaying information from foreign key relationship to self serializer
I have a model that contains two foreign keys about the same model. It looks like this: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True) parent = models.ForeignKey('self', related_name='parent_comment', on_delete=models.CASCADE, null=True) grandparent = models.ForeignKey('self', related_name='grandparent_comment', on_delete=models.CASCADE, null=True) comment = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) I'd like to create a Comment Serializer that shows parent and grandparent's usernames from the user model. My serializer looks like this: class CommentSerializer(serializers.ModelSerializer): author = UserSerializer(source='user') class Meta: model = Comment fields = '__all__' I know I can do depth=1 however, that will only display user_id and all the other information about the parent and grandparent comment, but the User information about those two fields. How can I do this? -
Running Django tests in Docker Windows
I am trying to run the tests of a Django project inside a container which is running on a Windows host. The problem is that when I run the command: python manage.py test I get the following erros for all my files: myproj/tests/tests_forms/test_product_form.py is executable; skipped I've checked the file permissions and all of them have execute permissions: -rwxr-xr-x. I've tried to change this using chmod, but it doesn't work probably because I am running docker on Windows. Is there a way around this? Maybe some way to force Django to run the tests regardless of the file permissions? -
Best approach for loading settings that can be modified in Flask
Hello all fellow StackOverFlow'ers, I'm making an app in Flask that runs depending on settings that can be changed by administrator via a POST request in their admin-panel, Actually, the only two things I came up with for doing this is using os.environ.get (Environment variables) [which i'm using now] or insert it to a PostreSQL Database config table and load it up Anyway I will be storing settings such as a couple of API_URLs and their API_KEY, and some Conditions of checking like a success value where if condition in text .. else is applied to ... I'm looking for the best performant approach for doing such thing. Best regards. -
Partially Updating the ManytoMany field DjangoRestFramework
I have the following models. Models.py from django.db import models from rest_framework.validators import UniqueValidator import datetime # Create your models here. class Member(models.Model): uin = models.CharField(max_length=9) name = models.CharField(max_length = 15) cardNumber = models.CharField(max_length=55,blank=True) points = models.IntegerField() class Meta: ordering = ['uin'] def __str__(self): return self.uin class Event(models.Model): eventName = models.CharField(max_length=60,blank=True) points = models.IntegerField(default = 0) date = models.DateField( default=datetime.date.today) members = models.ManyToManyField(Member) class Meta: ordering = ['eventName'] def __str__(self): return self.eventName And the following Serializers class MemberSerializer(serializers.ModelSerializer): class Meta: model = Member # validators = UniqueValidator(queryset=) fields = ['name','uin','points','cardNumber'] # overloading to_representation for if you want to add new datafields def to_representation(self, instance): data = super().to_representation(instance) return data class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ['id','eventName','date', 'members','points'] # overloading to_representation for if you want to add new datafields def to_representation(self, instance): data = super().to_representation(instance) return data At a new endpoint, I want the user to give an event id and card number. Given these arguments, I want the api to add this member to the event. I have been able to do this using the django shell using something similar to this: givenId = 1 givenCardNumber = '123439483' # select desired event selectedEvent = Event.objects.filter(id=givenId) selectedMember = … -
Django-celery Results DO not Delete all during backend cleanup
I'm using Django-celery-results as my results backend. I'm running a task every minute. Some of the task ids are saved in one of the other tables(HW) besides the django celery results task table.Between 20-24 tasks ids per day. The celery.backend_cleanup is run every day by celery and it deletes tasks that are over 24 hours when they expire. I have the model on _delete=models.PROTECT. This means that when the celery.backend_cleanup is run there is a Proected_Error and the task stops executing.This means that over 1400 records are not been deleted during cleanup. How can I have celery delete only those records where the foreign key is not contained on another table and pass onto the next record if it finds it in the HW table instead of raising the ProtectedError and completely stopping the process? Models.py class HW(models.Model): name = models.CharField(max_length=255) taskresult = models.ForeigKey( TaskResult, blank=True, null=True, on_delete=models.PROTECT) django.db.models.deletion.ProtectedError: ("Cannot delete some instances of model 'TaskResult' because they are referenced through a protected foreign key... -
Django Rest Framework nested serializer object is null
I have a two model setup using the Django Rest Framework. One model is a nested serializer into another object. One model is Player and the other model is TeamData. I want TeamData to be nested into Player. # models.py from django.db import models class TeamData(models.Model): urlName = models.CharField(max_length=50) city = models.CharField(max_length=50) nickname = models.CharField(max_length=50) tricode = models.CharField(max_length=3) def __str__(self): return self.city class Player(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) jersey = models.CharField(max_length=10) pos = models.CharField(max_length=10) posExpanded = models.CharField(max_length=10) heightFeet = models.CharField(max_length=2) heightInches = models.CharField(max_length=2) weightPounds = models.CharField(max_length=5) personId = models.CharField(max_length=50) teamData = models.ForeignKey( TeamData, on_delete=models.CASCADE, null=True, blank=True) isAllStar = models.BooleanField() orderChar = models.CharField(max_length=1) playerUrl = models.CharField(max_length=50) displayName = models.CharField(max_length=100) #serializer.py from rest_framework import serializers from .models import * class TeamDataSerializer(serializers.ModelSerializer): class Meta: model = TeamData fields = ('id', 'urlName', 'city', 'nickname', 'tricode') class PlayerSerializer(serializers.ModelSerializer): teamData = TeamDataSerializer('teamData') class Meta: model = Player fields = ('id', 'firstName', 'lastName', 'jersey', 'pos', 'posExpanded', 'heightInches', 'weightPounds', 'personId', 'teamData', 'isAllStar', 'orderChar', 'playerUrl', 'displayName') def create(self, validated_data): teamData = validated_data.pop('teamData') player = Player.objects.create(**validated_data) return player #views.py from rest_framework import viewsets from .models import Player, TeamData from rest_framework import viewsets, permissions from .serializers import * class PlayerViewSet(viewsets.ModelViewSet): queryset = Player.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class … -
Installation issues in my virtual environment in CentOS 7
I have a problem with my virtual environment in CentOS 7, when I install the programs I need to work everything seems to be working correctly, even Django runs on the local server, however, I successfully exit the virtual environment and successfully log out of my server and then nothing appears anymore when I log in again, I clarify that I have been using the same user since installation until now, any idea what might be happening ?. Note: I am using a virtual environment, within this virtual environment I have created an alias for python 3.6 to be able to install django 2.2.4. and the rest of the dependencies that I need. -
How to transfer images to Django REST framework applications?
I have learned a few about REST APIs and now while learning, as a practice I am trying to build one using REST framework of Python Django. The difficulty I have faced is that, I cannot make a POST request with images in it from POSTMAN or Curl or any other REST clients. I saw images can be encoded into base64 and then transferred. Unfortunately the internet resources could not help me enough to make me do it on my own. Now can anyone help me and walk out the whole process just to make it easier? Thanks in advance. -
Django SetUpTestData leads to database error with ManyToManyField
I am trying to test a Django application using a test runner. I would like to set up the test data once to run across several different test classes, rather than setting up the same data in each test class. For that reason, I am using setUpTestData() rather than setUp(). The model includes a ManyToManyField to connect collaborators to articles. When I set up a class to test the models using setUpTestData(), I am able to save and retrieve objects from the Collaborator model and the Article model. When I try to save the many-to-many relationship, however, I get an error that the table doesn't exist. How can I set up the test so that I can reuse these data, including the many-to-many relationship. Here is my code: from django.test import TestCase from cv.settings import PUBLICATION_STATUS, STUDENT_LEVELS from cv.models import Article, ArticleAuthorship, Collaborator from tests.cvtest_data import PublicationTestCase class ArticleTestCase(TestCase): """ Run tests of Django-CV :class:`~cv.models.Article` model. """ @classmethod def setUpTestData(cls): # Collaborator cls.col_einstein = Collaborator.objects.create( first_name="Albert", last_name="Einstein", email="ae@example.edu" ) # Article cls.art_gravitation = Article.objects.create( title='On the Generalized Theory of Gravitation', short_title='Generalized Theory of Gravitation', slug='gen-theory-gravitation', pub_date='1950-04-01', status=PUBLICATION_STATUS['PUBLISHED_STATUS'] ) # Authorship: ManyToManyField cls.auth = ArticleAuthorship( article=cls.art_gravitation, collaborator=cls.col_einstein, display_order=1 ) cls.auth.save() def … -
How can I get P5.Sound.js to load raw audio data?
I'm trying to update a song that is played in using the p5.Sound.js library after the file has been successfully added from a django back end. The data that is returned here is the actual file, but I need a path in order to create a sound is P5.js. Is there anyway that I can just make a soundfile using the raw returned data? function keyPressed() { soundobj.stop(); $.ajax( { type:"GET", url: "/change_song", success: function(data) { soundfile = new p5.soundFile() } }); } Here is my code from my django views def change_song_view(request): newSong = Song.objects.get(id=random.randrange(3, 7)) with open(newSong.audio_track.path, 'rb') as f: response = HttpResponse() response.write(f.read()) response['Content-Type'] ='audio/mp3' return HttpResponse(response) -
Django Custom UserModel gives error during password change by superuser i.e user my be deleted
hi every one when ever i click on change password link in admin panel change form it return to home page of admin and showing an info message that user User with ID "1/change/password" doesn't exist. Perhaps it was deleted? i created custom user model and custom admin class for registry like model.py ` class User(AbstractUser): Male = "ML" Female = "FM" Other = "OT" genders = ((Male,"Male"),(Female,"Female"),(Other,"Other")) doc = 'DO' pat = 'PA' types = ( (doc, 'Doctor'), (pat, 'Patient'), ) User_Type= models.CharField(choices=types,max_length=2,default="PA") Address = models.CharField(max_length=100 , default=None,blank=True, null=True) gender = models.CharField(choices=genders,max_length=2,default="ML") birth_date = models.DateField(verbose_name="DOB" ,default=timezone.now) picture = models.ImageField(upload_to="user/",default="user/team1.jpg") twitter = models.CharField(max_length=120, default="www.twitter.com") facebook = models.CharField(max_length=120, default="www.facebook.com") instagram = models.CharField(max_length=120, default="www.instagram.com") phone = models.CharField(max_length=20, blank=True, null=True) Updated_at=models.DateTimeField(verbose_name="Updated" ,auto_now_add=timezone.now) objects=UserManager() def image_tag(self): if self.picture: return mark_safe('<img src="%s" style="width: 45px; height:45px;" />' % self.picture.url) image_tag.short_description = 'Image' ` "admin.py" ` class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField(label="Password",help_text="Raw passwords are not stored,so there is no way to see this user's password, but you can change the password using <a href=\"password/\">this form</a>.") class Meta: model = User fields = '__all__' def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) f = self.fields.get('user_permissions', None) if f is not None: f.queryset = f.queryset.select_related('content_type') def clean_password(self): return self.initial["password"] class UserAdmin(BaseUserAdmin): … -
Cannot resolve keyword 'id' into field. Choices are: address, amount, city, email, items_json, name, order_id etc
I am using with Django 2.1.5 and Python 3.5 I want to add paypal payment gateway integration to my project but i faced this problem Cannot resolve keyword 'id' into field. Choices are: address, amount etc def checkout(request): if request.method == "POST": items_json = request.POST.get('itemsjson', '') name = request.POST.get('name', '') amount = request.POST.get('amount', '') email = request.POST.get('email', '') address = request.POST.get('address1', '') + " " + request.POST.get('address2', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip_code = request.POST.get('zip_code', '') phone = request.POST.get('phone', '') order = Orders(items_json=items_json, name=name, amount=amount, email=email, address=address, city=city, state=state, zip_code=zip_code, phone=phone) order.save() update = OrderUpdate(order_id=order.order_id, update_desc="The order has been placed") update.save() thank = True id = order.order_id return redirect('process_payment') return render(request, 'shop/checkout.html', locals()) def process_payment(request): order_id = request.session.get('order.order_id') order = get_object_or_404(Orders, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': str(amount), 'item_name': name, 'invoice': str(order.order_id), 'currency_code': 'USD', "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('payment_done')), "cancel_return": request.build_absolute_uri(reverse('payment_cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form} return render(request, "shop/process_payment.html", context) -
Change FK and values on deleting of a model - Django
everyone. What I need to do, is: after deleting of a parent model instance, change all 'votes' to 0 and set FK to null, for example. After creating a new parent model, Option fk`s should be equal to parent's id. How to achieve it? Thank you class Author(models.Model): """Model representing an author.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) class Meta: ordering = ['last_name', 'first_name'] def get_absolute_url(self): """Returns the url to access a particular author instance.""" return reverse('catalog:author-detail', args=[str(self.id)]) def __str__(self): """String for representing the Model object.""" return '{0}, {1}'.format(self.last_name, self.first_name) class Option(models.Model): def default_votes(): d=Author.objects.all().first() for a in d.option_set.all(): a.votes=0 a.author_id=0 return d author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=default_votes,null=True) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
Pillow is not installed error even after installation
as per tutorial I am following they ask me install pillow for file upload functionality. so for that I used command: pip install pillow and pytho-m pip install Pillow and both return result: Requirement already satisfied: Pillow in /usr/lib/python3/dist-packages (3.1.2) But when run my local server it shows error in terminal: ERRORS: book.Book.picture: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". I do not understand is pillow install or not. -
Problem with exposing headers in response using django-cors-headers and my own django REST API
I have been fighting my server for 2 days now to figure out how to setup authentication for my website. My set up is as follows: django REST API with django-rest-auth as endpoints for authentication. This connects to my frontend, a vuejs website. I am now in the very early stages of development for this hobby project, that I do to figure out how an django REST API works and how to build a website with vue, so switching any of these frameworks out is not an option for me. The problem I am having is that I can login, I can make GET-requests to protected parts of my API by providing the key that is returned upon making the login request to the django-rest-auth default endpoint. The problem is using the django-rest-auth logout endpoint. It says that I am logged out succesfully, but the server keeps serving me the same key when I login again with the same credentials. I figured out that I need to provide a csrf token to the server if I do a POST request to the API. So far so good. But I cannot retrieve the csrf token the server provides me upon logging … -
Configure .config file for AWS EB SSL
I'm trying to configure my https-instance.config file in .ebextensions for SSL configuration. I've set my custom domain(purchased from GoDaddy) using Route 53 for my AWS Elastic Beanstalk Linux instance. I've hosted my Django app on this. Now, I need to set SSL for my www.domainname.com and domainname.com Here's my https-instance.config code: Resources: sslSecurityGroupIngress: Type: AWS::EC2::SecurityGroupIngress Properties: GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]} IpProtocol: tcp ToPort: 443 FromPort: 443 CidrIp: 0.0.0.0/0 files: /etc/httpd/conf.d/ssl.pre: mode: "000644" owner: root group: root content: | LoadModule ssl_module modules/mod_ssl.so Listen 443 <VirtualHost *:443> <Directory /opt/python/current/app/build/static> Order deny,allow Allow from all </Directory> SSLEngine on SSLCertificateFile "/etc/letsencrypt/live/domainname/fullchain.pem" SSLCertificateKeyFile "/etc/letsencrypt/live/domainname/privkey.pem" SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH SSLProtocol All -SSLv2 -SSLv3 SSLHonorCipherOrder On SSLSessionTickets Off Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload" Header always set X-Frame-Options DENY Header always set X-Content-Type-Options nosniff ProxyPass / http://localhost:80/ retry=0 ProxyPassReverse / http://localhost:80/ ProxyPreserveHost on RequestHeader set X-Forwarded-Proto "https" early # If you have pages that may take awhile to # respond, add a ProxyTimeout: # ProxyTimeout seconds </VirtualHost> /tmp/renew_cert_cron: mode: "000777" owner: root group: root content: | # renew Lets encrypt cert with certbot command 0 1,13 * * * /tmp/certbot-auto renew packages: yum: epel-release: [] mod24_ssl : [] container_commands: 10_installcertbot: command: "wget https://dl.eff.org/certbot-auto;chmod a+x certbot-auto" 20_getcert: command: … -
Return mean of values in models instead of every value
I am trying to make a Movie project in django. I would like to have one view for film's ratings that can take single rate_value but by GET returns mean of rating values for a film. I have no idea where should I start. I tried some changes in view and serializer but didnt work. Here are: views.py: class RateListView(generics.ListCreateAPIView): permission_classes = [AllowAny] serializer_class = RateSerializer lookup_url_kwarg = 'rateid' def get_queryset(self): sum = [] rateid = self.kwargs.get(self.lookup_url_kwarg) queryset = Rate.objects.filter(film = rateid) # .aggregate(Avg('rate_value')) if queryset.exists(): return queryset else: raise Http404 def post(self, request, *args, **kwargs): serializer = RateSerializer(data = request.data) if serializer.is_valid(): if Film.objects.filter(pk = self.kwargs.get(self.lookup_url_kwarg)).exists(): serializer.save(film_id = self.kwargs.get(self.lookup_url_kwarg)) return Response(serializer.data, status=status.HTTP_201_CREATED) else: raise Http404 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py class RateSerializer(serializers.ModelSerializer): class Meta: model = Rate fields = ('rate_value',) and model.py class Rate(models.Model): film = models.ForeignKey(Film, on_delete = models.CASCADE) rate_value = models.IntegerField(validators = [ MinValueValidator(1), MaxValueValidator(10) ] ) def __str__(self): return str(self.film.title) + str(self.rate_value) Right now it returns single values correctly. -
How to insert JSON result to database automatically in Django?
I've built a scraper that gets product data from different shopping websites. When I run python scraper.py the program will print a JSON object containing all the data like this: { 'ebay': [ { 'advertiser': 'ebay', 'advertiser_url': 'https://rover.ebay.com/rover/1/711-53200-19255-0/1?ff3=2&toolid=10041&campid=5338482617&customid=&lgeo=1&vectorid=229466&item=302847614914', 'description': '30-Day Warranty - Free Charger & Cable - ' 'Easy Returns!', 'main_image': 'https://thumbs1.ebaystatic.com/pict/04040_0.jpg', 'price': '290.0', 'title': 'Apple iPhone 8 Plus Smartphone AT&T Sprint ' 'T-Mobile Verizon or Unlocked 4G LTE'} ]} I want this data to be added to the database automatically every time I run the scraper. Here's my database structure: models.py class Product(models.Model): similarity_id = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255, blank=True, null=True) url = models.SlugField(blank=True, unique=True, allow_unicode=True) advertiser_url = models.TextField(blank=True, null=True) main_image = models.TextField(blank=True, null=True) second_image = models.TextField(blank=True, null=True) third_image = models.TextField(blank=True, null=True) old_price = models.FloatField(default=0.00) price = models.FloatField(default=0.00) discount = models.FloatField(default=0.00) currency = models.CharField(max_length=255, default="$") description = models.TextField(blank=True, null=True) keywords = models.CharField(max_length=255, blank=True, null=True) asin = models.CharField(max_length=80, blank=True, null=True) iban = models.CharField(max_length=255, blank=True, null=True) sku = models.CharField(max_length=255, blank=True, null=True) seller = models.CharField(max_length=255, blank=True, null=True) free_shipping = models.BooleanField(default=False) in_stock = models.BooleanField(default=True) sold_items = models.IntegerField(default=0) likes_count = models.IntegerField(default=0) category = models.CharField(max_length=255, blank=True, null=True) sub_category = models.CharField(max_length=255, blank=True, null=True) reviews_count = models.IntegerField(default=0) rating = models.FloatField(default=0) active = models.BooleanField(default=True) is_prime = … -
How to add only required url of third party app in django?
my url : I have included third party app django djoser . There are several urls of the third party app . But I want only specific ones. urlpatterns = [ path('apis/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('apis/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path("auth/", include("djoser.urls.jwt")), ] Here are all the urls obtained from djoser . But I want only some urls and neglect the others. ^auth/ ^users/$ [name='user-list'] ^auth/ ^users\.(?P<format>[a-z0-9]+)/?$ [name='user-list'] ^auth/ ^users/activation/$ [name='user-activation'] ^auth/ ^users/activation\.(?P<format>[a-z0-9]+)/?$ [name='user-activation'] ^auth/ ^users/me/$ [name='user-me'] ^auth/ ^users/me\.(?P<format>[a-z0-9]+)/?$ [name='user-me'] ^auth/ ^users/resend_activation/$ [name='user-resend-activation'] ^auth/ ^users/resend_activation\.(?P<format>[a-z0-9]+)/?$ [name='user-resend-activation'] ^auth/ ^users/reset_password/$ [name='user-reset-password'] ^auth/ ^users/reset_password\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-password'] ^auth/ ^users/reset_password_confirm/$ [name='user-reset-password-confirm'] ^auth/ ^users/reset_password_confirm\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-password-confirm'] ^auth/ ^users/reset_username/$ [name='user-reset-username'] ^auth/ ^users/reset_username\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-username'] ^auth/ ^users/reset_username_confirm/$ [name='user-reset-username-confirm'] ^auth/ ^users/reset_username_confirm\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-username-confirm'] ^auth/ ^users/set_password/$ [name='user-set-password'] ^auth/ ^users/set_password\.(?P<format>[a-z0-9]+)/?$ [name='user-set-password'] ^auth/ ^users/set_username/$ [name='user-set-username'] ^auth/ ^users/set_username\.(?P<format>[a-z0-9]+)/?$ [name='user-set-username'] ^auth/ ^users/(?P<id>[^/.]+)/$ [name='user-detail'] ^auth/ ^users/(?P<id>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='user-detail'] ^auth/ ^$ [name='api-root'] ^auth/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root']