Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems configuring Apache2 WSGI django
So I am building a blog engine for my class. It is supposed to be an easy assignment, but for some reason, I cannot get Django working on apache 2, and I have not even started on the databases, which is the goal of this project. I have re-installed apache2 a hand full of times with no success. same with WSGI, and I have followed this guide fairly closely, only really changing names of folders to be more in line with the project https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I tested with ./manage.py runserver 0.0.0.0:8000, and everything on the test domain checked out fine. picture of working port 8000 here is my final configuration file <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname, and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName … -
How to do text based filtering on DateTimeFields using a specific template format?
I have a table that includes both CharFields and DateTimeFields displayed using django template language. The DateTimeFields are displayed in the format "Aug. 18, 2020, 6:33 p.m.". Is there an easy way to do a text based filter/query on the DateTimeFields based on that specific format? For example, searching "aug" or "Aug" or "Aug. 18" or "2020" should find that entry. I've tried icontains, but that seems to work on the underlying format, rather than the display format. For example, searching "2020-08" finds that entry, but searching "Aug" does not. Works: Entry.objects.get(created__icontains='2020') Entry.objects.get(created__icontains='2020-08') Entry.objects.get(created__icontains='33') Does not work: Entry.objects.get(created__icontains='Aug') Entry.objects.get(created__icontains='6:33') Entry.objects.get(created__icontains='p.m') Is there a way to search the using the specific dat time display format? What format is the underlying DateTimeField? Is it DB dependent? -
2021 python-social-auth "facebook Authentication process canceled" on production, but works on localhost
In my Django=2.2 app I want to implement facebook login via python-all-auth. But I am faceing a problem with authentication on production. Here some details: When I use facebook login on localhost, everything is working as expected. When clicking on fb login icon, I am being redirected to fb page, I give permittion to the application to my data and I am being redirected back to the main page with User being logged in. User is created in the both tables 'Social Account Users' and my custom 'User' table. BUT then on production, adjusting settings in facebook app accordingly, facebook authentication is being canceled. Same, after clicking on fb login icon I am being redirected to facebook page, pop up window is showing up and askig to give permittion to application by clicking "continue as a user" I am being redirected to main page with a message 'Authentication process canceled' with debug=True, the error is: Environment: Request Method: GET Request URL: http://www.sellspot.pl/oauth/complete/facebook/?granted_scopes=email%2Cpublic_profile&denied_scopes&code=SOME_CODE Django Version: 2.2.17 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'django.contrib.humanize', 'bootstrap_pagination', 'storages', 'social_django', 'auctions', 'users', 'data', 'contact_us', 'report'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware') Traceback: File … -
Simplify form submission in Django
I have a form in Django where the user can submit a file/ an image/ text in a single form as follows. <form id="send-form" action="{% url 'chat:message' context.room_id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <table style="width: 100%"> <input type="hidden" name="from" value="{{ user }}"> <input type="hidden" name="next" value="{{ request.path }}"> <tr style="width: 100%"> <td style="width: 50%"> <input type="text" id="chat-input" autocomplete="off" placeholder="Say something" name="text" id="text"/> </td> <td style="width: 16%"> <input type="file" name="image" accept="image/*" id="image"> </td> <td style="width: 16%"> <input type="file" name="file" accept="image/*" id="file"> </td> <td style="width: 16%"> <input type="submit" id="chat-send-button" value="Send" /> </td> </tr> </table> </form> In views.py, the form has to be submitted even if any of the three inputs is missing i.e, even if user submits only text/ only image/only file, the data has to be uploaded into database and I have written using try and except in the following way: def messages(request, room_id): if request.method == 'POST': try: img = request.FILES['image'] except: img = None try: text = request.POST['text'] except: text = None try: file = request.FILES['file'] except: file = None path = request.POST['next'] fields = [img,file,text] ChatMessage.objects.create(room=room,user=mfrom,text=text,document=file,image=img) Is there any other better way to do it. The code looks not so good with all the try excepts. -
media part in django is not coming
I cant upload an image file. media file doesn't come in django when i upload an image. i add settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def addArticle(request): form = ArticleForm(request.POST or None,request.FILES or None) if form.is_valid(): article = form.save(commit=False) article.author = request.user article.save() messages.success(request,"Makale Başarıyla Oluşturuldu.") return redirect("index") return render(request,"addarticle.html",{"form":form}) forms.py class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ["title","content","article_image"] when i upload an image in to my article i got nothing to view -
Store procedure returns Error converting data type varchar to int. (8114) (SQLExecDirectW)')
I am trying to use stored procedure to do CRUD operations but while updating i am getting the error Error converting data type varchar to int. (8114) (SQLExecDirectW)'). I wrote a function to return null strings to an integer and return it and it seems to work fine (I printed the result) but I get error. Here is the stored procedure: USE [testenr] GO CREATE PROCEDURE [dbo].[updateJobPost] @id int = Null, @TopicName nvarchar(300) = NULL, @UpdatedDate datetime2(7) = NULL, @IsActive bit = 0, @IsClose bit = 1, @ForceCloseReason nvarchar(3999) = NULL, @IsNotification bit = 0, @SMSText nvarchar(150) = NULL, @WhatsAppText nvarchar(1000) = NULL, @Category_id int = NULL, @CloseBy_id int = NULL, @ForceCloseCategory_id int = NULL, @SubCategory_id int = NULL, @User_id int = NULL AS UPDATE [dbo].[accounts_topiclist] SET [TopicName]=@TopicName, [UpdatedDate]=@UpdatedDate, [IsActive]=@IsActive, [IsClose]=@IsClose, [ForceCloseReason]=@ForceCloseReason, [IsNotification]=@IsNotification, [SMSText]=@SMSText, [WhatsAppText]=@WhatsAppText, [Category_id]=Category_id, [CloseBy_id]=@CloseBy_id, [ForceCloseCategory_id]=@ForceCloseCategory_id, [SubCategory_id]=@SubCategory_id, [User_id]=@User_id WHERE id = @id GO Here is the view: def post(self, request, pk): pk = self.kwargs.get('pk') if request.method == 'POST': topicname = request.POST['TopicName'] category_id = AllProcedures.empty(request.POST['Category']) sub_Category = AllProcedures.empty(request.POST['SubCategory']) isActive = request.POST.get('IsActive') active = AllProcedures.boolcheck(isActive) isClose = request.POST.get('IsClose') close = AllProcedures.boolcheck(isClose) closed_by = AllProcedures.empty(request.POST['CloseBy']) closereason = request.POST['ForceCloseReason'] CLosedCategory = AllProcedures.empty(request.POST['ForceCloseCategory']) isNotify = request.POST.get('IsNotification') notify = AllProcedures.boolcheck(isNotify) sms = request.POST['SMSText'] wap … -
What is django.db.utils.OperationalError: (2000, 'Unknown MySQL error')
Whenever I enter python .\manage.py runserver on django, this error: django.db.utils.OperationalError: (2000, 'Unknown MySQL error') appears. I think it is a client side error as other people running the same project do not have this error. Does anyone know what the error is and potentially how to fix it? -
How to use allauth-socialaccount for Apple provider
Into my Django project (for RESTful services to a mobile app) I'm using allauth + allauth.socialaccount to support social login as also the standard sign-in. As social login I'm using allauth.socialaccount.providers.facebook as Facebook provider. Now, as requested by Apple, It' necessary to integrate Apple-login also. As reported into all-auth release-notes, from 0.43.0 version it's supported Apple provider also. So, I would like to try to integrate it. Where can I found the documentation for this (or also a quick example)? I'm not sure I understand exactly the flow used in this implementation. For example, how should the url callback be handled? Is there some additional urls as documentation? Are there some example projects? I need to understand exactly the flow because I need to customize it (not only about the URLs but also about custom additional fields) -
Django: How do I handle urls with multiple apps
I have two apps: core and dm Here's my code: core/urls.py urlpatterns = [ path('', views.index, name='index') ] dm/urls.py urlpatterns = [ path('', views.dm, name='dm'), path('prices', views.dm_prices, name='prices') ] mysite/urls.py from core import views from dm import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), path("stripe/", include("djstripe.urls", namespace="djstripe")), path('dm', include('dm.urls')), path('dm/prices', include('dm.urls')), ] And so, looking from the 404 page, I can see that the URLs he sees are: admin/ [name='index'] stripe/ dm [name='dm'] dm prices [name='prices'] dm/prices [name='dm'] dm/prices prices [name='prices'] I would be really happy if someone could explain to me how django reads the different URLs and how it orders them. Thanks a lot! -
How to simulate Django file submissions to forms for unittests?
I am doing a Django project where a user uploads a file to my website and then a program takes that data and assigns it to a model. I am attempting to be a good little programmer and test my code as I go, but I appear to have run into a testing issue. One thing I want to do is limit the file types that the user can upload to .xls files. I wrote a test for this and submit the file to the form like so self.form = self.form({'file' : good_file}). I overrode the clean_file() method that the form uses to to look at the extension and raise a validation error if it's not in the approved file type list. I tried following the example posted here https://docs.djangoproject.com/en/3.1/ref/forms/validation/ and pulling the file from cleaned_data['file'] but all that is there for file is 'file' : None. However when I test a view redirecting to a different page when the user uploads a file like so response = self.client.post('/teacher/add_course', data={'file' : open(file)}) I see the file in clean_file() as 'file' : InMemoryUploadedFile. So basically I didn't submit the file right in the form test or at least didn't give it … -
Difference between Apache process and WSGI process?
I have a Django application running with Apache prefork (my code is not thread safe). I am relatively new to Apache, so apologies in advance if this is too basic. As far as I understand the main differences are: Apache process: control access and serve static files WSGI process: execute python code Does this mean that if I define MaxRequestWorkers in Apache as 250, and wsgi processes = 10.. each one of the 250 Apache processes can fork into another 10 processes? Also, according to mod_wsgi documentation sites using Apache prefork should set the wsgi threads = 1 My site actually works when setting wsgi threads = 5 with Apache prefork. But doesn't work with Apache worker since the code is not thread safe... How can this be? -
Heroku unable to verify card
I wanted to connect my custom domain to django website hosted on heroku because it was free, I wanted to connect my domain to heroku but it asks for verification, I tried to add my card and I also added all things correctly but it gives unable to verify card error, I tried with different card also but it gives same error, There is no fault of card, Is there any other solution to it, Is there any hosting that allows to host django website for free and also allows to add custom domain like heroku instead of digital ocean and amazon aws. -
How to keep the content inside the card?
I making my first web project, and as a first project im doing To-Do app. Im also learning to do it responsive website, but i have stuck in a problem. When I add a content larger then the table it goes out of the card. What i want is despite that the content is larger i want to stay inside the table. body { background-color: #6ea1ff; /*#3f7ef3;*/ font-family:; } /* The navbar */ .navbar { padding: 25px; } .navbar-brand { font-size:; } .d-flex { margin-right: 680px; width: 30%; } #add-btn { width: 80px; } /* THe table */ .container{ position: relative; bottom: -75px; width: 65%; font-family:; } .card { background-color: #0d2e72; } .card-header { border: none; } #header { font-size: 25px; text-align: center; color: white; } #tr-table { width: 100px; } #text-left { width: 10%; } #text-right { width: 15%; padding-left: 40px; } #text-center { text-align: center; } #btn-delete { width: 80px; margin-left: 35px; } /* THE footer */ footer { position: fixed; left: 0; bottom: 0; width: 100%; padding: 10px; background-color: #26272b; color: white; text-align: center; } @media screen and (max-width: 667px) { /* The navbar */ .navbar { padding: 15px; height: auto; } .d-flex { position: relative; left: … -
django filter get parent to child
i am using django(3.1.5). and i am trying to get parent model to child model by filter query i have model like - class Product(models.Model): product_name = models.CharField(max_length=255, unique=True) is_feature = models.BooleanField(default=False) is_approved = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) class ProductGalleryImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) product_gallery_image = models.FileField(upload_to='path') is_feature = models.BooleanField(default=False) i am getting data from SELECT * FROM products_product AS pp INNER JOIN products_productgalleryimage AS ppgi ON ppgi.product_id = pp.id WHERE ppgi.is_feature=1 AND pp.is_feature=1 AND is_approved=1 ORDER BY pp.created_at LIMIT 4 mysql query. so how can i get data like this query in django filter query -
How to enable cors in django (DJANDO + REACT)
Access to XMLHttpRequest at 'http://127.0.0.1:8000/lessons/student' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. xhr.js:177 GET http://127.0.0.1:8000/lessons/student net::ERR_FAILED On my localhost it works good, I get data from API but when my friend tries to go to the "Lessons" page and fetch data it shows that error; In the backend, I downloaded django-cors or whatever it is called and did everything as said CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'News', 'Users', 'Lessons', 'Tests', 'GradeBook', 'Schedule', 'DeadLines' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] I fetch data using redux-thunk with axios const lesson = await axios.get(`${url}/lessons/student`, { headers: { "Authorization": "JWT " + getState().auth.token.access, } }) I have checked a lot of answers to similar problem but they only say that I should install django-cors..enable cors...lalal... I do everything reload the server even localhost but it still doesn't work. It also isn't a problem with the browser, my friend tried chrome since he used opera. One more time, on my computer it works nice. I get the data once I … -
refresh a same page without reloading?
i have already asked this question here but none of the answers were working.i have a messaging app where users can send messages each other.i want to refresh the page so that the user can see new messages.but there is one problem if the user is writing a message and i try to reload the page every x-minutes the message that the user was writing will disapear.so how can i avoid this? window.location.reload(true);// this what i have tried history.go(0); window.location.href=window.location.href; -
Passing a form in the context of django view gives 502 bad gateway on aws server
I am getting a 502 bad gateway error as soon as i am passing a form object in my django view. If i don't pass the form it doesn't give any errors on the server. This is my model class scholarship(models.Model): GRADUATION_CHOICES = ( ('UG', 'Under Graduate'), ('G', 'Graduate'), ('PG', 'Post Graduate'), ) name = models.TextField() slug = models.SlugField(max_length=250, unique=True) supportingImage = models.FileField(upload_to ='student/scholarship/supportingImage/',null=True, blank=True, validators=[FileExtensionValidator(['jpg','png','jpeg'])]) author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='authorSCH', null=True, blank=True) productCategory = models.TextField(null=True, blank=True) currentClass = models.ManyToManyField(studentClass, related_name='currentClassSStudent', blank=True) graduation = models.CharField(max_length=10, choices=GRADUATION_CHOICES, default='G') scholarshipAmount = models.TextField(null=True, blank=True) fee = models.TextField(null=True, blank=True) gender = models.CharField(max_length=50, choices=GENDER_CHOICES, null=True, blank=True) country = models.ForeignKey(countryAndCurrencyList, related_name="countrySCH", blank=True,on_delete=models.SET_NULL,null=True) state = models.ForeignKey(state, related_name="stateSCH", blank=True,on_delete=models.SET_NULL,null=True) city = models.ForeignKey(city, related_name="citySCH", blank=True,on_delete=models.SET_NULL,null=True) eligibility = models.TextField(null=True,blank=True) scholarshipCourse = models.ManyToManyField("course", related_name='scholarshipCourseS',blank=True) scholarshipCareer = models.ManyToManyField(career,related_name='scholarshipCareerS',blank=True) scholarshipCollege = models.ManyToManyField(collegeProfile,related_name='scholarshipCollegeS',blank=True) scholarshipUniversity = models.ManyToManyField(universityProfile,related_name='scholarshipUniversityS',blank=True) scholarshipEntrance = models.ManyToManyField(entranceExams,related_name='scholarshipEntrance',blank=True) scholarshipGlobalisation = models.CharField(max_length=15,choices = AREA_CHOICE, default='india') dateToApply = models.DateField(default=datetime.date.today) whereToApply = models.TextField(null=True, blank=True) lastDateToApply = models.DateField(default=datetime.date.today) description = models.TextField(null=True, blank=True) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') def __str__(self): return self.name class Meta: verbose_name_plural = 'Student-Scholarship' def get_absolute_url(self): return reverse('studentApp:scholarshipDetail', args=[self.slug]) def save(self): if self.name: if not self.slug: self.slug = re.sub(r'[\W_]+', '-', self.name.lower()) super(scholarship, self).save() else: super(scholarship, self).save() … -
Logger emit() is called multiple times for a single request
I am trying to modify the emit() of logging. handler such that I can ship the logs to my Kafka broker. However, I am noticing something strange, every time I make a request, the emit() is called multiple times. E.g When I go to the browser and press enter once, the emit() is called once, and then when I retry the request, the emit() is called twice. The trend is that the calls to emit() increases linearly with every request. Tried debugging through the logs but couldn't find any errors. Any suggestion or advice would be really appreciated. handler.py from logging import StreamHandler from ..mykafka import MyKafka class ErrorLogHandler(StreamHandler): def __init__(self, broker, topic): StreamHandler.__init__(self) self.broker = broker self.topic = topic # Kafka Broker Configuration self.kafka_broker = MyKafka(broker,True) def emit(self, record): data = { 'sys_name': 'Test', 'logger_name': record.name, 'level': record.levelname, 'message': record.msg, 'function_name': record.funcName, 'file_name': record.filename, } self.kafka_broker.send(data, self.topic) mykafka.py from kafka import KafkaProducer import json class MyKafka(object): def __init__(self, kafka_brokers, is_json=False): self.is_json = is_json if not is_json: self.producer = KafkaProducer( bootstrap_servers=kafka_brokers ) else: self.producer = KafkaProducer( value_serializer=lambda v: json.dumps(v).encode('utf-8'), bootstrap_servers=kafka_brokers, ) def send(self, data, topic): if self.is_json: result = self.producer.send(topic, key=b'log', value=data) else: result = self.producer.send(topic, bytes(data, 'utf-8')) print("kafka send … -
Django Nested model or serializers
I'm new in Django and I have a simple use case to parse a nested json file. Most of tutorials I've seen are using nested relation in their serializer code like this which is a bit different than my case. What is the best way to create implement this structure? class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] And here is my input json file. { "BMW":[ { "model":"3", "price":"500" }, { "model":"5", "price":"600" } ], "TOYOTA":[ { "model":"X", "price":"300" }, { "model":"H", "price":"400" }, { "model":"S", "price":"500" } ] } -
I am trying to create an writable nested serializer in django, but can't use post method properly
So I am trying to create a serializer that shows me the whole object of the other model that is linked by a ForeignKey with the model I am working with my GET woks good, but I can only post by creating a new Country not with an actual existing one, so here are my two models, Model 1 class CountryName1(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name the other model, Model 2 class TeslaModel1(models.Model): model_name = models.CharField(max_length=30) price = models.IntegerField() origin = models.ForeignKey(CountryName1, on_delete=models.CASCADE, related_name='teslamodels') def __str__(self): return self.model_name My serializers are like this class CountryNameSerializer(serializers.ModelSerializer): class Meta: model = CountryName1 fields = ['name'] class TeslaModelSerializer(serializers.ModelSerializer): origin = CountryNameSerializer() class Meta: model = TeslaModel1 fields = ['model_name', 'price', 'origin'] def create(self, validated_data): origin_data = validated_data.pop('origin') country_model = CountryName1.objects.create(**origin_data) Here are my views: class TeslaModelListCreateAPIView(ListCreateAPIView): queryset = TeslaModel1.objects.all() serializer_class = TeslaModelSerializer class CountryNameListCreateAPIView(ListCreateAPIView): queryset = CountryName1.objects.all() serializer_class = CountryNameSerializer -
Django PayPal delay
I'm creating a payment system for a project I'm working on and I'm using django-paypal. I followed their guide and implemented the signals and everything is working correctly (user clicks on a button -> gets redirected to paypal -> if everything is good success page is shown). The thing is in my signals I have a thing where I want to give users points when the do the buying function. I have that in my signals but there is a delay between showing the success page and the actual signal receiving the data and being executed. I don't know if this is because I'm using stuff like ngrok and localtunnel or is it something else. This is my signals.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received, invalid_ipn_received from account.models import Account def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: if ipn_obj.receiver_email != "**": # Not a valid payment print("BAD EMAIL") else: print("ALL GOOD") acc = Account.objects.get(account_url=ipn_obj.custom) acc.coins = acc.coins + int(ipn_obj.mc_gross) acc.save() else: print("FAIL") valid_ipn_received.connect(show_me_the_money) So if I'm understanding everything this is all correct but for some reason the delay is happening and I don't know whats causing it. -
Django - Extending user profile not showing fileds in chenge form
I want to extend the user model in django adding new fields and of course be able to manage it through the admin pages. I created a CustomUser model in django extending AbstractUser and added some extra fields, created a UserCustomCreateForm and UserCustomChangeForm to manage the creation and change and then registered a CustomUserAdmin that extend the UserAdmin adding the two forms. In admin, it seems to work fine when create a new users but unfortunately the new fields don't appear on the change view. What am i doing wrong? Thanks here is the models.py users/models.py # Create your models here. from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # add additional fields in here address = models.CharField(max_length=50, null=True, verbose_name='Indirizzo') house_phone = models.CharField(max_length=20, null=True, verbose_name='Telefono') mobile_phone = models.CharField(max_length=20, null=True, verbose_name='Cellulare') def __str__(self): return self.first_name + ' ' + self.last_name here the forms # users/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser from django import forms class UserCustomCreateForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'first_name', 'last_name', 'address', 'house_phone', 'mobile_phone') class UserCustomChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ( 'username', 'email', 'first_name', 'last_name', 'address', 'house_phone', 'mobile_phone') … -
Show the button based on value of one column
I'm using django and trying to create a template and the last column would be the "View". If the variable c equals success, then there will show a detail button. If error, then the view column in this row would be blank. How could I realize this idea? Btw, the button will pop up a modal form when clicking. "columns": [ {"data": "a"}, {"data": "b"}, {"data": "c"}, { "data": null, "defaultContent": '<button type="button" class="btn btn-info btn-sm">Detail</button>' }, ], -
Reverse related object lookup is not accessing in ForeignKey
I am Building a BlogApp and I stuck on a Problem. I am trying to access two model objects but Failed many times. models.py class Topic(models.Model): dairy_no = models.CharField(max_length=100000,default='') dairy_title = models.CharField(max_length=2000,default='') date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Profile,on_delete=models.CASCADE,null=True) def __str__(self): return self.dairy_title class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE,default='',related_name='topic') date_added = models.DateTimeField(auto_now_add=True,null=True) updated = models.DateTimeField(auto_now=True) note = models.TextField() def __str__(self): return str(self.topic) views.py def show_entry(request): showd = Journel.objects.all() context = {'showd':showd} return render(request ,'mains/showd.html', context) showd.html {% for post in topic.journel_set.all %} {{ post.dairy_title }} {{ post.note }} {% endfor %} The Problem I am trying to access both model's Objects in showd.html. What have i tried I saw tons of Answers like :- This This and Many More answers about reverse related object lookup. BUT nothing is worked for me. I don't know am i doing wrong in this. Any help would be Appreciated. Thank You in Advance. -
django channels is slow
I am using django channel to send periodic message to subjects. The messages are not instantaneously sent to consumers even when I just test with 2 players. I am struggling to improve it. Any ideas that I could try? I am using threading.timer if this is relevant. There is the code. def periodic_signal(self, subperiod, num_subperiods): start = time.time() msg = {} for p in self.get_players(): ...some code here msg[pcode] = {'subperiod': subperiod + 1, 'signal': sampled_choices_counter_list} channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(self.get_group_channel_name(), { 'type': 'send.signal', 'msg': msg, 'time': time.time() }) # print('periodic_signal elapsed', time.time()-start) In consumers.py: def send_signal(self, event): msg = event['msg'] print('consumer elapsed', time.time() - event['time']) self.send_json({ 'msg': msg }) Here is some print output with 2 users and python 3.8.5: consumer elapsed 5.806595802307129 consumer elapsed 5.8080527782440186 consumer elapsed 0.007779836654663086 consumer elapsed 0.009441852569580078 consumer elapsed 5.816624164581299 consumer elapsed 5.818100929260254 It is improved if I use python 3.7.4 but still there is about 1 second delay sometimes. consumer elapsed 0.9057967662811279 consumer elapsed 0.8448600769042969 consumer elapsed 0.05404329299926758 consumer elapsed 0.051050424575805664 consumer elapsed 0.022072315216064453 consumer elapsed 0.014770746231079102 consumer elapsed 0.14920377731323242 consumer elapsed 0.15003633499145508 consumer elapsed 0.0430903434753418 consumer elapsed 0.04086613655090332 Django==2.2.12, channels==2.4.0 redis==3.3.8