Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django soft resize uploaded Image to multiple sizes and upload to respective folder
I have the following model on my App def image_path(self, filename): return 'app_name/images/{}/{}'.format(slugify(self.name), filename) class Color(models.Model): name = CICharField(max_length=22, unique=True) image = models.ImageField("Image", upload_to=image_path, blank=True) Once the image is uploaded I want to create 3 images size: small (100 by 100), medium (300 by 300) and large (800 by 800) with the soft image crop. Then I want to manage the URL Structure for my upload. For Eg. Original Image URL from "Image" field = 'app_name/images/image_1.jpg' if I upload the image, Then it will produce the following images. small = 'app_name/images/small/image_1.jpg' medium = 'app_name/images/medium/image_1.jpg' large = 'app_name/images/large/image_1.jpg' Can anyone tell me, How can I achieve this on Django. Thanks. -
How do I consume data from Django Rest Framework API with frontend javascript (separate repository)
I can view my api with the Browsable API and I can make calls to my DRF API using postman, but I can't seem to integrate with a frontend. The same goes whether it is deployed or local. These are the headers from the response in Postman: Date →Sat, 05 Sep 2020 23:29:15 GMT Server →WSGIServer/0.2 CPython/3.8.5 Content-Type →application/json Vary →Accept, Cookie Allow →GET, HEAD, OPTIONS X-Frame-Options →DENY Content-Length →185 X-Content-Type-Options →nosniff Referrer-Policy →same-origin These are some of the settings I have implemented for my DRF API settings: ALLOWED_HOSTS = ['*'] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny' ], 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], } MIDDLEWARE_CLASSES = ( 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ) CORS_ORIGIN_ALLOW_ALL=True Here's a call that I'm attempting to make from my local react project which returns empty: const [data, setData] = useState(); useEffect(async () => { const result = await axios.get( 'http://127.0.0.1:8000/movies/1', { headers: { 'Content-Type': 'application/json' } } ); setData(result); }, []); I've attempted to consume the data with local and remote JS frontends to no avail. -
How to check if value from a field in a table object is equal to specific string in django template language?
I am iterating over all the entries in a django table called Ideas. One field in the table is status, and I want to check if the status is equal to some specific string. I have already checked that I am accessing this field correctly, with idea.status in my case, but I can't find how to compare that entry to a specific string in the django template language docs. I am trying to change a table's cell color based on what is in that cell. Here is what I tried, but to no avail: {% for idea in ideas_list %} ... {% if idea.status == 'Not Started' %} <td style="background-color:red;"> {% elif idea.status == 'Completed' %} <td style="background-color:green;"> {% elif idea.status == 'In Progress' %} <td style="background-color:yellow;"> {% else %} <td> {% endif %} {{idea.status}} &nbsp;</td> ... {% endfor %} My page is still rendering with the status text in the table, suggesting to me that all the if's were failed, which would end in the else condition being met, giving <td>{{idea.status}} &nbsp;</td>, with no cell color, and suggesting to me the problem is in my if statements themselves. -
is there way to add Pagination to html page in Django?
i have problem when i try to add pagination to my home html page , i tried this in my code but i got error .. i tried do this : views.py def home_page(request, template='html_file/enterface.html'): contextt = { 'opratingSystems': OpratingSystems.objects.all(), 'androidgames': AndroidGames.objects.all(), 'androidapk': AndroidApks.objects.all(), 'antivirus': Antivirus.objects.all(), 'pcgames': PCgames.objects.all(), 'pcprogram': PCprogram.objects.all(), } app = pcgames.objects.all() page = request.GET.get('Page', 1) # the_home_page is the name of pages when user go to page 2 etc paginator = Paginator(app, 6) # 6 that's mean it will show 6 apps in page try: pcgame = paginator.page(page) except PageNotAnInteger: pcgame = paginator.page(1) except EmptyPage: pcgame = paginator.page(paginator.num_pages) return render(request,template,contextt) in HTML page : <div class="container"> <div class='row'> {% for pcgame in pcgames %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href=" {{ pcgame.page_url }} "> <img src="{{ pcgame.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3 class="font_control_for_home_page_pc_games_name"><a href=" {{ pcgame.page_url }} ">{{ pcgame.name }}</a></h3> </div> {% endfor %} </div> and in the end of html page i added this {% if pcgame.has_previous %} <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page=1">First</a> <a id="border_pagination" class="btn btn-outline-info mb-4" href="?Page={{ pcgame.previous_page_number }}">Previous</a> {% endif %} {% for num in pcgame.paginator.page_range %} {% if pcgame.number == num %} <a class="btn btn-info mb-4" href="?Page={{ num }}">{{ num … -
Django- TypeError... post() missing 1 required positional argument: 'listing_id'
I am still pretty new to Python and Django stackoverflow has really being my strength during this journey. I am working on a Django app where car owner will list their fleet of cars and drivers interested in renting them for Taxi or Uber will make a request to rent the cars… i basically have three models at this point the users(car owners and drivers) car listed by owners(models.Listing), and model.Rent (request being made by drivers to rent a car), i have a listView to list all the car available and a detailView for showing details of each car, i have a button on the detailed view, when clicked by a Driver i want it to take the logged in driver request.user instance and the primary key from the car Listing model on the detailed view and save it in the rent model… But i am getting a “TypeError at /listing/1/ (post() missing 1 required positional argument: 'listing_id’)” Below are my view.py, models.py and error messages: I have read through various similar questions here, some suggested using Listing.id instead of Listing.pk… that resulted into a ValueError. With regards to stackoverflow’s rule, i’ve spent about a week trying out suggestions from … -
Django : python manage.py runserver (multiple errors)
I started using Django recently for my first web app following a tutorial on youtube, every thing went fine until this command : $ python manage.py runserver meaning i was able to create a virtual environment and create a project using : $ python3 -m django startproject <projectname>. Here's what my manage.py looks like: """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_blog.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) execute_from_command_line(sys.argv) if __name__ == '__main__': main() Here are some of my different attempts and errors: $ python manage.py runserver Error: File "manage.py", line 22, in <module> main() File "manage.py", line 14, in main "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Attempt n°1: $ python pip install django Error: python: can't open file 'pip': [Errno 2] No such file or directory $ python -m pip install … -
How do I pass the streamed tweets from the Twitter stream API to a Django view?
I want to display some of my streamed tweets (say 10 tweets) on my Django app once the user hit the refresh button. I have succeed building the Django app and setting up a connection with twitter stream API using Tweepy. However I am still stuck on passing on the streamed tweets from Tweepy code to my view on Django App. I have my Django and Tweepy streaming codes running at the same time. Here what I have tried so far... My streaming code responsible of: on_status fetches the tweets from API and fills a specific number of tweets into a list called tweets. get_tweets returns the tweets list and then empty it so that it can be update once again. >>> Stream.py tweets = [] class TwitterStreamListener(tweepy.StreamListener): def on_status(self, status): global tweets if len(tweets)< 10: print(status.text) tweets.append(status.text) def on_error(self, status_code): if status_code == 403: print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached") return False # Function to return the retrieved tweets and empty the list so that can be filled once again def get_tweets(): global tweets tweets_copy = tweets.copy() tweets = [] return tweets_copy On the other hand, I … -
UserProfile add Post to Wishlist? error FoodListUser didn't return an HttpResponse object. It returned None instead
I got two related issue I guess. I tried to create a wishlist: When I clic the link to add Post (belongs to the main nutri app) to UserProfile whishlist. I got this : The view user.views.FoodListUser didn't return an HttpResponse object. It returned None instead user/models.py class UserProfile(models.Model): wishlist = models.ManyToManyField(Post, related_name='user_wishlist') ... user/views.py def FoodListUser(request, post_id): post = get_object_or_404(Post, pk=post_id) userprofile = get_object_or_404(UserProfile, user=request.user) if request.method == "POST": userprofile.wishlist.add(post) #request.user.userprofile.follow.add(pk) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) @property def total_wishlist(self): return self.wishlist.count() user/urls.py path('wishlist/<int:post_id>/', FoodListUser, name="foodlist_user"), -
Django + Uvicorn + Gunicorn: object HttpResponse can't be used in 'await' expression
I'm getting this when running django + uvicorn + gunicorn on every request. It's my first time setting this up and it's not clear where things are going wrong, because runserver works fine. Traceback (most recent call last): File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/whitenoise/middleware.py", line 59, in __call__ response = self.get_response(request) File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 139, in __call__ return call_result.result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 428, in result return self.__get_result() File "/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/Users/james/Github/oregano-server/.venv/lib/python3.7/site-packages/asgiref/sync.py", line 204, in main_wrap result = await self.awaitable(*args, **kwargs) TypeError: object HttpResponse can't be used in 'await' expression -
Django doesn't render images
WebSite Admin Panel First of all sorry for bad english. But i cant see my images on my website. I can see titles descriptions. Can you help me. I checked page resources it links my images and there is no problem. thats exactly where my photos are page resources settings.py STATIC_URL = '/static/' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') template <ul class="slides-container"> {% for rs in sliderdata %} <li class="text-center"> <img src="{{ rs.image.url }}" alt=""> <div class="container"> <div class="row"> <div class="col-md-12"> <h1 class="m-b-20"><strong>Hoşgeldiniz <br> Site İsmi</strong></h1> <p class="m-b-40">{{ rs.title}} <br> {{ rs.description }}</p> <p><a class="btn hvr-hover" href="#">İncele</a></p> </div> </div> </div> </li> {% endfor %} views.py def index(request): setting = Setting.objects.get(pk=1) sliderdata = Slider.objects.all()[:3] category = Category.objects.all() context={'setting':setting, 'page': 'home','category':category,'sliderdata':sliderdata} models.py class Slider(models.Model): Status = ( ('True', 'Evet'), ('False', 'Hayır'), ) title = models.CharField(max_length=150) description=models.CharField(max_length=255) image = models.ImageField(upload_to='images/', blank=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title -
Django creates another media folder inside media folder
I'm a beginner with Django and that's exactly what it does. I do just as it was in the documentation but anyway maybe something went wrong? From admin-page I adding\setting-up a product and choosing the 'image', then when I'm saving it creating a thumbnail and trying to save in '/media/uploads/' but instead it's creating another 'media' folder and the image stored in '/media/media/uploads/img.png' when path on site is '/media/uploads/img.png'. Here is the code: /shop/settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # or even 'media/' /shop/urls.py: urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after that's added, then in my Product model I do: /apps/store/models.py: class Product(models.Model): ... image = models.ImageField(upload_to='media/uploads/', blank=True, null=True) thumbnail = models.ImageField(upload_to='media/uploads/', blank=True, null=True) ... def save(self, *args, **kwargs): self.thumbnail = self.make_thumbnail(self.image) super().save(*args, **kwargs) @staticmethod def make_thumbnail(image, size=(512, 512)): if not image: return img = Image.open(image) if img.mode in ('RGBA',): # converting image to RGB if it's RGBA img.load() rgb_convert = Image.new('RGB', img.size, 0) rgb_convert.paste(img, mask=img.split()[3]) img = rgb_convert img.thumbnail(size) thumb_io = BytesIO() img.save(thumb_io, 'PNG', quality=80) thumb = File(thumb_io, name=image.name) return thumb I tried to change 'upload_to' to 'uploads/' and then it stores files in the right direction but path to it on-site also changes to … -
Implementing a following system and fetching posts of people a user follows in django
I am designing a social media site and have a model of follower/following system that when a following relationship is made the feed will get all the posts by the followers of the user, I have tried to make the model for my user class and the post class as following: Class User(AbstractBaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=30) email = models.EmailField(max_length=30, unique=True) contact_no = models.CharField(max_length=15) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) class Post(models.Model): posted_by=models.ForeignKey(User,on_delete=models.CASCADE) date= models.DateField(auto_now=True) time=models.TimeField(auto_now=True) content=models.CharField(max_length=2000) media=models.ImageField(blank=True) and this is the model that establishes the relationship between two users. class Following(models.Model): user_id = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE) following_user_id= models.ForeignKey(User,related_name='followers',on_delete=models.CASCADE) class Meta: unique_together = ("user_id", "following_user_id") But when I try to combine things while calling upon the posts of the concerned user through this code class Feed(): def __init__(self,User): self.following=Following.objects.filter(user_id=User).values('following_user_id') def GetPosts(self): self.post=Post.objects.filter(posted_by__in=self.following) But this returns me an empty list even after creating the objects, If any of you guys could help me with it in anyway, I would really appreciate it. -
Django API: Revoke tokens after a certain amount of request
I am trying to code an API that would receive a string or a list of strings and return my model's predictions. I use token authentication for the ease of use, however, I don't understand/can't imagine how I can limit the amount of requests a user can make on a per month basis. Or give a limited amount of requests to an anonymous user. Should I create a custom permission class ? ### settings.py ## INSTALLED_APPS = [ # basics 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # API 'rest_framework', 'rest_framework.authtoken', # auth 'rest_framework_tracking', # logging ] ## views.py ## class MyAPIView(APIView, LoggingMixin): logging_methods = ['POST', 'PUT'] authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] renderer_classes = [BrowsableAPIRenderer, JSONRenderer, CSVRenderer] parser_classes = [JSONParser, MultiPartParser] def post(self, request, proba=False): query = request.POST.get('q') content = { 'result': "Model predictions." } return Response(content, status=status.HTTP_200_OK) -
How to convert an object in django rest framework to a hyperlink
Here is the result of my serializer model "saved_homes": [ { "id": 23, "saved_home": { "home_id": 1, "home_price": 120000, "home_type": "Flat", "virtual_tour_url": "https://www.youtube.com/watch?v=LnsIJcx6fqY", "hoa_dues": 1000, "address": "112 Salleydeen Street, Tema Community 25", "number_bedrooms": 4, "number_bathrooms": 3, "lot_size": 2400, "year_built": 2010, "describe_home": "A home full of the latest technology", "related_website": "https://www.youtube.com/watch?v=tkuqpsyktvA", "love_about_home": "The amount latest technology built in this house" } } ] so I am wondering, is they a way in django rest framework that I can make a reference to another api endpoint using saved_home id(home_id); So I want saved_homes to be something like this; "saved_homes": [ { "id": 23, "saved_home": { "http://localhost:8000/api/homes/1/" } } ], -
Unexpected format when passing a DateField straight to a template
I have a DateField on my model. And I'm passing the fields value straight into a DocxTemplate, where it comes out as "YYYY-mm-dd" format. I was wondering if there is a way of letting Django format the date so that it comes out in a localised format? In "models.py": class Bar(models.Model): date_fld = models.DateField() Generating the "docx": from app.models import Bar from django.shortcuts import get_object_or_404 from docxtpl import DocxTemplate ... bar = get_object_or_404(Bar, pk=1) tpl = DocxTemplate("tpl.docx") context = { 'foo': bar.date_fld, } tpl.render(context) tpl.save("result.docx") I know that I could use a function to convert the date to a string, but it doesn't seem like a Django way of doing things: def getDateString(date): return date.strftime('%d/%m/%Y') And then: context = { 'foo': getDateString(bar.date_fld), } -
Django Rest Framerowk setting user/owner to a ModelSerializer (Tweet)
I am new to DRF. While creating the twitter app I faced a problem with serializers. Since the user is required - I need somehow to pass the actual user to the TweetSerializer class. I have tried different methods that did not work. This is giving me an error owner = serializers.HiddenField(default=serializers.CurrentUserDefault()) error image error image continued also i have tried to se the user by passing it tot he serializer constructor serializer = TweetSerializer(owner=request.user) also did not work class TweetSerializer(serializers.ModelSerializer): try: owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) except Exception as exception: print(exception) class Meta: model = Tweet fields = '__all__' read_only_fields = ['owner'] def validate(self, attrs): if len(attrs['content']) > MAX_TWEET_LENGTH: raise serializers.ValidationError("This tweet is too long") return attrs class Tweet(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey('auth.User', related_name='tweets', on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) class Meta: ordering = ['-id'] @api_view(['POST']) def tweet_create_view(request, *args, **kwargs): serializer = TweetSerializer(data=request.POST) user = request.user if serializer.is_valid(): serializer.save() else: print(serializer.errors) return JsonResponse({}, status=400) try: pass except Exception as e: print(str(e)) return JsonResponse({}, status=400, safe=False) return JsonResponse({}, status=201) -
Wishlist / Favourite list - django what's the best way to build it?
I was wondering what is the best way to build a favorite list (from Post) and display it on the User Profile? I got a UserProfile and a Post model. First solution create a new model: class favoriteList(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name='user_favorite') favorite = models.ManyToManyField(Post,related_name='post_favorite') def __str__(self): return self.user.username Second solution build it from UserProfile model: class UserProfile(models.Model): favorite = models.ManyToManyField(Post, related_name='user_favorite') -
How to communicate from a webserver to a local device using UDP?
Here's the scenario: I have a webserver(django) hosted on the cloud, which needs to send some data to an android application (also developed by me) when some event occurs. I don't want to use polling using Http or other protocols from the android. What i want is the webserver to send the data via UDP (socket programming on both android and django). I have tested this by hosting the webserver on my local computer and providing the local IP of the android devices. It works perfectly. The scenario changes when the same server is hosted on the cloud as now, I don't know the public IP of the Android devices. WhatismyIp on google simply shows the public IP of the router which is not enough to route the packets to my local devices. Using a VPN and its managed IP works ofcourse, but is there a way to do this without a VPN? Any help will be appreciated. -
How to work with multiple server and databases in Django?
So I few data collection tasks that involves saving data on multiple servers. Could have saved data on a master server but I use Docker and background tasks to collect data and for some reason background tasks stops while saving data on master server. I have changed settings in postgres file and it can be accessed from different server. I gave up on master server eventually. Now I am accessing the second server using multiple database functionality in Django but it is kind of slow to fetch data from second server and then do operations on it. Is there any solution for faster operation Or a master server kind on thing? -
How can i add an image my homepage with django
First of all i gotta tell that sorry for bad english. Now i am explaining my problem. I ve been working on django for a while. In fact it is first time i used django. I want to get some images by using admin panel. As an example I got some products and i upload its title descriptions images etc on my admin panel. I used {if rs in products} to make it happened. All works right. Titles descriptions all are in my website. But i cant see any image. So i checked my page resources. And images are linked and all is true. (image src="uploads/images/x.jpg") thats where my images are but it doesnt render on my homepage. Thank you all -
Bokeh slider update on Django
I am able to display GeoJson data on a choropleth map using Bokeh on Django but unable to update the source dataframe based on slider input. Using CustomJS callbacks it seems to be possible to modify simple dataframe from within JS but how do we query a dataframe got from django models? Below is my code, any help would be greatly appreciated. #this is the view def dataviz(request): #load the shapefile for world map gdf = geopandas.read_file('/home/naveed/ne_50m_admin_0_countries/ne_50m_admin_0_countries.shp')[['ADMIN', 'ADM0_A3', 'geometry']] #Rename columns. gdf.columns = ['country', 'country_code', 'geometry'] #function to return geojson data based on date def geojson_data(day): if day == 10: day = datetime.date(2020,8,10) df = pandas.DataFrame.from_records(OxCases.objects.filter(count_date=day).values_list()) df = df[[1,4]] df.columns = ['confirmed_cases','country_code'] merged_df = gdf.merge(df,left_on='country_code', right_on='country_code') geojson_data = json.dumps(json.loads(merged_df.to_json())) return geojson_data p = figure(title='My geo map', plot_width=1150, plot_height=500, tools="wheel_zoom,pan", background_fill_color='#FFFFFF') p.toolbar.active_scroll = p.select_one(WheelZoomTool) p.toolbar_location = None p.xgrid.visible = False p.ygrid.visible = False hover = HoverTool(tooltips = [('','@country_code'),('','@confirmed_cases')], # callback = CustomJS(code = code_hover) ) p.add_tools(hover) palette = d3['Category20c'][12] # palette = brewer['BuGn'][9] #Reverse color order so that dark blue is highest obesity. palette = palette[::-1] #Instantiate LinearColorMapper that linearly maps numbers in a range, into a sequence of colors. color_mapper = LinearColorMapper(palette = palette) color_bar = ColorBar(color_mapper=color_mapper, label_standoff=10,width = 20, … -
CKEditor deleting <span> in Django
I'm having a problem with CKeditor (with ckeditor_uploader) in Django, I looked everywhere, found a lot of answers but none of those worked. The solutions I found was inserting one of those to the config.js: CKEDITOR.editorConfig = function (config) { config.allowedContent = true; config.autoParagraph = false; config.extraAllowedContent = 'span(*)'; }; CKEDITOR.dtd.$removeEmpty.span = 0; CKEDITOR.dtd.$removeEmpty['span'] = false; Everytime I click out of source and go back, or save and go back, the span tag is gone: Also, this is what I have in my settings.py: CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': [ 'Source', '-', 'Save', 'NewPage', 'Preview', 'Print', '-', 'Templates']}, {'name': 'clipboard', 'items': [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, {'name': 'editing', 'items': [ 'Find', 'Replace', '-', 'SelectAll']}, {'name': 'forms', 'items': ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe']}, '/', {'name': 'styles', 'items': [ 'Styles', 'Format', … -
Facebook Link Sharing Issue
I have a single "share to facebook" link on my site using Django Social Share. The issue is that the link being posted to Facebook isn't being scraped - the image, the description, and the title are not populating. All OG meta tags are present and correct, so I checked the Facebook Sharing Debugger and it shows the following error: SSL Error Can't validate SSL Certificate. Either it is self-signed (which will cause browser warnings) or it is invalid. Curl Error Curl error: 60 (SSL_CACERT) The site's SSL cert is perfectly valid - no errors or warnings at all. I'm using LetsEncrypt on Apache with a Django app behind it through WSGI. No issues with any other social networks. An example of one of the links giving this error: https://www.netizen.net/news/post/2643/netizen-ranks-184-on-the-2020-inc-5000-list As you can see if you visit the page, there are no SSL errors. The same link is scraped just as expected on LinkedIn, Twitter, and elsewhere but FB seems to have this issue. -
Why do i keep getting this error even though there seems to not be anything wrong?
I keep getting an error that login.html cant be find in the folder that its supposed to be while it is literally there . directory error -
Unable to create a new object for many to many field in Django
I have 2 models (Order and order items)with many to many relation. However, the order item unable to create a new objects even I create a new Order. I will really appreciate for your help. models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) def __str__(self): return f"{self.quantity} of {self.item.product_name}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user views.py def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.item_code = gen_item_code() order_item.save() messages.success(request, 'added to cart') return redirect('product_detail', slug=slug) else: order.items.add(order_item) messages.success(request, 'added to cart') return redirect('product_detail', slug=slug) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.success(request, 'added to cart') return redirect('product_detail', slug=slug)