Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
connecting list view and detail view -django
i am trying to create class based detailed view, which can be accessed by clicking listview items.. the problem is it was easly achieved in function based views but cant do the same in class based views. model.py from django.db import models import datetime # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title views.py from.models import BlogPost , EDITORIAL_RESPONSIBILITIES , Reviewers ,Confrences ,ABSTRACT_IN_CONFERENCES class BlogList(ListView): model = BlogPost template_name = 'blog/bloglist.html' context_object_name = 'post' class BlogDetail(DetailView): model = BlogPost template_name = 'blogdetail.html' urls.py path('list', BlogList.as_view(), name='list'), path('(?P<id>\d+)/', BlogDetail.as_view()) listview template is working absolutely fine.. the directory structure is fine.. both listviw.html and detail.html are in same folder under templates/blog/ .. listview template <div class="post-body"> {% for p in post %} <blockquote>{{p}}</br></br>{{p.Date}}</blockquote> {% endfor %} </div><!-- end post-body --> -
Django - how to create a form for two models that is related?
I have a model called Kitchen and a model called Furnitures. A kitchen has lot of furnitures, how can I create a form/view/template in a way that the user can fill the info about these two models at the same time and when the button is pressed the two models are created and already related with each other? Is that possible? -
Cannot call QuerySet with a ForeignKey in Django
Version Mac OS : 10.15.6 Django : 3.7.6 What I want to do Get all Want_Items that are had by a specific user Hello, I'm a beginner to Django. I am trying to create an app that each can exchange their items. I created models, User, Parent_Item, Want_Item, Give_Item. And I set relations between them like below. User - Parent_Item => One To Many Parent_Item - Give_Item => One To Many Parent_Item - Want_Item => One To Many I succeeded in getting all parent_item that one user has. However, I cannot get want_item for some reason. This is my attempts and errors I was faced with. >>>toshi_want = Toshi.item.want_item.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'RelatedManager' object has no attribute 'want_item' >>> toshi_all=Toshi.item.all() >>> print(toshi_all) <QuerySet [<Parent_Item: MacBook>, <Parent_Item: Desk>, <Parent_Item: shirt>]> >>> print(toshi_all.want_item.all()) Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'want_item' I surely set a ForeignKey with related_name = "want_item". Why cannot I use this in this case?? I would like you to teach me solutions and why it happens. models.py class User(models.Model): username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) password = … -
Django Foreign Key Constraint failed after blank = True
I get an Integrity error, Foreign Key Constraint failed. I have the following function I am trying to run: if request.method == "POST": #Get token access_token = AccessToken.objects.get(token = request.POST.get('access_token'), expires__gt = timezone.now()) #Get profile customer = access_token.user.customer # Check if customer has a order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.POST["address"]: return JsonResponse({"status": "failed", "error": "Address is required."}) # Ger Order Details order_details = json.loads(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] if len(order_details)>0: # Step 1 - Create an Order order = Order.objects.create( customer = customer, restaurant_id = request.POST["restaurant_id"], total = order_total, status = Order.PENDING, address = request.POST["address"] ) # Step 2 - Create Order details for meal in order_details: OrderDetails.objects.create( order = order, meal_id = meal["meal_id"], quantity = meal["quantity"], sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] ) return JsonResponse({"status": "success"}) Here is my order class: Class Order(models.Model): PENDING = 1 COOKING = 2 READY = 3 ONTHEWAY = 4 DELIVERED = 5 STATUS_CHOICES = ( (PENDING, "Pending"), (COOKING, "Cooking"), (READY, "Ready"), (ONTHEWAY, "On The Way"), (DELIVERED, "Delivered"), ) customer = models.ForeignKey(Customer, … -
Django - How to get all items from a model that has foreign key?
I'm creating two models: Feedstockformula and formula. This is the code for each one: FeedstockFormula: from django.db import models class FeedstockFormulas(models.Model): ratio = models.FloatField() feedstock = models.OneToOneField("dashboard.Feedstock", on_delete=models.CASCADE, default="0") formulas = models.ForeignKey("dashboard.Formulas", on_delete=models.CASCADE, default="") Formula: from django.db import models class Formulas(models.Model): name = models.CharField(max_length=100) cost = models.FloatField() weight = models.FloatField() How can I get all the FeedstockFormulas that is part of a Formula? -
Django-Import-Export: Import Error - AttributeError: 'str' object has no attribute 'year'
I'm trying to use the django-import-export package to import a csv into my django model. the csv is very simple, a header row and the one row of values. there are two fields on the csv that are defined in the model as DateField's #models.py edit_date = models.DateField(verbose_name="Edit Date", blank=True, default="1970-01-01") premiere_date = models.DateField(verbose_name="Premiere Date", null=True, blank=True) there are another set of DateTime.Field's in the model that are not included in the csv file. I have added header fields to the csv for these, but the csv hs no values for the fields. created = models.DateTimeField(blank=True) updated = models.DateTimeField(blank=True) deleted_at = models.DateTimeField(blank=True,null=True) For the django-import-export package, I have a Resource class defined in my admin.py and it is working for exporting a csv. But when I try to import a csv - I get an Attribute Error. AttributeError: 'str' object has no attribute 'year' The full traceback is listed below. I've tried to fix this by adding a before_save_instance method to the Resource class. But I'm still getting the same error. I've been through the docs and searched stack overflow, but I can't find a clear explanation of how to handle imports with the import-export package. #admin.py from datetime import … -
Does the django-rest-framework provide an admin site to manage models?
I'm looking to setup a REST API server with django, and googling suggests this is best done using the django-rest-framework. The API will return objects stored in a database, and I would also like to be able to add/modify the objects in the database using the django admin site. However, looking at the django-rest-framework documentaion, I see no reference to the admin site (I did find things about "AdminRenderer", but it looked like this isn't what I want). Simply, does the django admin site exist for a django-rest-framework project? -
Django Access Token Matching Query Does Not Exist
I have the following code I am trying to test: def customer_add_order(request): """ params: access_token restaurant_id address order_details(json format), example: [{"meal_id": 1, "quantity":2}, {"meal_id": 2, "quantity":3}] stripe_token return: {"status": "success"} """ if request.method == "POST": #Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) #Get profile customer = access_token.user.customer # Check if customer has a order that is not delivered if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"}) # Check Address if not request.POST("address"): return JsonResponse({"status": "failed", "error": "Address is required."}) # Ger Order Details order_details = json.load(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal[quantity] if len(order_details)>0: # Step 1 - Create an Order order = Order.objects.create( customer = customer, restaurant_id = request.POST["restaurant_id"], total = order_total, status = Order.PENDING, address = request.POST["address"] ) # Step 2 - Create Order details for meal in order_details: OrderDetails.objects.create( order = order, meal_id = meal["meal_id"], quantity = meal["quantity"], sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] ) return JsonResponse({"status": "success"}) I enter the params in Postman, and use an access token that shows valid in django, and it hasn't expired. I am using the rest framework and the function … -
Django Admin page models name instead of TABLE object(id)
Is there any way to change the way objects are named in Django Admin page. Currently all of the objects are using a TABLE Object(id) as their name: table in admin page Can i make it for example a key form the table like a name or smth. And is there any way to add search bar that goes over the names of the items in the table to filter it by that name. -
Unable to import apps from settings.py's INSTALLED_APPS list
I'm hitting an error when running makemigrations, and it seems to be related to my INSTALLED_APPS list. Here is a screenshot of my project: and here is the error: I've also attempted to use the following strings in the INSTALLED_APPS list, but I got the same error: '.api.apps.ApiConfig', '.pizzas.apps.PizzasConfig', The classes ApiConfig and PizzaConfig both follow this structure in their respective apps.py files: from django.apps import AppConfig class PizzasConfig(AppConfig): name = 'pizzas' Does anyone have any ideas as to what I could be missing here? -
Pinax-teams: what does self.memberships mean in BaseTeam?
I am trying to understand each step of the Pinax-teams models.py file (https://github.com/pinax/pinax-teams/blob/master/pinax/teams/models.py). I can't work out what memberships in the following method (belonging to the BaseTeam class) refers to: def for_user(self, user): try: return self.memberships.get(user=user) except ObjectDoesNotExist: pass There are several ForeignKey fields in other classes with related_name="memberships" but none of these fields link to the BaseTeam class directly. Please can someone tell me what memberships means? -
Filtering elements from Django database on two conditions
I want to select elements from my Django database on two conditions - whether the boolean value "used" is true and whether or not the "dateUsed" is within the last 20 days. However, my current filter statement is returning an empty QuerySet, even though there should be elements that meet both conditions. Am I filtering the elements correctly? I've attached the code that filters the elements, the definitions of my models, as well as the block of code that changes the value of "used" once the model elements have been displayed on my site. Filter: def pastSongs(request): window = datetime.now().date() - timedelta(days=20) songHistory = Song.objects.filter(used = True).filter(dateUsed__gt = window) ent = {} ent["ent"] = songHistory return render(request, 'rollingStone/songs.html',ent) Models: class Song(models.Model): rank = models.IntegerField() artist = models.CharField(max_length=100) title = models.CharField(max_length=100) cover = models.URLField() writers = models.CharField(max_length=100) producers = models.CharField(max_length=100) releaseInfo = models.CharField(max_length=100) description = models.TextField(max_length=3000) used = models.BooleanField(default=False) dateUsed = models.DateField(auto_now=True) Changing "used" field: def reload(): # Change status of old song/album to used, and save the date that it was used if entry["status"] == "filled": currentSong = Songs.objects.get(entry["songEnt"].name) currentAlbum = Albums.objects.get(entry["albumEnt"].name) currentSong.dateUsed = datetime.now().date() - timedelta(days=1) currentAlbum.dateUsed = datetime.now().date() - timedelta(days=1) currentSong.used = True currentAlbum.used = True currentSong.save() currentAlbum.save() -
Trying to understand how to add to cart in Django ecommerce tutorials
I have been following this tutorials for quite some time by JustDjango on youtube here is the link https://www.youtube.com/watch?v=Xjty8q524Jo&t=3s I don't actually understand logic in add to cart function the codes are not just making sense to me. @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, 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] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("core:order-summary") else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("core:order-summary") This part below confuses me a lot. Who can explain wat dis means order = order_qs[0] order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): Is there anytutorials that explains adding to cart in django very well, I will like to see it What is the logic in this if and else along with the nested if else inside it if order_qs.exists(): ............... # check if the order item … -
Is there an elegant way to export a Bootstrap-Studio project to a folder of lovely Django templates?
Dear wise and experienced spirits of StackOverflow, I am turning to thee in deep despair. My teacher gave me the honourable task to design a data-administration interface for our school paramedics. Somehow experienced in Python through machine learning I planned on writing the backend of the website with Django, as I did not have any interest in learning a fully new language / framework in such short time. Because of me being quite a greenhorn when it comes to WebDev, I remembered owning a license for Bootstrap-Studio through GitHub-Edu. As you might guess, I now have a fairly pretty frontend with all those forms I needed, but am unable to convert it into these Django templates that I need even more. I reeeeaaaaally hope that there might be any chance of getting this project done as ASAP as possible (see what I did there, huh?), because I am really running out of mental fuel these days. Yes, I might be a fool, but there are so many deadlines to hit... :( Thank you very much in advance, every tiniest bit of help is higly appreciated. Thus indebted to you for your pains taken for me, I bid you farewell. -
What is the difference in localhost:8000 and http://127.0.0.1:8000?
I am running a Django project with react redux (trying to implement authentication system) and the very weird thing i observed that my site is rendering properly when i use localhost:8000 or http://127.0.0.1:8000. But when i m trying to login/signup (ie trying to send post request) then it working only when i use localhost:8000, and giving some error when using http://127.0.0.1:8000. One of the error when using http://127.0.0.1:8000 is shown below. However i have seen this and found localhost will often resolve to ::1, the IPv6 loopback address. But i am getting is it related to this or not ? And whether localhost:8000 and http://127.0.0.1:8000 is same or not ? Please try to answer in simple words because I have not much knowledge of internet protocol or networking. -
Django Admin StackedInline
I have a stackeinline Django admin. This is used to add multiple products for a shop. However, when I click on 'Save and add another' it sometimes shows 'Entity too large', even when the files are below the allowed size, or sometimes it shows 'DATA_UPLOAD_MAX_NUMBER_FIELDS' error. My question is, does Django stackedinline admin save each and every object each time we click on save? If no, then what could be the reason for this error? -
Creating instances of 2 related models using nested serializer in Django
I am a newbie at Django and I have come across this problem with my code. I have a Custom User Model and an Account model which are related by many-to-many field. During SignUp a user is asked to either create an Account or not ( join other account through a link ). If the User creates an Account then he is the owner of the account and other Users can join the account.(Did not finish the code for ownership) One User can be a part of several accounts at the same time. Creation of Account(or not) and the User takes place in the Signup view. I read up about the nested serializer in the documentation and i think this should create the two models instances. How to create relationships in one view using nested serializers? Other Approaches to solve the issue? Models class Account(models.Model): AccountName = models.TextField(max_length=100, blank=False, null=False) class User(AbstractBaseUser): AccountName = models.ManyToManyField(Account) CreateAccount = models.BooleanField(blank=False, null=False) EmailId = models.EmailField(max_length=128, blank=False, null=False, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'EmailId' REQUIRED_FIELDS = ['AccountName', 'CreateAccount',] # Implemented the other req. functions objects = MyAccountManager() Serializers class AccountCreationSerializer(ModelSerializer): class Meta: model = … -
Rendering ForeignKey objects in template with Django
I'm having trouble rendering related objects in a template. I have a Page model, that has a ForeignKey relationship to itself to define parent-child relationships. class Page(BaseModel): title = models.CharField( max_length=280, blank=False, null=False, ) description = models.CharField( max_length=280, blank=False, null=False, ) slug = models.SlugField( blank=False, null=False, ) is_home = models.BooleanField( default=False, ) is_parent = models.BooleanField( default=False, ) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, default='Home', blank=True, null=True, related_name='children', ) content = RichTextField( blank=False, null=False, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('page_detail', args=[str(self.slug)]) My views.py filters out non-parent pages: class PageListView(ListView): queryset = Page.objects.filter(is_parent=True, is_home=False) template_name = 'pages/page_list.html' context_object_name = 'page' But when it comes to rendering 'child' objects in my template, I'm stuck. I've figured that I need a loop within a loop (first for parent pages, second for child pages per parent page), but can't get the second loop to work. Here was my latest attempt, which got me a "'Page' object is not iterable" error. {% extends '_base.html' %} {% block content %} <div class="container"> {% for page in page %} <p>{{ page.title }}</p> {% for children in page %} <p>{{ page.title }}</p> {% endfor %} {% endfor %} </div> {% endblock content %} -
Passing html code from django and also from Javascript. How can I improve this?
I am making a twitter like social web page por homework. In one single page I have a form to write a tweet and enough space down there to show the tweets. To dynamicaly show them I`m using javascript fetch api to intercept the form and show them asynchronously: document.querySelector('form').onsubmit = (event) => { event.preventDefault(); fetch("", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { document.querySelector('#new_message').value = "" let div = document.createElement('div') div.innerHTML = ("<p>" + result.creation_date + "</p>" + "<a href='#'>" + result.username + "</a>" + ' said:' + '<br><br>' +"<div class='container'>" + "<p>" + result.body + "</p>" + "</div>"); div.style.cssText = "box-shadow: 0px 0px 2px; ; background-color:#F5F5F5; border-radius:10px; padding: 10px; margin: 5px;"; document.querySelector('#posts').append(div); }); } This dinamically shows the tweet when it`s written withouth reloading the page. But the problem comes when I want to display them when a user actually reloads the page, i mean, via a get method: if request.method == "GET": if request.user.is_authenticated: posts = Posts.objects.all().order_by('-creation_date') return render(request, "network/index.html", { "posts":posts }) else: return render(request, "network/login.html") This makes me handle the tweet html from the javascript code and also with django … -
Django site cycling between two views using schedule function
I created a site in Django that's supposed to cycle display a different song and album each day from Rolling Stone's top 500. However, if you refresh the site a few times, it eventually displays a different song and album than it originally did. What's more, it eventually goes back to the original song and album choices after a few more refreshes. Even stranger, it only switches between the same two song and album combinations, it never spontaneously picks a new song/album or adds a new set of songs and albums to the rotation. I've attached my views.py code responsible for displaying my home screen and loading a new song/album, let me know if you see the issue. entry = {"status": None} # Define song and Album of the day def reload(): # Change status of old song/album to used, and save the date that it was used if entry["status"] == "filled": currentSong = Songs.objects.get(entry["songEnt"].name) currentAlbum = Albums.objects.get(entry["albumEnt"].name) currentSong.dateUsed = datetime.now().date() - timedelta(days=1) currentAlbum.dateUsed = datetime.now().date() - timedelta(days=1) currentSong.used = True currentAlbum.used = True currentSong.save() currentAlbum.save() # If there is no old song, skip above step and begin adding new songs else: entry["status"] = "filled" song = Song.objects.filter(used = False).order_by("?").first() … -
Heroku Internal Server Error when Debug is False and collectstatic dosen't work - Django
I deployed an app to Heroku, which uses Postgres. Anytime I set Debug to True, it works fine. When I set it back to False, it gives an Error 500, Internal Server Error. I don't know why it does that. Does it have to do with staticfiles? I am using whitenoise for serving static files. Anytime I run heroku run python manage.py collectstatic, it gives me Running python manage.py collectstatic on djangotestapp... up, run.9614 (Free) 300 static files copied to '/app/staticfiles', 758 post-processed. When I then run heroku run bash, I find out that there is no staticfiles folder. Where exactly does it copy the static files to? Is this what is causing the Error 500? How can I solve it? settings.py import os import dj_database_url from decouple import config, Csv # 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/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = 200 SECURE_HSTS_PRELOAD = True ALLOWED_HOSTS … -
How to stop Django from removing stop words in auto-generated slugs from prepopulated_fields?
I am developing a dictionary application using Django. I would like the URL to contain the dictionary headword currently being examined, and I would like this to happen automatically. Using Django prepopulated_fields, however, when I insert headword "this is my headword", I get the slug "my-headword". How can I tell Django to generate the slug "this-is-my-headword" instead? In other words, how do I stop it from removing stop words from auto-generated slugs? Here is my Headword class in models.py: class Headword(models.Model): headword = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=32, unique=True) def __str__(self): return f"{self.headword}" And here is my HeadwordAdmin class in admin.py: class HeadwordAdmin(admin.ModelAdmin): fieldsets = [ (None, {"fields": ["headword"]}), ("URL", {"fields": ["slug"]}), ] inlines = [DefinitionInline] list_display = ("headword",) search_fields = ["headword"] prepopulated_fields = {"slug": ("headword",)} -
'RedisChannelLayer' object is not callable
I have a Django app I'm using Django channels when deploying this app to Heroku I get this error 'RedisChannelLayer' object is not callable This is the trackback for this error 2020-08-29T19:33:37.543129+00:00 app[web.1]: 2020-08-29 19:33:37,542 DEBUG HTTP b'GET' request for ['10.9.251.250', 35308] 2020-08-29T19:33:37.543586+00:00 app[web.1]: 2020-08-29 19:33:37,543 ERROR Traceback (most recent call last): 2020-08-29T19:33:37.543592+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/daphne/http_protocol.py", line 180, in process 2020-08-29T19:33:37.543593+00:00 app[web.1]: "server": self.server_addr, 2020-08-29T19:33:37.543594+00:00 app[web.1]: TypeError: 'RedisChannelLayer' object is not callable 2020-08-29T19:33:37.543599+00:00 app[web.1]: 2020-08-29T19:33:37.543727+00:00 app[web.1]: 2020-08-29 19:33:37,543 DEBUG HTTP 500 response started for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544107+00:00 app[web.1]: 2020-08-29 19:33:37,543 DEBUG HTTP close for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544398+00:00 app[web.1]: 2020-08-29 19:33:37,544 INFO "10.9.251.250" - - [03/Jan/1970:21:31:20 +0000] "GET /favicon.ico HTTP/1.1" 500 452 "https://belkahla-mohamed-chatapp.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.9 Safari/537.36" 2020-08-29T19:33:37.544593+00:00 app[web.1]: 2020-08-29 19:33:37,544 DEBUG HTTP response complete for ['10.9.251.250', 35308] 2020-08-29T19:33:37.544687+00:00 app[web.1]: 10.9.251.250:35308 - - [29/Aug/2020:19:33:37] "GET /favicon.ico" 500 452 this is my asgi.py file: import os import django from channels.routing import get_default_application from channels.layers import get_channel_layer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ProfilesApp.settings.development') django.setup() application = get_default_application() channel_layer = get_channel_layer() settings.py ASGI_APPLICATION = "ProfilesApp.routing.application" WSGI_APPLICATION = 'ProfilesApp.wsgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, }, } Please let me know how to fix … -
Django on Google Cloud App Engine: No Module Named 'django'
I am trying to deploy a Django website to GAE, but I keep getting a 502 error. When I look at the log files, I see this: "Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/env/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/srv/main.py", line 1, in <module> from tanuki.wsgi import application File "/srv/tanuki/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django'" I have Django installed on my virtual environment and my sys.path includes the path to the site-packages. Is there something else I am missing? -
How to change this code to make sure the User can only send a follow request once and not multiple times?
Hey guys I have a model and a function to send follow request to other users and they will be accepting the request if the sender has to follow them. problem is I need to make sure that when the sender first sends a request, the button shouldn't show follow again, instead should show cancel option to delete that request. As of now the user can send requests again and again. These are the codes. def send_follow_request(request, username): user_from = request.user user_to = Account.objects.get(username=username) # is_requested = False send_request = notify.send(user_from, recipient=user_to, verb='has sent you a follow request', target=user_to) # is_requested = True return redirect('posts:userprofile', user_to.username) models.py class Contact(models.Model): user_from = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_from_set', on_delete=models.CASCADE) user_to = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_to_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, db_index=True) follow_status = models.CharField(choices=FOLLOW_STATUS, max_length=10) #USER_FROM IS THE ONE WHO IS FOLLOWING AND USER_TO IS ONE BEING FOLLOWED class Meta: ordering = ('-created',) def __str__(self): return f'{self.user_from} follows {self.user_to}' following = models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False) #adding the above field to User Model class user_model = get_user_model() user_model.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) Thank you