Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django plotly dash-application returning completely blank page when using django bootstrap components
I'm building a web application with Django and Dash and the excellent django_plotly_dash package. Everything is running smoothly, except for when I attempt to include Django bootstrap components. Adding even a single Django bootstrap component results in a totally blank page - even the html-divs from django_plotly_dash dissappear. Also, the external_stylesheets option seems to be totally ignored, even when add_bootstrap_links=True. This produces the expected output: import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc dis = DjangoDash("test_app_dash", add_bootstrap_links=True) dis.layout = html.Div( [ html.H1("THIS WORKS FINE"), ] ) While this produces a totally blank page (without raising any exceptions): import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc dis = DjangoDash("test_app_dash", add_bootstrap_links=True) dis.layout = html.Div( [ html.H1("THIS WORKS FINE"), dbc.Alert("THIS DOES NOT WORK", id="base-alert", color="primary"), ] ) Here are some of the key files for a minimal working example (see screenshot of full project structure): test_app views.py: from django.shortcuts import render from . import test_app_dash def test(request): return render(request, "test_app/test.html") main urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("test_app.urls")), path('admin/', admin.site.urls), path('django_plotly_dash/', include('django_plotly_dash.urls')) ] test_app urls.py: from django.urls import path from . import views as test_views urlpatterns = … -
custom query set priting in django rest framework
class Topic(models.Model): Title = models.CharField(max_length=150) UserId = models.ForeignKey(User,on_delete=models.CASCADE) GenreId = models.ForeignKey(Genre,related_name='genres',on_delete=models.CASCADE) StartTime = models.DateTimeField(auto_now_add=False) Createdtime = models.DateTimeField(auto_now_add=True) IsBlocked = models.BooleanField() CounterLike = models.IntegerField() IsRepoCalulated = models.IntegerField() def __str__(self): return self.Title class TopicXReport(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s: %s' % (self.TopicId, self.UserId) class TopicXLike(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s: %s' % (self.TopicId, self.UserId) class TopicXVote(models.Model): TopicId = models.ForeignKey(Topic,on_delete=models.CASCADE) UserId = models.ForeignKey(User,on_delete=models.CASCADE) VoteType = models.BooleanField() status = models.BooleanField() IsBlocked = models.BooleanField() Createdtime = models.DateTimeField(auto_now_add=True) def __str__(self): if self.VoteType == True: Votetypebool = "for it" else: Votetypebool = "against it" return '%s "status" %s : %s -> %s' % (Votetypebool, self.status, self.UserId, self.TopicId) i wanted to get api as like all topic fields with topicXlike and topicXreport total number of likes and report i am using django rest framework modelsearializer approach but not able to find spacific like how can i get output how i want output format is below { "id": 1, "Title": "is it", "StartTime": "2020-04-04T16:09:37.781958Z", "Createdtime": "2020-04-14T15:31:11.459409Z", "IsBlocked": false, "totallike": 50, #this fields are coming from topicXlike models "totalvotes": 50,#this fields are coming from topicXvotes models "IsRepoCalulated": 0, "UserId": { "id": 2, "username": "shilpa", … -
AttributeError: module 'django.db.models' has no attribute 'RichTextField'
I'm new to wagtail and am following both official and youtube tutorials (yt ones skip instructions to installing libjpeg and zlib but when I tried to, it says Pillow has them included); Running on windows10, Using latest python, latest wagtail, latest django; Stuck on the first spot, still getting the same issue when running makemigrations or migrate or runserver: File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\home\models.py", line 14, in HomePage banner_subtitle = models.RichTextField(features=["bold", "italic"]) AttributeError: module 'django.db.models' has no attribute 'RichTextField' here's my models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): """Homepage model.""" body = RichTextField(blank=True) templates = "templates/home/home_page.html" max_count = 1 banner_title = models.CharField('Body', blank=True) banner_subtitle = models.RichTextField(features=["bold", "italic"]) banner_image = models.ForeignKey(features= "wagtailImages.Image", null=False, blank=False, on_delete=models.SET_NULL, related_name="+" ) banner_cta = models.ForeignKey( "wagtailcore.Page", ) content_panels = Page.content_panels + [ FieldPanel("banner_title"), ] class Meta: verbose_name = "HomePage" verbose_name_plural = "HomePages" And here's full traceback : Traceback (most recent call last): File ".\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\TalkyWalky\Desktop\Workspace\bloggyblog\venv_bloggyblog\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File … -
Django: Query relational models in serializer
I have a Project and Memberships model where each project has a list of members. I need to find out if the current logged in user is listed as a member on the project from the project serializer, but I can't seem to get the request correct in my get_i_am_member method. I need to pass the project id from the Project model to the Membership model to filter the data, then check if the user in the filtered memberships model matches the user making the request. Can someone please assist? Here is my code: ###################################################### # Serializer ###################################################### class ProjectSerializer(LightWeightSerializer): id = Field() name = Field() slug = Field() description = Field() created_date = Field() modified_date = Field() owner = MethodField() members = MethodField() is_private = Field() anon_permissions = Field() public_permissions = Field() is_looking_for_people = Field() looking_for_people_note = Field() i_am_member = MethodField() i_am_admin = MethodField() my_permissions = MethodField() def get_members(self, project): members = Membership.objects.filter(project_id=project.id).select_related() return MembershipSerializer(members, many=True, context=self.context).data def get_i_am_member(self, request): members_list = Membership.objects.filter(project_id=request.project.id).select_related('user') for member in members_list: if member.user == request.username: print(member.user) print("True") return True else: print(member.user) print("False") return False ###################################################### # Models ###################################################### class Project(models.Model): name = models.CharField(max_length=250, null=False, blank=False, verbose_name=_("name")) slug = models.SlugField(max_length=250, unique=True, null=False, blank=True, verbose_name=_("slug")) … -
Django return redirect() does nothing
I am currently try to redirect from one view to another view. However, nothing happens, the token gets printed and that's it. class SocialLoginInvUserAPIView(APIView): permission_classes = [AllowAny] @staticmethod def post(request): print(request.data["token"]) return redirect("auth_user_login") Here is the login url: url(r'login/$', LoginInvUserAPIView.as_view(), name='auth_user_login'), -
no match for queryset in UpdateView
The queryset in my view dont send back any result, however when Im executing the raw SQL command with DB Browser for example I have the result I want, I dont understnad why my queryset dont send back anything... I got a 404 Not Found - No soldier to list found matching the query the view: class EditUnitsToListUpdateView(UpdateView): model = SoldierToList fields = ('soldier', 'list', 'author') template_name = 'armybuilder_edit_unit_to_list.html' def get_queryset(self): print (self.model.objects.filter(list=54).query) return self.model.objects.filter(list=54) My models: class List(models.Model): faction = models.ForeignKey(Faction, on_delete=models.CASCADE) title = models.CharField(max_length=30) format_points = models.IntegerField() description = models.CharField(max_length=30) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse("home") class Soldier(models.Model): title = models.CharField(max_length=30) picture = models.FileField(blank=True,) points = models.IntegerField() factions = models.ManyToManyField(Faction) def __str__(self): return self.title class SoldierToList(models.Model): soldier = models.ForeignKey(Soldier, on_delete=models.CASCADE,) list = models.ForeignKey(List, on_delete=models.CASCADE,) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) My urls: path('list/own/<int:list_id>/<int:faction_id>/addunit', AddUnitsToListFormView.as_view(), name='add_unit_to_list'), path('list/own/<int:pk>/<int:faction_id>/editlist/toto', EditUnitsToListUpdateView.as_view(), name='edit_unit_to_list'), The raw sql that work when executed separatly: SELECT "armybuilder_soldiertolist"."id", "armybuilder_soldiertolist"."soldier_id", "armybuilder_soldiertolist"."list_id", "armybuilder_soldiertolist"."author_id" FROM "armybuilder_soldiertolist" WHERE "armybuilder_soldiertolist"."list_id" = 54 Thanks for your help guys and have a great day ! -
Display Progressbar In Django View When downloading video (youtube-dl)
I am calling 'search/' when button is clicked through ajax call. Now my question is i want to show these details {"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} in a progress bar while downloading in a web page. How should i get the json response from video_progress_hook each time it is call by 'progress_hook' parameter in javascript? Please help. def search(request): file_name=""+str(uuid.uuid1()).split('-')[0]+".mp3" query=request.GET.get("query") ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192'}], 'outtmpl': 'media/'+file_name, 'progress_hooks':[video_progress_hook], 'quiet': False, } ydl = youtube_dl.YoutubeDL(ydl_opts) ydl.download([query]) args={'url_link':file_name} return JsonResponse(args) def video_progress_hook(d): args={} if d['status'] == 'downloading': args={"file_name":d['filename'],"percentage":d['_percent_str'],"speed":d['_eta_str']} return JsonResponse(args) -
Google Cloud Storage URL expires after a day
I switched to google cloud recently for my django app, all works well except that the url to some of my pictures coming from google cloud storage keeps getting expired after a day, and this is really terrible as there is always broken images on my app. I have even set my bucket to public, and still the urls expires after a day. How can one change this? -
how to serve files from /tmp directory in django
I want to serve downloadable files located in the /tmp directory via django. However I don't want these files copied or moved to the static_dir. The whole point of having the files in /tmp is that a cronjob will delete them every night. I realized I could just set /tmp as my static_dir in the django settings, but I already have a static_dir set that I am using in my project. My question is what is the easiest way to allow an end user to download files located in the /tmp directory? If I hit this url: http://localhost:8000/api/v2/tmp/testfile.zip I would expect to download /tmp/testfile.zip Can this be done via just a single entry in urls.py? Or am I going to have to create a new view? -
Add class to model form label Django
I've done a lot of digging on how to accomplish this, and aside from using 3'rd party modules is there not a simple way to customize labels for auto-generated forms in Django? i.e. models.py from django.db import models class Foo(models.Model): email = models.CharField(max_length=200) forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo index.html <form action={% url 'FooApp:results' %} method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> views.py from .forms import FooForm def index(request): form = FooForm() return render(request, 'foos/index.html', {'form': form}) This seems to be the most "Django" way of doing things, but it offers little flexibility in terms of using frameworks such as bootstrap (which requires classes to be added to specific elements including input labels) I have read many answers that use widget customization, for example if I wanted to add the class bar to my email field on my FooForm: forms.py from django.forms import ModelForm from FooApp.models import Foo class FooForm(ModelForm): class Meta: model = Foo widgets = { 'email': TextInput(attrs={ 'class': 'bar' }), } however, I still can't figure out how to add a bar class to the label that is generated along with this input … -
Converting Naive Datetime object to user selected timezone in Django Template
I have Naive Datetime object stored in my Postgresql DB. I know the timezone used in the django project. Now, I have to convert these time objects into user selected timezone values in the template. Is there any way to make all the naive datetime objects to aware objects in the DB using proper migration? -
does django db_index=True index null value?
for example if i have a field name slug = models.CharField(null=True, db_index=True,max_length=50) and while saving data if left slug empty. will database index this saved null value? -
How to initialise a field in Django models using other fields in the model
I would like to call an API that will return the latitude and longitude from a postcode which is part of my Django Model class Nurse(models.Model): firstName = models.CharField(max_length=100, default="") lastName = models.CharField(max_length=100, default="") postCode = models.CharField(max_length=10, default="") area = models.CharField(max_length=100) phoneNumber = models.CharField(max_length=20) email = models.EmailField(max_length=100, null=True) latitude = models.FloatField(max_length=10, null=True) longitude = models.FloatField(max_length=10, null=True) So when a nurse object is created, I would like to call an api (postcode.io) which means I am able to get a latitude and longitude based on the postcode that saves these values to the data model. I need to have the latitude and longitude because I have use for it in a template where I need to access this information. Thanks! -
is there a function that return current path but in Django class
I need function that return part of url but inside ListView(where"XXXX") About project: its just a shopping list. I have 2 classes in models(ShoppingList and ShoppingItem). ShoppingItem looks like this: name = models.CharField(max_length=50, null=False) count = models.IntegerField(null=False) list = models.ForeignKey(ShoppingList, on_delete=models.CASCADE, related_name='shopping_items')** date_created = models.DateTimeField(auto_now_add=True) My ListView class: class ListDetailUpdateView(ListView): model = ShoppingItem template_name = 'xlist_app/ListDetailUpdateView.html' context_object_name = 'products' queryset = ShoppingItem.objects.filter(list = XXXX) My idea is to cut last part of url (for example when i enter list number 2 i have adress http://127.0.0.1:8000/ListDetails/2) and replace "XXXX" with such a function. In my mind it should look like: queryset = ShoppingItem.objects.filter(list = int(request.path.split('/')[-1]) (if there is a better way to do that i will aprreciate all sugestions) -
Django update number of items on each save or delete
I am new to Django and still learning. I am looking to keep track of how many events I have under a test. My current model looks like class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) num_of_events = models.IntegerField(default=0) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test = models.ForeignKey(Test,on_delete=models.CASCADE) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name def save(self): obj, created = Test.objects.update_or_create(name=self.test) obj.num_of_events += 1 super().save() def delete(self): self.test.num_of_events -= 1 super().delete() I thought I could just override the save() function but it does not update on the admin panel and still shows 0. I am trying to figure out what I am doing wrong. -
Django message variable not available in If.. statement
I am trying to use the Django message system to send the user back to their previous page. I have a Delete Customer FBV that can be accessed from multiple locations and after deleting the customer I want to send the user back to where they were. If I do this it works well and I get the behavior I expected: @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' if request.method == "POST": storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust } return render(request, 'delete_customer.html', context) However, I want to be able to use that returnURL variable both in the If "POST" section and in the context variable to send to the render statement. Why when I do this does it not work? @login_required def delete_customer(request, custpk): del_cust = Customer.objects.get(pk=custpk) returnURL = '' storage = get_messages(request) for message in storage: returnURL = message.message storage.used = True if request.method == "POST": del_cust.delete() return redirect(returnURL) context = { 'del_cust': del_cust, 'returnURL': returnURL } return render(request, 'delete_customer.html', context) Why does this not work? When the redirect hits it says there is nothing to redirect to. How can I … -
how to access multiple models' classes chained with foreign keys in Django
I have 5 models chained with foreign keys in Django (version 3.0.5, Python 3.6.5). Theses models are as follow: class MyUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('nick name '), max_length=48, unique=True) first_name = models.CharField(_('First name '), max_length=48) last_name = models.CharField(_('family name '), max_length=48) email = models.EmailField(_(' Emial address'), unique=True) date_joined = models.DateTimeField( _('date_joined'), auto_now=False, auto_now_add=True) date_updated = models.DateTimeField( _('date_updated '), auto_now=True, auto_now_add=False) is_active = models.BooleanField(_('is your account active '), default=True) is_staff = models.BooleanField( _('is the user among admin team '), default=True) avatar = models.ImageField( upload_to='profile_image', blank=True, null=True) class ForumsPosts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=64) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsPostImages(models.Model): id = models.AutoField(primary_key=True) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsPostimages/%Y/%m/%d', blank=True, null=True ) class ForumsComments(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(MyUser, on_delete=models.CASCADE) post = models.ForeignKey(ForumsPosts, on_delete=models.CASCADE) comment_content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) class ForumsCommentImages(models.Model): id = models.AutoField(primary_key=True) comment = models.ForeignKey(ForumsComments, on_delete=models.CASCADE) images = models.ImageField(upload_to='ForumsCommentimages', blank=True, null=True ) I made request using GET method passed through ajax. The GET method has one parameter which is "ForumsPosts ID" . In Django I have a view function as … -
slug field to an existing database and unique slug generator
I already had a database created without the slug field. I wanted to add a unique slug field into my database. I have read the document django document on non nullable unqiue slug and have gone through the video: Master code online. And here is what I have done: I have created a slug field with params max_length and blank=True. Created utils.py in my project folder with function unique_slug_generator. Run python manage.py makemigrations. Added RunPython in migrated file. Run python manage.py migrate. Again changed the slug params to unique=True and repeated the process again. shop/models.py: class products(models.Model): image = models.ImageField(upload_to='products/') name = models.CharField(max_length=50) title = models.CharField(max_length=50) slug = models.SlugField(max_length=150, unique=True) price = models.FloatField() def __str__(self): return self.name project/utils.py: from django.utils.text import slugify import random import string def random_string_generator(size): return ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for n in range(size)) def unique_slug_generator(model_instance, name, slug_field): slug = slugify(name) model_class = model_instance.__class__ while model_class.objects.filter(slug=slug).exists(): new_slug = "{slug}-{randstr}".format(slug=slug, randstr=random_string_generator(4) ) return slug After first makemigrations: # Generated by Django 3.0.4 on 2020-04-16 17:41 from django.db import migrations, models from project.utils import unique_slug_generator def update_slug(apps, schema_editor): products = apps.get_model('shop', 'products') for query in products.objects.all(): if not query.slug: query.slug = unique_slug_generator(query, query.title, query.slug) query.save() class Migration(migrations.Migration): dependencies … -
Speed tuning for mysql fetching in Django
I have model like this class MyJson(models.Model): created_at = models.DateTimeField(null=True) tweet_status = JSONField() is_show = models.BooleanField() def __str__(self): return self.tweet_id class Meta: indexes = [ models.Index(fields=['is_show']), models.Index(fields=['created_at',]) ] class MyJsonSerializer(serializers.ModelSerializer): tweet_status = serializers.SerializerMethodField() def get_tweet_status(self,obj): return obj.tweet_status class Meta: model = MyTweet fields = ('id','tweet_status','created_at') class MyJsonFilter(filters.FilterSet): is_show = filters.BooleanFilter(method='is_show_filter') created_at = filters.DateTimeFilter(lookup_expr='gt') def is_show_filter(self, queryset, name, value): return MyJson.objects.filter(is_show=1) then I want to fetch 5000 rows from more than 200000 rows where is_show = 1 order by created_at. But it takes more than 1 min. It's a bit too slow, I want to speed up more.... Where is the bottle neck???or where should I improve?? I set is_show and created_at as index. Is there any setting for this case??? -
Why are my users messages not appearing fully?
Ok, so I am building an inbox and messaging system for my DatingApp. I have been able to display the conversations between my user and other users in my view 'Messages'. Now, I am attempting to display the contents of the conversations through messages via the Message view but I am failing. Because only the sent messages from request.user are showing. I attempted doing two queries at once through my InstantMessage model (which has a foreign key to my Conversation model), a query for request.user and one for user, but still, only the messages sent from request.user are showing up. And furthermore, when you click on the conversation, it should only show messages between that specific user but I am showing ALL messages sent out by request.user to ALL users. So I got two problems here. I'm super stuck on this, so any help would be HIGHLY appreciated. views.py/Message and Messages #Displays contents of a conversation via messages def message(request, profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', ).\ order_by('date',) conversations = Conversation.objects.filter(members=request.user) context = {'messages' : messages, 'conversations':conversations} return render(request, 'dating_app/message.html', context) #Displays conversations a user is having def messages(request,profile_id): messages = InstantMessage.objects.filter(Q(sender_id=request.user) | Q(sender_id=profile_id)).\ values('sender_id','receiver_id', 'message', 'date', … -
How can i get error logs on my live Django/Django channels app?
I deployed a Django/Django Channels application to a VPS using Nginx, Gunicorn, Daphne and systemd, everything seems to work for now, but when i try to reach a Websocket consumer of my app using this: ws = create_connection("ws://mydomain/receiver") ws.send('Test') I get a Connection refused error, which means that something is not right on my Django Channels side. Since the Django app is running on a linux VPS, i do not have access to a console like i would during development. Is there any way to check the errors of my application, or a console or anything that would help me see what's happening behind the scenes here? -
Django model that stores multiple other models that store multiple other models
I am learning Django so this is all very new to me. What I am trying to create is a bit of functionality in my admin panel that will allow me to create a layout like this. Test -Event1 --Property1 --Property2 --Property3 --Property4 -Event2 --Property1a --Property2b --Property3c --Property4d -Event3 --Property1aa --Property2bb --Property3cc --Property4dd -Event4 --Property1aaa --Property2bbb --Property3ccc --Property4ddd I want to have multiple tests. My current model setup looks like this: from django.db import models from django.forms import ModelForm TYPE_CHOICES = ( ("string", "string"), ("integer", "integer"), ("array", "array"), ("boolean", "boolean") ) class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=255) test_id = models.IntegerField() class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Property(models.Model): name = models.CharField(max_length=255) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) class Meta: verbose_name = 'Property' verbose_name_plural = 'Properties' def __str__(self): return self.name class TestForm(ModelForm): class Meta: model = Test fields = ['name', 'description'] I have my admin panel setup so that I can create multiple properties. But then when I go to the "Events" section in my admin panel I can only create events. I want … -
NameError at /contact/ name 'ContactForm' is not defined error:
I am creating a contact page where an email is sent to the user. When I go to access the contact page I run into the error "NameError at /contact/ name 'ContactForm' is not defined" Any idea? Code: def Contact(request): Contact_Form = ContactForm if request.method == 'POST': form = Contact_Form(data=request.POST) if form.is_valid(): contact_name = request.POST.get('contact_name') contact_email = request.POST.get('contact_email') contact_content = request.POST.get('content') template = get_template('/contact_form.txt') context = { 'contact_name' : contact_name, 'contact_email' : contact_email, 'contact_content' : contact_content, } content = template.render(context) email = EmailMessage( "New contact form email", content, "Creative web" + '', ['servwishes@gmail.com'], headers = { 'Reply To': contact_email } ) enter code here email.send() return redirect('blog:success') return render(request, 'users/contact.html', {'form':Contact_Form }) -
Django Rest Framework - ImproperlyConfigured: Could not resolve URL for hyperlinked relationship
Similar to this question, but I do not have namespaces or base-names, so none of the solutions in that question have worked. I have 2 models: Organisation Student A student can belong to an organisation. When I retrieve an organisation, I want a child object in the returned JSON that lists the 'related' students as hyperlinked urls (as per HATEOS). models.py class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True, related_name='students') serializers.py class OrganisationSerializer(serializers.ModelSerializer): students = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='student-detail', lookup_url_kwarg='organisation_id') class Meta: model = Organisation fields = ('id', 'name','students') class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' urls.py from rest_framework import routers from .views import OrganisationViewSet, StudentViewSet from django.conf.urls import url router = routers.DefaultRouter() router.register(r'api/v1/organisations', OrganisationViewSet) router.register(r'api/v1/students', StudentViewSet) urlpatterns = router.urls views.py from .models import Organisation, Student from rest_framework import viewsets, permissions from .serializers import OrganisationSerializer, StudentSerializer # Organisation Viewset class OrganisationViewSet(viewsets.ModelViewSet): queryset = Organisation.objects.all() serializer_class = OrganisationSerializer permission_classes = [ permissions.AllowAny ] # Student Viewset class StudentViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer permission_classes = [ permissions.AllowAny ] So this should work as this … -
daphne in supervisor not working. How to make it work?
alltime in console browser i see it WebSocket connection to 'ws://(amazon_www...).compute.amazonaws.com/ws/chat_view/43/' failed: Error during WebSocket handshake: Unexpected response code: 404 [program:gunicorn] directory = /home/ubuntu/site command=/home/ubuntu/env/bin/gunicorn --workers 1 --bind unix:/home/ubuntu/site/app.sock djangoshop.wsgi:application autostart=true autorestart=true stopasgroup=true [program:platform_asgi_workers] command=/home/ubuntu/env/bin/python3 /home/ubuntu/site/manage.py runworker channels process_name=asgi_worker%(process_num)s numprocs=1 stdout_logfile=/var/log/worker.log [program:daphne] socket=tcp://localhost:9000 directory = /home/ubuntu/site command=/home/ubuntu/env/bin/daphne -u /run/daphne/daphne%(process_num)d.sock --endpoint fd:ft fd:fileno=0 --access-log - --proxy-headers djangoshop.asgi:application numprocs=1 autostart=true autorestart=true stopasgroup=true stdout_logfile=/var/log/worker.log daphne BACKOFF Exited too quickly (process log may have details) gunicorn RUNNING pid 20882, uptime 0:00:16 platform_asgi_workers:asgi_worker0 BACKOFF Exited too quickly (process log may have details) per 1 sec supervisor out daphne STARTING gunicorn RUNNING pid 20882, uptime 0:00:22 platform_asgi_workers:asgi_worker0 STARTING nginx: upstream app { server wsgiserver:8000; } upstream ws_server { server localhost:9000; } server { listen 80; server_name (my_www).compute.amazonaws.com; client_max_body_size 20M; location / { try_files $uri @proxy_to_app; } location /ws { try_files $uri @proxy_to_ws; } location @proxy_to_ws { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; proxy_pass http://ws_server; } location @proxy_to_app { proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Url-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Forwarded-Port $server_port; proxy_pass http://app; } location /static/ { alias /home/ubuntu//djaro/site/static_in_dev/; } Gunicorn worked, daphne not, with manage.py …