Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve dynamic value from Django settings.py in a Celery Task?
My Django rely on Celery and Celerybeat to spawn tasks. I have 3 systemd services/units: myapp.service (gunicorn daemon) celery-myapp.service (celery worker(s)) celerybeat-myapp.service (celerybeat daemon) I have an environment variable MY_SECRET defined in my main "myapp.service" service (systemd unit). I can't get this value from settings.py or directly environment variable in my tasks (tasks.py), but I can retrieve this value smoothly from my view (views.py) using settings.py or environment variable directly. Do I need to replicate environment variable MY_SECRET defined in myapp.service to celery-myapp.service and celerybeat-myapp.service so that I could grab this value from my Celery tasks? myapp.service [Unit] Description=My App After=network.target Wants=celery-myapp.service Wants=celerybeat-myapp.service [Service] User=myapp Group=nginx Environment=MY_SECRET=1234 WorkingDirectory=/opt/myproject/ ExecStart=/opt/myproject/env/bin/gunicorn --workers 3 --log-level debug --bind unix://opt/myproject/myapp.sock myaproject.wsgi:application [Install] WantedBy=multi-user.target Environment variable is referenced in my Django project 'settings.py' along with other settings I intended to use within the application: settings.py # Populated with environment variable defined by systemd unit MY_SECRET = os.environ.get('MY_SECRET') # Static value MY_URL= 'http://127.0.0.1' From my view I can get value defined as environment variable MY_SECRET from settings.py and directly from environment: views.py def my_view(request): from django.conf import settings as project_settings my_secret_env = os.environ.get('MY_SECRET') my_secret_setting = project_settings.MY_SECRET my_url_setting = project_settings.MY_URL return render(request,'mypage.html',{ 'my_secret_env': my_secret_env, 'my_secret_setting': my_secret_setting, 'my_url_setting': my_url_setting, … -
Perform calculations on data in backend in anticipation of API request
First up, I'm not looking for any code, but only guidance related to the workflow and technologies which can be used to address our specific problem. We have a system where we provide a visual query builder kind of interface. We have loads of data on which the user can apply this query. So the query can be something like all rows where x > 5 and y <2.5. While this is fairly easy to achieve, the problem we are facing is that the fields x and y are not pre-calculated fields and these relations can be defined by the user. For instance, the user can define a relationship like x = (a+b)-c^2 and then apply a filter on x. Since the value of x needs to be dynamically calculated, the query builder then takes significant amount of time to return the results. So I was wondering if we can implement some kind of prefetching and preprocessing such that the moment the user selects the field x, we calculate all the values for x in the backend. Since the user can take a few seconds to define the entire query, we'd have at least part of the calculation done by … -
Deploy application developed using Django + Angularjs on apache http server [closed]
I am working on a POC using Django as backend and angular js as front end . I want to deploy the application on Apache http server. How to set up apache http server and what configuration changes should be done on backend and front end to run the application using apache http server. -
Access basket/shipping address in django oscar pricing strategy
What would be the best practice to get the shipping address in a pricing strategy? Based on the country selected, I would like to apply tax, or not. I have an instance of CheckoutSessionData in my Selector, and the Selector inherits from CheckoutSessionMixin. But, CheckoutSessionMixin needs a basket for many operations, especially for getting a shipping address. And, the BasketMiddleware gets it's strategy first, and only then sets the basket on the current request. So, how to get the shipping address, before? Any best practices? -
Django distinct method
I just want to select what i want to distinct field, in my case the Grading_Behavior__GroupName should not coincide with being distinct of Grading_Behavior__Name this is my current result this is I want result This is my views.py behaviorperlevel = EducationLevelGradingBehavior.objects.filter(GradeLevel__in = coregradelevel).filter(Grading_Period__in = coreperiod)\ .order_by().values('Grading_Behavior__GroupName','Grading_Behavior__Name','Display_Sequence','id').distinct('Grading_Behavior__Name') my models class EducationLevelGradingBehavior(models.Model): Display_Sequence = models.IntegerField(null=True, blank=True) GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Behavior = models.ForeignKey(GradingBehavior, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) this is my admin site -
django-allauth: override a user already existing
In my movies app, I allow anonymous users creating their own movie lists. This is done by means of retrieving the session_key parameter and saving it into the User model. So, I actually register anonymous users as users on the background, and their username is their id in this case. Now, when an authenticated anonymous user registers via Facebook or Google (registration is implemented by means of django-allauth), I want not to create a new User instance, but to update the existing user, so as to keep their movies_list intact, with their username changing from their id in the database to the actual username retrieved from Facebook. I have tried to play with the user_signed_up signal and to override DefaultAccountAdapter, but this yielded no results. Obviously, I just don't understand how this should work and need some conceptual advice on how to implement the desired scheme: update the existing User instance instead of creating a new one from Facebook or Google with django-allauth. -
What is the best way to handle different but similar models hierarchy in Django?
What is the deal: I'm crating a site where different types of objects will be evaluated, like restaurants, beautysalons, car services (and much more). At the beginning I start with one app with with Polymorfic Model: models.py: from django.db import models from users.models import ProfileUser from django.utils import timezone from polymorphic.models import PolymorphicModel class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) sea_food = models.BooleanField(default=False) is_cash = models.BooleanField(default=False) is_bank_card = models.BooleanField(default=False) is_wi_fi = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='restaurants') category_bg_name = models.CharField(max_length=100, default='Ресторанти') bg_name = models.CharField(max_length=100, default='Ресторант') is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class SportFitness(Object): is_fitness_trainer = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='sportfitness') category_bg_name = models.CharField(max_length=100, default='Спорт и фитнес') bg_name = models.CharField(max_length=100, default='Спорт и фитнес') class CarService(Object): is_parts_clients = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='carservice') category_bg_name = models.CharField(max_length=100, default='Автосервизи') bg_name = models.CharField(max_length=100, default='Автосервиз') class Comment(models.Model): object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name='comments') author … -
How to check that uuid field is generated when creating a custom user in Django?
I have added an uuid field to the cusom user model. How can I check that every user I'm creating will have the uuid value? I have tried to print the uuid but it doesn't work. The field I added is: uuid = models.UUIDField(default=uuid.uuid4) -
Django ORM: Select with TO_CHAR
I have DB with fields: task_description, type, hours, date, status, user_id, created_at, updated_at, project_id, I need create list with dicts like this: [{"month":"2020 Mar","Accepted":0,"Declined":0,"Open":40}] I generated SQL query: select "t"."status", sum("t"."hours") as "total_hours", TO_CHAR("t"."date" :: DATE, 'YYYY-MM') as "ddate" FROM "tracks_track" as "t" WHERE "t"."user_id" = 1 GROUP BY "ddate", "t"."status" Format of date is YYYY-MM-DD, but i need to group this fields by YYYY-MM Can I do it using Django ORM? -
How do I make a signal run only if the user created is on a specific group in Django?
I have a model Client which uses a @receiver signal to update its fields whenever a User is created, so it creates a Client profile. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) class Meta: verbose_name_plural = "Clientes" @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Clients.objects.create(user=instance) instance.clients.save() Is there a way to only run this if the user created belongs to the Clients group? Because if a user is created in the Employees group, I don't want to create a profile. This is the view that creates the Client in the Clients group: @login_required(login_url='./accounts/login/') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() # this creates the user with first_name, email and last_name as well! group = Group.objects.get(name='Clients') user.groups.add(group) user.refresh_from_db() # load the profile instance created by the signal user.clients.address = form.cleaned_data.get('address') user.clients.city = form.cleaned_data.get('city') user.clients.postal = form.cleaned_data.get('postal') user.clients.nif = form.cleaned_data.get('nif') user.clients.mobile = form.cleaned_data.get('mobile') return redirect('clients') else: form = SignUpForm() return render(request, 'backend/new_client.html', {'form': form}) -
Django : defining method inside the models
serialize() method included in the django Tools_booked class but while trying to access that method it shows error. 'QuerySet' object has no attribute 'serialize' models.py from django.core.serializers import serialize class UpdateQuerySet(models.QuerySet): def serialize(self): print("*****Entered the serizlize inside the UpdateQuerySet models **********") qs = self return serialize('json', qs, fields=('auto_increment_id','user','component','booked')) class UpdateManager(models.Manager): def get_queryset(self): return UpdateQuerySet(self.model, using=self._db) class Tools_booked(models.Model): auto_increment_id = models.AutoField(primary_key=True) user=models.ForeignKey(Profile, on_delete=models.CASCADE) component = models.CharField(max_length=30, blank=True) booked = models.DateTimeField(auto_now_add=True,blank=True) objects = UpdateManager() def __str__(self): return self.component def serialize(self): json_data = serialize("json", [self], fields=['auto_increment_id','user','component','booked']) stuct = json.loads(json_data) print(struct) data = json.dump(stuct[0]['fields']) return data views.py class SerializedDetialView(View): def get(self, request, *args, **kwargs): print("*****Entered the SerializedDetialView **********") obj_list= Tools_booked.objects.filter(auto_increment_id=1) json_data = obj_list.serialize() return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): json_data = Tools_booked.objects.all().serialize() return HttpResponse(json_data, content_type='application/json') The error traceback json_data = Tools_booked.objects.all().serialize() AttributeError: 'QuerySet' object has no attribute 'serialize' But this works. class SerializedDetialView(View): def get(self, request, *args, **kwargs): obj_list= Tools_booked.objects.filter(auto_increment_id=1) json_data = serializers.serialize("json", obj_list ) return HttpResponse(json_data, content_type='application/json') class SerializedListView(View): def get(self, request, *args, **kwargs): qs = Tools_booked.objects.all() json_data = serializers.serialize("json", qs ) return HttpResponse(json_data, content_type='application/json') How to use the serialize() method inside the models.py ,Tools_booked class. -
What am I missing in this Django model relationship
I have a custom user model, and a blog model. Here is the user model: class CustomUser(AbstractUser): pass email = models.EmailField(unique=True) first_name = models.CharField(max_length=20, default="", blank=True) and the blog model: class Blog(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, verbose_name=_('user'), related_name="%(class)s_blogs", on_delete=models.SET_NULL) blog_id = models.CharField(max_length=150, null=False, default=get_id, unique=True, editable=False) blog_title = models.CharField(max_length=150, null=False) My understanding is that I could use the related_name to get all blogs by a user. >>> from users.models import CustomerUser >>> user = CustomUser.objects.get(pk=1) >>> user.blog_blogs.all() <BlogQuerySet []> As you must have seen, this turns to always return but an empty queryset, even though there are blog entries by that user. So is it am not understanding here? Thank you. -
how to make custom user login using SQL query in DjangoRestFulAPI?
i have user data set in my database that contains user_id,username and password. i want to fetch data from databases using raw query. user_raw_query = ''' SELECT * from users ''' now i want to make custom user login as per above details. any help would be appreciated. -
JS files of django-smart-select not working. net::ERR_ABORTED 404
I want to use django-smart-select I have installed it via pip and used this command as mentioned in django-smart-select problems: sudo pip3 install git+https://github.com/digi604/django-smart-selects.git@js-unlinting-fixes I have added 'smart_selects' to settings.py and added these lines to URLs: url(r'^chaining/', include('smart_selects.urls')), also used this line in settings.py JQUERY_URL = True and as mentions again in problems added this lines to HTML: {% load staticfiles %} <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> but when I load the page it raises these errors. it leads to not working the second option in django smart select: GET https://example.com/static/smart-selects/admin/js/chainedfk.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/chainedm2m.js net::ERR_ABORTED 404 GET https://example.com/static/smart-selects/admin/js/bindfields.js net::ERR_ABORTED 404 models.py: class CustomerAddressProvince(LoggableModel): title = models.CharField(verbose_name='province', max_length=60) class CustomerAddressCity(LoggableModel): title = models.CharField(verbose_name='city', max_length=60) province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.CASCADE, related_name='cities') class CustomerAddress(LoggableModel): province = models.ForeignKey(CustomerAddressProvince, verbose_name='province', on_delete=models.SET_NULL, related_name='address_province', null=True, blank=True) city = ChainedForeignKey( CustomerAddressCity, verbose_name='city', chained_field="province", chained_model_field="province", show_all=False, auto_choose=True, sort=True, null=True, blank=True) -
bootstrap not working for djano send_mail
In my views.py I have the following code def cpio(request): mainDict9=['hemant','jay','yash','Hari'] args={'mainDict9':mainDict9,} msg_html =render_to_string('/home/user/infracom2/JournalContent/templates/JournalContent/test1.html', {'mainDict9':mainDict9,}) from_email = 'gorantl.chowdary@ak-enterprise.com' to_email = ['gorantla.chowdary@ak-enterprise.com'] subject="TESTING MAIL" send_mail('email title',subject,from_email,to_email,html_message=msg_html,) return render(request,'JournalContent/test1.html',args) In my test1.html I have my following code <!DOCTYPE html> <html> <table class="table table-bordered"> <thead> <tr> <th scope="col" class="table-secondary"><center>Modified Binaries/components</center></th> <th scope="col" class="table-secondary"><center>CRs</center></th> </tr> </thead> <tbody> {% for king in mainDict9 %} <tr> <td style="width: 10px;" class="table-active">{{ king }}</td> <td style="width: 10px;" class="table-active"></td> </tr> {% endfor %} </tbody> </table> </html> The problem is in my GUI the bootstrap code is working fine but when I send the content in mail bootstrap functions are not applying -
SSL: CERTIFICATE_VERIFY_FAILED trying to validate a reCAPTCHA with django
I'm getting a <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)> When I try to validate captchas in my django project. This is how i do it: recaptcha_response = request.POST.get('g-recaptcha-response') print(recaptcha_response) url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.CAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) # It fails here result = json.loads(response.read().decode()) print(result) The site has a valid certificate, and it works on local. In the log i'm getting this: Request Method: POST Request URL: http://prod.xxxx.com/evalua Which is weird because the site works in https. Its on kubernetes, could that be the problem? I really have no idea what the problem IS? I have the captcha keys correctly set up in de recaptcha admin console. And the certificate are not autosign. I use lets encrypt -
Using localhost for google chrome extension
I created a Google Chrome extension.I made a Django app to process the ajax request it sends.But when I use my localhost I get the following error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/working' from origin 'chrome-extension://nmgmbpgmpjfoaefb' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have no idea how to make it work. -
Chaning Image Resolution Django
I am fetching images from website by using BeautifulSoup, but the resolution is too small, when I want to make image bigger by adding width attribute in src, it loses quality. Is it possible to enlarge image resolution which is downloaded from url? I've tried thumbnail sorl, but then images dissapeared views.py def home(request): source = requests.get('https://lol.gamepedia.com/Ultraliga/Season_3').text hours_games = ['17:30', '18:30', '19:30', '20:30', '17:30', '18:30', '19:30', '20:30'] soup = BeautifulSoup(source, 'lxml') first_team_images = [] first_team_images_res = [] team_image1 = None first_team_names = [] second_team_names = [] td1s = None td2s = None tables = soup.find_all('table', class_='wikitable matchlist') for table in tables: td1s = table.find_all('td', class_='matchlist-team1') td2s = table.find_all('td', class_='matchlist-team2') for td in td1s: span = td.find('span') first_team_names.append(span.text) span2 = span.find('span', class_='teamimage-left') team_image1 = span2.find('img')['src'] first_team_images.append(team_image1) for td in td2s: span = td.find('span') second_team_names.append(span.text) context = { 'all_teams':zip(first_team_names, second_team_names, hours_games, first_team_images) } return render(request, 'profilecontent/home.html', context) template {%extends 'profilecontent/base.html' %} {%block content%} <div class="container-home"> <div class="home-wrapper home-wrapper-first"> <p class='home-matches'>Przyszłe mecze <span class='home-week'>W3 D2</span></p> <div class="match-wrapper"> <ul class='team-schedule-list'> {% for data in all_teams %} <li class='item-team-schedule'><span class='team-describe first-team-name'>{{ data.0 }}</span> <img src="{{data.3}}" width='150' height='150' alt=""> <span class='hours-game'>{{ data.2 }}</span> <span class='team-describe2 second-team-name'>{{ data.1 }}</span></li> {% endfor %} </ul> </div> </div> <div class="home-wrapper … -
How to stop __init__ of a class based view executing twice in django?
I have shuffled the questions and corresponding options in the exam. Once student has wriiten the exam score will be displayed, and I want to show the student their answer sheet in the same way as they have seen while writing the exam with their answers and correct answers. So I decided to use random.seed(). Why init() is executing twice ? [12/Mar/2020 14:08:58] "GET /exam/4/ HTTP/1.1" 200 11103 [12/Mar/2020 14:41:15] "GET / HTTP/1.1" 200 5059 init seed = 13 student now writing the exam with seed = 13 [12/Mar/2020 14:41:24] "GET /exam/3/ HTTP/1.1" 200 13156 init seed = 57 saving seed = 57 [12/Mar/2020 14:42:04] "POST /exam/3/ HTTP/1.1" 200 59 views.py class ExamDetailView(LoginRequiredMixin, DetailView): model = Exam #context_object_name = 'exam' def __init__(self, *args, **kwargs): super(ExamDetailView, self).__init__(*args, **kwargs) self.seed = random.randint(1, 100) print("init seed = ", self.seed) def setup(self, *args, **kwargs): super().setup(*args, **kwargs) print(dir) def get_context_data(self, **kwargs): context = super(ExamDetailView, self).get_context_data(**kwargs) try: self.seed = ResultPerExam.objects.get(student_id = self.request.user.id, exam_id = self.kwargs[self.pk_url_kwarg]).seed #checking sudent has already written the exam or not print("seed read from ResultPerExam is ", self.seed) context["has_written"] = True random.seed(self.seed) print("student already writen exam with seed = ", self.seed) except ResultPerExam.DoesNotExist: context["has_written"] = False random.seed(self.seed) context["seed"] = self.seed print("student now writing … -
I can't display OpenCV processed image in Django Template (sent as parameter)
My app works like this: My client uploads an image. I crop that image using OpenCV and want to display the cropped image in the next view. I don't want to store on my server any of these images. The image I get is stored in crop variable. I tried something like this: crop_png = png.from_array(crop, mode="L") content = crop_png.getvalue().encode("base64") img = "data:image/png;base64," + content return render(request, 'finish_page.html', {"img": img}) And tried to display like this in my finish_page.html <img src="{{img}}"> I receive the following error: 'Image' object has no attribute 'getvalue' I also tried this encoded_string = base64.b64encode(crop) mime = "image/png" img = "data:%s;base64,%s" % (mime, encoded_string) But still didn't work. And I've also tried something like this: output = io.StringIO() encoded_string = base64.b64encode(crop) encoded_string.save(output, "PNG") output.close() -
Display frames generated from opencv Django React
I want to show a video generated from opencv, I am getting each frame from opencv and with the help of the django I send this to react. So what happens, I send a request from react to django api to get frame from opencv and I then show that on react, I am calling this api in a loop to get multiple frames in a second and show on react ( its so fast that it shows frame in a form of video). But I found that its a wrong way I have to use sockets to send so much request at a time. Can some show me how can I get the same functionality through websockets,I have a short time so I need a smaller and quicker solution I have googled a lot but did't find nothing. here's my current approach of sending multiples request: const interval = setInterval(() => { axios .get("http://127.0.0.1:8000/MyApp/get_logs/") .then(res => { set_show(res.data); }) .catch(err => { console.log(err); }); }, 500); return () => clearInterval(interval); The above function is called after every 0.5 seconds, I get a frame in base64 and show it in image, and it happens repeatedely that makes it in a … -
Html button not changing color when toggled to on/off
{{ value.stat }} < The above is my html code which iam using in django.can any one please tel me how to change the color of the switch when i'm toggling it to on/off. -
changed the database settings.py from sql to postgres in server (nginx)
Developing a Django web application having geojson data, using postgres(postgis extension) as a database, while uploading the changes to the server done in my settings.py and running the project on the server, i am getting an error like this File "/opt/rh/rh-python36/root/usr/lib64/python3.6/ctypes/__init__.py", line 361, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib64/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 my settings.py looks like this: import os if os.name == 'nt': import platform OSGEO4W = r"root\my_project\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****************************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'my_app', 'leaflet', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], … -
Query to save data from json request in Django
I'm trying to create a Calorie Info API which saves calorie intake for a user. If it is a new user, then add an entry for the user id and item id. If the user already exists, If the item is new, then just map the item id and the calorie count with that user. If the item id is already mapped with that user, then add the items calorie count with that item for that user. Url: /api/calorie-info/save/ Method: POST, Input: { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } Output: - Response Code: 201 My model: class CalorieInfo(models.Model): user_id = models.IntegerField(unique=True) itemId = models.IntegerField(unique=True) calorie_count = models.IntegerField() I tried: class Calorie(APIView): def post(self, request): user_id = request.GET["user_id"] item_id = request.GET["item_id"] calorie = request.GET["calorie"] try: check = CalorieInfo.objects.get(user_id=user_id) except CalorieInfo.DoesNotExist: entry = CalorieInfo(user_id=user_id, item_id=item_id, calorie=calorie) entry.save() res = {"status": "success"} return Response(res, status=status.HTTP_201_CREATED) How to make a post request in the above format? -
How to get value in variable from Django template in views.py?
I am working in django and want to pass the value in views.py my code is HTML Template {% for doctor in doctor_list %} {% if citysearch == doctor.city %} <h1>Name of doctor is </h1> <form class="form" method="POST"> {% csrf_token %} <input type="submit", class="btn view", name="{{doctor.contactNumber}}" value="View Profile"> </form> {% endif %} {% endfor %} Views.py if request.method == 'POST': selectdocnum = request.POST.get["doctor.contactNumber"] print(selectdocnum) return redirect('patientPannel') This is not returning the value of doctor.contactNumber, and error is method object is not subscriptable