Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter on a model with OneToOne relation
My application uses Django's built-in authentication system, but I create a Customer profile based on user first_name and last_name, and I add a phone_number field. So it looks like this: from django.db import models from django.dispatch import receiver from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=64, default='') last_name = models.CharField(max_length=64, default='') phone_number = models.CharField(max_length=13, default='') @receiver def create_customer_profile(sender, instance, created, **kwargs): if created: Customer.objects.create( user=instance, first_name=instance.first_name, last_name=instance.last_name, phone_number='', ) @receiver def save_customer_profile(sender, instance, **kwargs): instance.profile.save() def __str__(self): return self.user.username Then, somewhere in a view I want to filter Customer objects based on the user related to it. I tried this: @login_required def my_account(request): if request.user.is_authenticated: # ... customer = Customer.objects.filter(user=request.user) But I get this error: 'QuerySet' object has no attribute 'user' Django version: 3.1.3 -
How do I can redirect login, logout, register using rest_auth package?
I'm using Django rest_auth package in my project. by default when I using login, logout and register It showing me a key I want to redirect users in my home URL but I can't. I have LOGIN_REDIRECT_URL but still it shows me the key and LOGIN_REDIRECT_URL doesn't works. what should I do????? -
django how to update data without refreshing the page?
I hope my title is enough to understand what i want, i have this form in my html where the data updating in my database, <form method="POST" id="form" >{% csrf_token %} <input type="hidden" value="{{bought.id}}" name="itemID"> <div class="order-option"> <span id="quantity-field"> <input type="submit" value="-" id="down" formaction="/updatecart_index/" onclick="setQuantity('down');" > <input type="text" name="quantity" id="quantity" value="{{bought.quantity}}" onkeyup="multiplyBy()" style="width: 13%; text-align:left;" readonly> <input type="submit" value="+" id="up" formaction="/updatecart_index/" onclick="setQuantity('up');" > </span> </div> </form> this is my views.py def updatecart_index(request): item = request.POST.get("itemID") print(item) quantity = request.POST.get("quantity") product = CustomerPurchaseOrderDetail.objects.get(id=item) print("aa", CustomerPurchaseOrderDetail.objects.get(id=item)) product.quantity = quantity product.save() return HttpResponseRedirect('/') my urls.py path('updatecart_index/', customAdmin.views.updatecart_index, name='updatecart_index'), -
Deploying a Django site to GCP on App Engine, connecting App Engine to Cloud SQL
I've followed two tutorials to deploy my Django app to App Engine and to connect to the database: https://medium.com/@BennettGarner/deploying-a-django-application-to-google-app-engine-f9c91a30bd35 https://cloud.google.com/python/django/appengine I have the app "succesfully" running atm, but from print statenments I can see from the log information that as soon as the site reaches a point where it needs to query the database it times out (after 5min or so). So that suggests to me that there are some issues with the App Engine and Cloud SQL connection. I have succesfully the django site connected locally through the cloud sql proxy, and I try to deploy with the same configurations but doesn't seem to work. I suspect that the issue is one of the following: The Cloud SQL Configs should be different when running the app locally vs. in app engine (settings.py) In some examples I've seen the Main.py contain a lot of stuff around the database connection, but in neither of the tutorials do they do this, for example this is the GCP tutorial on the main.py file: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard_python3/django/main.py I've checked that all App Engines inside the project have access to CLoud SQL by default, and the user also has access (i've used it for access). I'm not … -
Remove search option from django widget FilteredSelectMultiple
I am using FilteredSelectMultiple widget in my form but i want to remove the search option from the widget. forms.py study = forms.MultipleChoiceField(required=True, widget=FilteredSelectMultiple(_('Study'),False)) After rendering it's code comes out as a html paragraph with id="id_study_filter" and class="selector-filter". I tried to remove it using it's id but the following code didn't work. document.getElementById("id_study_filter").style.display = 'none'; I also tried to hide it after a timeout, still it's not working. $(document).ready(function() { $('#id_study_filter').delay(3000).hide();}); -
Posting to two related models through same api
I would like to post to related models using single api, I couldn't able to do it. I tried to override create as suggested here how to post multiple model data through one serializer in django rest api here's my models.py class Fullfillment(models.Model): candidate_name = models.CharField(max_length=60) manpower_requirement = models.ForeignKey(ManpowerRequirement, on_delete=models.CASCADE) passport_number = models.CharField(blank = True, max_length=60) joined_date = models.DateField(blank = True, null = True, default = '') remarks = models.TextField( blank = True) def __str__(self): return self.candidate_name class Meta: verbose_name_plural = "Fullfillment" class FullfillmentStatus(models.Model): fullfillment = models.ForeignKey(Fullfillment, on_delete=models.CASCADE) status = models.CharField(max_length=60) status_date = models.DateField() remarks = models.TextField( blank = True ) def __str__(self): return self.fullfillment.candidate_name class Meta: verbose_name_plural = "FullfillmentStatus" hers's seriallizers.py class FullfillmentSerializer(serializers.ModelSerializer): project = ManpowerRequirementSerializer(read_only=True,source='manpower_requirement') class Meta: model = Fullfillment fields = ('id','status','project','passport_number', 'candidate_name', 'joined_date',) class FullfillmentStatusSerializer(serializers.ModelSerializer): fullfillment_id = FullfillmentSerializer(source='fullfillment') class Meta: model = FullfillmentStatus fields = ('fullfillment_id','status','status_date','remarks',) def create(self, validated_data): data = validated_data.pop('fullfillment_id') fullfillment = Fullfillment.objects.create(**data) data_object = FullfillmentStatus.objects.create(fullfillment_id=fullfillment, **validated_data) return data_object here's my views.py class FullfillmentViewSet(viewsets.ModelViewSet): queryset = FullfillmentStatus.objects.all().order_by('id') serializer_class = FullfillmentStatusSerializer -
Why is the attach() not working in Django
I'm trying to attach a png file which is inside the "project_name/static/images/logo.png". My views.py code looks like this: def ForgotIDView(request): context = {} if request.method == 'POST': email = request.POST.get('email') try: user = User.objects.get(email=email) if user is not None: method_email = EmailMessage( 'Your ID is in the email', str(user.username), settings.EMAIL_HOST_USER, [email], ) method_email.attach_file('/images/logo.png') method_email.send(fail_silently=False) return render(request, 'accounts/id_sent.html', context) except: messages.info(request, "There is no username along with the email") context = {} return render(request, 'accounts/forgot_id.html', context) and the file directory looks like this: I'm sure that the settings.py on MEIDA_URL and stuff like that is alright, because everything else that has to do with the medias work. But only when I try to attach the files in this view, it's gives me back an error saying that: any way to solve this?? -
Cannot run python script in Django
In my Django project I have an app called 'catalog', here's the model in models.py: from django.db import models class Catalog(models.Model): brand = models.CharField(max_length=255) supplier = models.CharField(max_length=255) catalog_code = models.CharField(max_length=255, null=True, blank=True) collection = models.CharField(max_length=255) season = models.CharField(max_length=255) size_group_code = models.CharField(max_length=2) currency = models.CharField(max_length=3) target_area = models.CharField(max_length=255) I want to create one Catalog object but I don't want to do it using the admin panel or a form, so in the same app 'catalog' I've created tools.py which is just a script, it reads a csv file and create an istance of Catalog(). from catalog.models import Catalog def create_catalog(file): with open(file, 'r') as f: f = f.readlines() catalog = Catalog(# all my keyword args) catalog.save() I don't know if the script is fine but it's not important, my problem is when I try to run tools.py froom my IDE I get this error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to run it from the shell with: exec(open('catalog/tools.py').read()) but nothing happens and no traceback. So how can I run a Python script inside of a Django project that creates objs … -
How to get text inside <a> tag in views.py django via form action?
I have a list in my function in views.py and displayed them in the html page as tags. When i click on any of the tag i need to get those text of tags in another function in views.py when the form is submitted. def index(request): vendor_data = requests.get('https://cve.circl.lu/api/browse').content vendors = json.loads(vendor_data) vendor_list = [] context = {} for i in range(len(vendors['vendor'])): vendor_list.append(vendors['vendor'][i]) paginator = Paginator(vendor_list, 50) page_number = request.GET.get('page') context['page_obj'] = paginator.get_page(page_number) return render(request,'index.html',context) index.html <form action="{% url 'appVuldb:output' %}" method="POST" id="venform"> {% csrf_token %} {%for vendor in page_obj%} <ul> <li> <a href="javascript:void(0);" class="link" name="vendor_name" onclick="document.forms['venform'].submit();">{{vendor}} </a> </li> </ul> {%endfor%} </form>` -
Error during template rendering: inconsistent use of tabs and spaces in indentation
[the running pic of django local site][ In the pic i have tried all the methods but that error is not going Can any one suggest how to solve it or some clear methods to integrate django with react. Thanks.] -
Will YouTube embedded videos work when I host the website on a public domain?
Currently, youtube embedding videos do not work on the IP address local server. Will it work if I deploy the site into production? -
Django in production not loading webfonts and javascript from Amazon S3 bucket [Cross-Origin Request Blocked]
I've installed django-cors-headers and added: CORS_ALLOWED_ORIGINS = [ "https://s3.us-east-2.amazonaws.com/", ] CORS_ORIGIN_ALLOW_ALL = False It doesn't seem to work. The problem is I can't keep bringing the site down and back up again because I only have so many Let'sEncrypt SSL certificates that I can get. I'll include the console errors please if someone can help I really need to finish this site. I've replaced my web address with 'my-site.static': GEThttps://s3.us-east-2.amazonaws.com/my-site.static/static/vendor/fade-zoom-scroll/dist/FadeJr.min.css [HTTP/1.1 403 Forbidden 430ms] GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/Animate.js-master/dist/animate.min.js [HTTP/1.1 403 Forbidden 251ms] GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/fade-zoom-scroll/dist/FadeJr.min.js [HTTP/1.1 403 Forbidden 242ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/simple-line-icons/fonts/Simple-Line-Icons.woff2?v=2.4.0. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). downloadable font: download failed (font-family: "Font Awesome 5 Free" style:normal weight:900 stretch:100 src index:1): bad URI or cross-site access not allowed source: https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff2 GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/Animate.js-master/dist/animate.min.js [HTTP/1.1 403 Forbidden 47ms] downloadable font: download failed (font-family: "simple-line-icons" style:normal weight:400 stretch:100 src index:1): bad URI or cross-site access not allowed source: https://s3.us-east-2.amazonaws.com/my-site.static/vendor/simple-line-icons/fonts/Simple-Line-Icons.woff2?v=2.4.0 GEThttps://s3.us-east-2.amazonaws.com/my-site.static/vendor/fade-zoom-scroll/dist/FadeJr.min.js [HTTP/1.1 403 Forbidden 47ms] Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://s3.us-east-2.amazonaws.com/my-site.static/vendor/fontawesome-free/webfonts/fa-solid-900.woff. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). downloadable font: download failed (font-family: "Font … -
showing Django rest nested comments for products
I created nested comment for my project. I have my model and Serializer. I want to when I retrieve a product for showing product's details the product comments show as well. how do I can do this? this is my code: #models.py class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) #serializers.py class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created'] #views.py class RetrieveProductView(generics.RetrieveAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = (permissions.AllowAny,) lookup_field = 'slug' -
How to connect web docker container (Django) to postgresql database locally (not in contaiiner)?
I am neewbie in Docker and experiment different configurations. My stack: Django/Nginx/Postgresql/Docker-compose I work locally with a Windows environnement and have to deploy apps on remote servers with Linux/Ubuntu. I try to set a configuration to be able to connect my Django app (inside a Docker container) to a Postgresql database hosted locally (http://127.0.0.1:55193 using pgAdmin 4). But when I built container, I can not access my Django app. I have no error messages (docker logs <my_container> seems to be OK). So I guess it is because my Django app do not connect to my postgresql database. Is extra_hosts parameters needed? What should be the IP? .env.prod DEBUG=0 SECRET_KEY=********************************** DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_prod SQL_USER=user_prod SQL_PASSWORD=user_prod SQL_HOST=db SQL_PORT=5432 DATABASE=postgres DJANGO_SETTINGS_MODULE=core.settings.prod docker-compose.prod.yml version: '3.7' services: web: build: context: ./app dockerfile: Dockerfile.prod restart: always command: gunicorn core.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./.env.prod extra_hosts: - "db:127.0.0.1" nginx: build: ./nginx restart: always volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1338:80 depends_on: - web volumes: static_volume: media_volume: -
Why my serializer gets only one image instead of multiple (Rest Framework)
I am trying to upload multiple images with this serializer but it only accepts one image . View class ArticleView(CreateAPIView): queryset = Article.objects.all() serializer_class = ArticleViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleViewSerializer(data=request.data) if serializer.is_valid(): article = serializer.save() serializer = ArticleViewSerializer(article,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ArticleImagesView(CreateAPIView): queryset = ArticleImages.objects.all() serializer_class = ArticleImagesViewSerializer permission_classes = (AllowAny,) parser_classes = (MultiPartParser, FormParser,) def get(self, request, format=None): queryset = ArticleImages.objects.all() serializer = ArticleImagesViewSerializer() return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = ArticleImagesViewSerializer(data=request.data) if serializer.is_valid(): articleimages = serializer.save() serializer = ArticleImagesViewSerializer(articleimages,many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class ArticleImagesViewSerializer(serializers.ModelSerializer): class Meta: model = ArticleImages fields = ('id','image') def create(self, validated_data): return ArticleImages.objects.create(**validated_data) class ArticleViewSerializer(serializers.ModelSerializer): imageset = ArticleImagesViewSerializer(required=False,many=True) class Meta: model = Article fields = ('imageset','id','author') def create(self, validated_data): images_data = self.context.get('view').request.FILES article = Article.objects.create(**validated_data) for image_data in images_data.values(): ArticleImages.objects.create(article=article, image=image_data) return article When i send a postman request to my django serializer,it only accepts one imageset ,like this: "imageset": [{ "id": "ec7b9665-92cd-4a8c-ba16-d62b4c24dfca", "image": "http://127.0.0.1:8000/images/images/download2_dmpBXZQ.png"}], I have also coded my def create() function such that it enters into loop,but i know … -
Django Celery: create periodic task at runtime with schedule depending on user input
I have a simple Django (v3.1) app where I receive data from a form, process it with a view and then pass it on to Celery (v4.4.7, RabbitMQ as broker). Depending on the data submitted in the form, it can be a one-time task or a periodic task. The periodic task should have a start date, end date and an intervall (e.g.: execute every 2 days at 4pm, starting now until 4 weeks). My view (shortened and renamed for illustration purposes, of course): # views.py if request.method == 'POST': form = BackupForm(request.POST) if form.is_valid(): data = ... if not form.cleaned_data['periodic']: celery_task = single_task.delay(data) else: schedule = { 'first_backup': form.cleaned_data['first_backup'], 'last_backup': form.cleaned_data['last_backup'], 'intervall_every': form.cleaned_data['intervall_every'], 'intervall_unit': form.cleaned_data['intervall_unit'], 'intervall_time': form.cleaned_data['intervall_time'], } celery_task = periodic_task.delay(data, schedule) return HttpResponseRedirect(reverse('app:index')) The single task looks like this: # tasks.py @shared_task def single_task(data: dict) -> None: asyncio.run(bulk_screen(data=data)) This works well for a single task. However, I don't know how to adapt this to create dynamic periodic tasks. My schedule data varies, depending on the users' form input. I have to create the periodic task at runtime. According to the official documentation on periodic tasks, crontab schedules is what I need: from celery.schedules import crontab app.conf.beat_schedule = { # … -
anytomany field and a foreignkey to the same model class in a django model
How can I set a manytomany field and a foreignkey to the same model class in a django model. My data structure is similar to a linking list. class cls_object(models.Model): child = models.ManyToManyField('cls_object') parent = models.ForeignKey('cls_object', on_delete=models.CASCADE, blank=True, null=True) django always tells me to change one of the two: ERRORS: cls_object: (fields.E304) Reverse accessor for 'cls_object.child' clashes with reverse accessor for 'cls_object.parent '. HINT: Add or change a related_name argument to the definition for 'cls_object.child' or 'cls_object.parent'. cls_object: (fields.E304) Reverse accessor for 'cls_object.parent' clashes with reverse accessor for 'cls_object.child'. HINT: Add or change a related_name argument to the definition for 'cls_object.parent' or 'cls_object.child'. i would like to have the opportunity to find out its parents from the respective object and have to know which objects emanate from it. A loop would not be possible (syntax, of course, yes). should one possibly do this differently? The error is sure that he does not know how to resolve it clearly in the database, but something like that should work anyway, right? am I completely wrong? -
Query multiple tables with manytomany relationship and also check against a timestamp that is in the through table
Here's a simplified version of my model class: class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class UserProfile(models.Model): user = models.OneToOneField(User, related_name = 'profile') first_name = models.CharField(max_length=120, blank=True, null=True) last_name = models.CharField(max_length=120, blank=True, null=True) following = models.ManyToManyField(User, related_name = 'followed_by', blank=True, through='FollowingRelation') class FollowingRelation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) I'd like to query all rows from BlogPost that have been created by the session user, plus all other posts created by the users that the sessionUser is following, but has a timestamp greater than or equal to the timestamp when the session user started following. The raw sql query is something like this: select * from blog_blogpost A where A.user_id = sessionuserid or A.timestamp >= ( select timestamp from userprofile_followingrelation where user_id = A.user_id and userprofile_id = (select id from userprofile_userprofile where user_id = sessionuserid) ) I am unable to build this query in django. -
How to backup postgis database via terminal in linux?
I tried to back up a PostGIS database via terminal from the info from the site https://postgis.net/workshops/postgis-intro/backup.html like this pg_dump --file=test_pro.backup --format=c --port=5432 --username=postgres test_pro but I am encountering an error like this pg_dump: [archiver (db)] query failed: ERROR: could not access file "$libdir/postgis-2.5": No such file or directory pg_dump: [archiver (db)] query was: SELECT a.attnum, a.attname, a.atttypmod, a.attstattarget, a.attstorage, t.typstorage, a.attnotnull, a.atthasdef, a.attisdropped, a.attlen, a.attalign, a.attislocal, pg_catalog.format_type(t.oid,a.atttypmod) AS atttypname, array_to_string(a.attoptions, ', ') AS attoptions, CASE WHEN a.attcollation <> t.typcollation THEN a.attcollation ELSE 0 END AS attcollation, a.attidentity, pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(option_name) || ' ' || pg_catalog.quote_literal(option_value) FROM pg_catalog.pg_options_to_table(attfdwoptions) ORDER BY option_name), E', ') AS attfdwoptions FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_type t ON a.atttypid = t.oid WHERE a.attrelid = '23466'::pg_catalog.oid AND a.attnum > 0::pg_catalog.int2 ORDER BY a.attnum this is my django database setting DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test_pro', 'USER': 'postgres', 'PASSWORD': 'test_pro', 'HOST': 'localhost', 'PORT': '5432', } } what can I do to backup the PostGIS database via the terminal in linux -
django admin site has been occurred with s3, cloudfront
enter image description here enter image description here As you can see above, I'm using AWS S3 and Cloudfront through the django-storages library. But since I recently started using the cloudfront key, 403 errors have occurred on the admin site. -
Django error updating -> invalid literal for int() with base 10
i have the following problem when i tried to update a Ingredient... Internal Server Error: /menu/edit-plate/a6bf6537-878e-4321-8446-f3caad5a71dc Traceback (most recent call last): File "/home/l30n4rd0/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'a6bf6537-878e-4321-8446-f3caad5a71dc' ¿Can you help me? Here my code: Model: from django.db import models from django.urls import reverse import uuid from menu.models.ingredient import Ingredient class Plate(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID único para este plato") title = models.CharField(max_length=200) ingredient = models.ManyToManyField(Ingredient, help_text="Seleccione un ingrediente para este plato") def __str__(self): """ String que representa al objeto Book """ return self.title def get_absolute_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('plate-details', args=[str(self.id)]) def get_edit_url(self): """ Devuelve el URL a una instancia particular de Menu """ return reverse('edit-plate', args=[str(self.id)]) View functions: class PlateCreate(generic.CreateView): model = Plate fields = ['title', 'ingredient'] success_url = 'plate-list' class PlateDetailView(generic.DetailView): model = Plate class PlateUpdate(generic.UpdateView): model = Ingredient fields = ['title', 'ingredient'] template_name_suffix = '_update_form' success_url = '/menu/plate-list' class PlateListView(generic.ListView): model = Plate Template: <form method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Update"> </form> Urls.py from django.conf.urls import url from django.urls import path, include from . import views urlpatterns = [ url(r'^create-plate$', views.PlateCreate.as_view(), name='create-plate'), url(r'^plate-list/$', … -
How to fix Facebook has detected MyAppName isn't using a secure connection to transfer information
I am trying to implement facebook social Oauth login on my Django app but I am faced with the below error. I have tried changing my http protocol from http to https on Valid OAuth Redirect URIs. But I am still faced with the same problem. -
Deploy Django app on Microsoft Azure with Local Package
I would like to deploy an Django App on to Microsoft Azure through the App Service. In the requirements.txt I have a package that I wrote myself and need to install from local directory which is in the same directory as manage.py. I have tried to deploy the app through local git, and everytime it is running into the error it is not able to import the local package although it is able to install it with no problem in "antenv" (the virtual env Azure creates automatically) -
'decimal.Decimal' object is not iterable an error occurred django
im getting an error while trying to loop and get total of a decimal object in a django model, tried so many soloutions all failed. thr error is 'decimal.Decimal' object is not iterable and here is the model and object.. class Order(models.Model): # customer = models.ForeignKey(Customer, on_delete=models.CASCADE) total_price = models.DecimalField(max_digits=10, decimal_places=2, default=0) #success = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=True) # product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return 'Order {0}'.format(self.id) @property def order_prices(self): order = 0 for o in self.total_price: order += o return order -
How can I get unread messages for each user?
I'm creating a django web application. I want to create a one way messaging system so users can receive messages from admin. Currently I did this using a model like below: from django.db import models from django.contrib.auth.models import User class AdminMessage(models.Model): title = models.CharField(max_length=120) receivers = models.ManyToManyField(User) message = models.TextField() is_read = models.BooleanField(default=False) the problem is I want each user to be able to see his unread messages in his profile. how can I do that?