Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why should we use parent in a Comment model?
what are self and parent? this is part of a comment app models.py class Comment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True) email = models.EmailField(blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) -
Return related fields but filtered in Django Viewset
I have two simple models Group and Question as follows: class Group(models.Model): name = models.CharField(max_length = 250) class Question(models.Model): question = models.CharField(max_length = 250) active = models.BooleanField(default=True) group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='questions') In my API Viewset, I have managed to show the questions (which is exactly what I want) as follows: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class GroupSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True, read_only=True) class Meta: model = Group fields = '__all__' However, I would like to be able to control the questions that are returned for each group to be only those that are currently active. I understand that I could overwrite the queryset in the viewset: class GroupViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] serializer_class = GroupSerializer queryset = Group.objects.all() However, this only filters on the Group object and not the active questions underlying this. Any ideas? -
Django Many-to-Many Model relationship
I am writing a newsletter app for Django. The app handles subscriber enrolling, newsletter rendering and sending. I am stuck with my lack of understanding of databases with respect to the Many to Many relationship and the 'through' model. My models.py has a subscriber model and a newsletter model and a 'through' model that binds them. There is also an email read and date_read field in the 'through', which will be updated the first time that the subscriber opens the email and allows images (not guaranteed I know). One subscriber can have many newsletters and one newsletter can have many subscribers. Here is an abbreviation of my models.py: class Subscriber(models.Model): first_name = models.CharField(max_length=30) #etc.. newsletters = models.ManyToManyField('Newsletter', through='NewsletterEngagement') def __str__(self): return '%s %s %s %s %s %s' % \ (self.pk, self.first_name, #etc.., ) class Newsletter(models.Model): title = models.CharField(max_length=200) #etc.. subscribers = models.ManyToManyField('Subscriber', through='NewsletterEngagement') def __str__(self): return '%s %s %s %s' % \ (self.pk, #etc.., ) class NewsletterEngagement(models.Model): subscriber = models.ForeignKey(Subscriber, on_delete=models.CASCADE) newsletter = models.ForeignKey(Newsletter, on_delete=models.CASCADE) read = models.BooleanField(default=False) read_date = models.DateField(null=True) def __str__(self): return '%s %s %s %s' % \ (self.subscriber, self.newsletter, self.read, self.read_date, ) The model seems to work quite well as follows: >>> s1 = Subscriber.objects.get(pk=1) >>> s2 … -
I could not install mysqlclient
pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Using legacy setup.py install for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\blackknight\desktop\simpleblog\myenv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Blackknight\AppData\Local\Temp\pip-install-85jgwelt\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Blackknight\AppData\Local\Temp\pip-install-85jgwelt\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Blackknight\AppData\Local\Temp\pip-record-7y2zgqqa\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\blackknight\desktop\simpleblog\myenv\include\site\python3.8\mysqlclient' cwd: C:\Users\Blackknight\AppData\Local\Temp\pip-install-85jgwelt\mysqlclient Complete output (23 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\blackknight\desktop\simpleblog\myenv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\Blackknight\AppData\Local\Temp\pip-install-85jgwelt\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\Blackknight\AppData\Local\Temp\pip-install-85jgwelt\mysqlclient\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\Blackknight\AppData\Local\Temp\pip-record-7y2zgqqa\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\blackknight\desktop\simpleblog\myenv\include\site\python3.8\mysqlclient' Check the logs for full command output. WARNING: You are … -
Django - Custom Object Permission View
I'm trying to give shop owner permissions for a view. So I made a file in which I created different permissions. In my permission I first of all check if the user was logged in with a has_permission function. I am now trying to determine if a user actually owns the shop with the has_object_permission function. Unfortunately, I don't feel that my function was performed correctly. I can always, despite my permission, make a request from any account, shop owner or not. Here are the models I use: models.py class Shop(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey(ShopCategory, on_delete=models.SET_NULL, null=True, blank=True) description = models.TextField(blank=True, null=True) path = models.CharField(max_length=255, unique=True, null=True, blank=True) # Set a null and blank = True for serializer mustBeLogged = models.BooleanField(default=False) deliveries = models.FloatField(default=7) def __str__(self): return self.name class UserShop(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) def __str__(self): return f"{self.user.name} {self.user.surname} - {self.shop.name}" Here are my permissions : utils.py class IsOwner(BasePermission): """ Check if the user who made the request is owner. Use like that : permission_classes = [IsOwner] """ def has_permission(self, request, view): return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): try: user_shop = UserShop.objects.get(user=request.user, shop=obj) return True except: return False class OwnerView(APIView): """ … -
How logout from Django AdminLTE iFrame?
AdminLTE https://adminlte.io/themes/v3/iframe.html hi, I am Django beginner and try AdminLTE templates above to my Django. In my Django, when click logout link to redirect login page is default action. In this template, there is no button/link for logout. So after add to top-navi a link <a href="/logout/">logout</a> and click it. Django try to load logout template 'logout.html' to iframe and it was fail. It looks fail logout. When reload this page as is, it displayed login page. seems Login sessions is abandoned now. But without reloading page and click any link, it load template to iframe tab normally and that dead session is reborn. How can I logout this page? regards. -
Django direct_cloud_upload No file was submitted. Check the encoding type on the form
I am trying to use the library direct_cloud_upload to opload directly a file to a Google Cloud Storage Bucket without going thourh my cloudrun (to bypass the 32Mb request limitation). Unfortunately, I consistently have this error: No file was submitted. Check the encoding type on the form. on the admin fontend when I try to upload a file, even though the file is sucessfully uploaded to the storage. There is obviously something I am missing, here is my code: models.py class AudioFileModel(models.Model): title = models.CharField(max_length=80) audio_file = models.FileField(upload_to='audio/') class Meta: ordering = ['title'] def __str__(self): return f"{self.title}" forms.py from .models import AudioFileModel from django import forms from google.cloud.storage import Client import direct_cloud_upload import os from direct_cloud_upload import CloudFileWidget from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file( 'service-account-key.json' ) client = Client(credentials=credentials) gcs_bucket = client.get_bucket(os.environ.get("GS_BUCKET_NAME")) ddcu_bucket_identifier = direct_cloud_upload.register_gcs_bucket(gcs_bucket) class UploadAudioFileForm(forms.ModelForm): class Meta: model = AudioFileModel fields = ('title', 'audio_file') widgets = { 'audio_file': CloudFileWidget( bucket_identifier=ddcu_bucket_identifier, path_prefix="audio_file_new/", ) } } urls.py from .views import * import direct_cloud_upload urlpatterns = [ path("admin/", admin.site.urls), path('upload_audio_file.html', AudioFileUploadView, name='AudioFileUploadView'), path('direct_cloud_upload/', include(direct_cloud_upload.urlpatterns)), ] views.py from .forms import UploadAudioFileForm from django.http import HttpResponse def AudioFileUploadView(request): if request.method == 'POST': form = UploadAudioFileForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('The file … -
I can't have access to some of my objects (which are not matched with my own manager filters) in Django administration
well, I made my own manager for my model with my customized filters but now I don't have access to all of my objects in Django administration panel and when I click on them in the recently changed panel it says: "object with ID “x” doesn’t exist. Perhaps it was deleted?" this is my managers code: class PublicFilesManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='public') -
Hello, I encountered a problem in django. Here is the error that I got
The Error: ValueError at /admin/saling_stuff_site/menproduct/add/ Invalid format string Request Method: POST Request URL: http://127.0.0.1:8000/admin/saling_stuff_site/menproduct/add/ Django Version: 3.2 Exception Type: ValueError Exception Value: Invalid format string Exception Location: D:\django sale site\sale site\venv\lib\site-packages\django\db\models\fields\files.py, line 318, in generate_filename Python Executable: D:\django sale site\sale site\venv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['D:\django sale site\sale site\vending_site', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'D:\django sale site\sale site\venv', 'D:\django sale site\sale site\venv\lib\site-packages'] Here is models.py > from django.db import models > > class MenCategory(models.Model): > title = models.CharField(max_length=255) > slug = models.SlugField(max_length=255, verbose_name='Url', unique=True) > > def __str__(self): > return self.title > > class Meta: > ordering = ['title'] > > class WomenCategory(models.Model): > title = models.CharField(max_length=255) > slug = models.SlugField(max_length=255, verbose_name='Url', unique=True) > > def __str__(self): > return self.title > > class Meta: > ordering = ['title'] > > > class SubCategoryMen(models.Model): > title = models.CharField(max_length=100) > slug = models.SlugField(max_length=100, verbose_name='Url', unique=True) > category = models.ManyToManyField(MenCategory, blank=True, related_name='product') > > def __str__(self): > return self.title > > class Meta: > ordering = ['title'] > > > class SubCategoryWomen(models.Model): > title = models.CharField(max_length=100) > slug = models.SlugField(max_length=100, verbose_name='Url', unique=True) > category = models.ManyToManyField(WomenCategory, blank=True, related_name='product') > > def __str__(self): > return self.title … -
Django login/register issue
I am new to Django and am building a database-driven website using PyCharm. I am having an issue with users registering/logging in. What is happening is, when a user registers, I check the "Database" tab to the right, and the information will be passed into a table named "SavBlock_user", which will have the users name, password, etc.. Then, when I try to log in, it won't allow me to login due to incorrect username/password. However, if I try to login using a username/password from a different table named "auth_user" (like username: admin / password: admin), then I can successfully login. I'm not sure how to fix this. Ideally, what I would like to do is completely remove the "SavBlock_user" table and strictly use "auth_user" for all of my users, but I'm not sure how to do this. I may have created a 'custom' user model back when I was learning the system, but I can't remember. My files: Project\register\forms.py from django import forms from SavBlock.models import * # <--- Contains User ''' Form for users to register ''' class RegisterForm(forms.ModelForm): email = forms.EmailField( initial='myemail@savagez.com' ) uso_validate = forms.BooleanField( label='Are you a PSMC member? (Chief, Uso, Anak)', initial=False ) class Meta: … -
Django AUTH_USER_MODEL refers to model that has not been installed
I am working on a django prodject which requires login through email or phone number. This is my models.py file: class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, blank=True, unique=True) first_name = models.CharField(max_length=150, blank=True) phone_regex = RegexValidator(regex =r'^\+?1?\d{9,14}$', message="Phone number must be in the format: '+999999999'. Upto 14 digita allowed.") phone = models.CharField(validators=[phone_regex], max_length=15, unique=True) first_login = models.BooleanField(default=False) start_date = models.DateTimeField(default=timezone.now) about = models.TextField(_( 'about'), max_length=500, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) #objects = CustomAccountManager() #objects = EmailOrPhoneModelBackend() USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] def __str__(self): return self.username def get_email_field_name(self): if self.email: return self.email else: return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return self.is_active @property def is_staff(self): return self.is_staff @property def is_admin(self): return self.is_admin To authenticate by using both email and phone number I have created a custom authentication file - backends.py class EmailOrPhoneModelBackend(ModelBackend): #This is a ModelBacked that allows authentication with either a username or an email address. def authenticate(self, username= None, password=None, **kwargs): if '@' in username: kwargs = {'email': username} elif re.search("^0?[5-9]{1}\d{9}$",username): #optional kwargs = {'phone':username} try: user = NewUser.objects.get(**kwargs) if user.check_password(password): return user except NewUser.DoesNotExist: return None def get_user(self, user_id): … -
Django Gunicorn: While registering gunicorn to Vultr server, I made service file, 'django_website.service'
I'm deploying a Django project on an ubuntu machine using gunicorn and nginx, following this tutorial to do it. I have a gunicorn service that looks like this, similar to the one in the tutorial: Description=gunicorn daemon After=network.target [Service] User=admin Group=admin WorkingDirectory=/home/admin/github/django_website EnvironmentFile=/home/admin/github/django_website.env ExecStart=/admin/github/django_website/bin/gunicorn \ --workers 2 \ --bind unix:/tmp/gunicorn.sock \ my_site_prj.wsgi:application [Install] WantedBy=multi-user.target``` After this, I got error messages on the following [![enter image description here][1]][1] [![enter image description here][2]][2] I checked there is a file, django_website.service file in the directory of system... I don't know why it was not found this file... and failed to run [1]: https://i.stack.imgur.com/xHiCg.jpg [2]: https://i.stack.imgur.com/fTJzI.jpg -
how to seprately queryset admin django and rest api by model manger?
By code below in admin panel query set return only rows that is_deleted is "false" if I want to return all rows. I have one idea but not sure that is bests or does not have a bug. all models inherit from this model class BaseModel(models.Model): is_deleted = models.BooleanField(default=False, verbose_name=_("is Deleted")) objects = BaseModelManager() ... and I add filter (is_deleted=false) for all query by the below manager(I can not delete this code because all APIs use this code) class BaseModelManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) for example, a model book is class Book(BaseModel): title = models.CharField(max_length=150) ... In the app admin @register(Book) class BookAdmin(BaseAdminModel): list_display = ('title',) list_filter = ('is_deleted',) class BaseAdminModel is class BaseAdminModel(ModelAdmin): list_display = ('is_deleted',) my idea is to change the "base model" and "base admin model" like this class BaseModelManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_deleted=False) class AdminModelManager(models.Manager): def get_queryset(self): return super().get_queryset().all() class BaseModel(models.Model): is_deleted = models.BooleanField(default=False, verbose_name=_("is Deleted")) objects = BaseModelManager() admin_objects = AdminModelManager() ... class BaseAdminModel(ModelAdmin): list_display = ('is_deleted',) def get_queryset(self, request): return self.model.admin_objects.all() -
Django custom Management: Unable for an "administrator" to update an user
I'm currently creating a django customer management/admin interface for a web application(I know of the built-in one, but as part of this project, a custom one needs to be created). I'm supposed to be able to create/update/delete users from this interface, while connected as a Manager/Admin. While connected as a manager/admin I can successfully create or delete an user, I'm unable to update one (I keep getting the error that the user "already exists") Help or the wright direction to follow would be much apreciated as I've been struging with this for a while and am blocked atm. Hereunder the code. (models.py) class UserProfile (one to one to built-in Django User class) class UserProfile(models.Model): """ The Class UserProfile extends the built-in "User" class of Django Used here to add extra fields in the forms """ user = models.OneToOneField(User, on_delete=models.CASCADE,verbose_name="User") vpn_enabled = models.BooleanField(default=False, verbose_name="VPN Enabled") language = models.CharField(max_length=2, choices=LANGUAGES, default='EN', verbose_name="Language") birth_date = models.DateField(null=True,blank=True, verbose_name="Birth Date") address = models.CharField(max_length=200, null=True, blank=True, verbose_name="Address") postal_code = models.CharField(max_length=50,null=True, blank=True, verbose_name="Postal Code") country = models.CharField(max_length=20, blank=True, null=True, verbose_name="Country") class Meta: verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' def __str__(self): return self.user.username views.py @group_required('Administrator', 'Manager') def update_user(request, id): user = User.objects.get(id=id) user_update_form = UserUpdateForm(request.POST or … -
Python flask/django object-oriented databases usage
I always use SQL or NoSQL databases in my project and at my job, but now I am asked to use an object-oriented DB. I don't even know for what reason I should do that. Despite this fact, I google for OODBMS in python and can't see any easy way to use this approach. Now I think, that django ORM (and flask sql alchemy) are the simplest way to construct databases. So, I have two questions: What are the main benefits of using OODBMS instead of, e.x., Django ORM? Is there a simple way to use OODBMS in flask and django? -
Django, annotate + values duplicates records
I have a model called Location and I'm querying the model with filters that yield 4000 objects: count = Location.objects.filter(**filters).count() 4000 there is a related Model called KPIs, each Location has many KPIs and there are 2,944,000 KPIs records. I have a very complex query for the Location that annotates a lot of the KPIs data. query_set = (Location.objects. filter(**filters). select_related(RelatedNames.LOCATION). prefetch_related(prefetch_location_kpis). alias(latest_date=Max('scores__date'), branch_date=branch_date, **alias_for_trends, **kpis_annotations ). annotate(members_prem_count=sum_of_members_prem, members_count=members_count_of_latest, assigned_members_count=assigned_count_of_latest, farm_latitude=Min(LOCATION__LATITUDE), farm_longitude=Min(LOCATION__LONGITUDE), address=location_str, farm_size=farm_size, latest_date=Max('farm_scores__date'), **kpis_objects ). values(ID, NAME, ADMIN_EMAIL, ADMIN_PHONE, MEMBERS_PREM_COUNT, MEMBERS_COUNT, ASSIGNED_MEMBERS_COUNT, SIZE, ADDRESS, latitude=F(LOCATION_LATITUDE), longitude=F(LOCATION_LONGITUDE), *kpis_names ) ) this query yields 2,944,000 records, which means each for each KPI record and not Location. I tried adding distinct calls in several ways but I either end up with: NotImplementedError: annotate() + distinct(fields) is not implemented. Or the query just ignores it and doesn't add distinct location objects. the docs suggest that values and distinct don't play nice together and that probably somewhere there is an order by that breaks it. I've looked at all the involved models, queries and subqueries and removed the order by but it still doesn't work. I also tried adding this to the query: query_set.query.clear_ordering(True) query_set = query_set.order_by(ID).distinct(ID) but this raises that NotImplementedError -
How to connect some Django template to html hyperlink?
[1]For example i have such html page(main page) [1]: https://i.stack.imgur.com/PJlbd.png Also there are three tags, and i want to generate some template for each tag when it's clicked. For example, if "home" is clicked, i will generate the same page with template of all posts of my blog. If 'create' is clicked, i'll generate the same page with another template that contains a form for creating of a post. It's a code of my main page <body> <div class="left-menu"> <img src="/static/POST PROJECT.png" class="logo" alt=""> <ul class="left-ul"> <li class="left-li"> <a href="{% url 'main'%}">Home</a> </li> <li class="left-li"> <a href="{% url 'main'%}">Create</a> </li> <li class="left-li"> <a href="{% url 'main'%}">Find</a> </li> </ul> </div> <div class="main"> {% block content %} {% endblock %} </div> My urls.py urlpatterns = [ path('', views.main, name='main') ] It's my views.py def main(request): return render(request, "index.html", {}) -
i am new to django and was trying to create a website for event managment.I followed this tutorial
https://realpython.com/django-user-management/ #error Using the URLconf defined in awesome_website.urls, Django tried these URL patterns, in this order: ^ ^dashboard/ [name='dashboard'] ^admin/ The empty path didn't match any of these. can anybody tell me whats wrong ? -
Why is my Slick-Slider carousel not working Django?
I have seen several other posts with issues to get it working but none of them provided a solution for me. The slick-slider folder is in my static file and is successfully being read but nothing at all is happening to my HTML. I appreciate the help :) {% for game in game_lines %} {% if game.status == 'scheduled' or game.status == 'in progress' %} <div class="slick-slider"> <div class="col-1 text-center"> <p class="white">{{ game.away_abbr }}</p> <p class="white">vs.</p> <p class="white">{{ game.home_abbr }}</p> </div> </div> {% endif %} {% endfor %} {% block postloadjs %} <script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"> </script> <link type="text/javascript" href="{% static 'slick/slick.min.js' %}"> <script type="text/javascript"> $(document).ready(function(){ $('.slick-slider').slick({ infinite: true, speed: 700, autoplay:true, autoplaySpeed: 2000, slidesToShow: 10, slidesToScroll: 1 }); }); </script> {% endblock %} {% block extra_css %} <link rel="stylesheet" href="{% static 'slick/slick.css' %}"> <link rel="stylesheet" href="{% static 'slick/slick-theme.css' %}"/> {% endblock %} -
React and Django Nginx gives 404 not found error on page refresh
I deployed my Django and React app (CRA build with npm run build) on digital ocean and Nginx serves as reverse proxy. I followed DigitalOcean blog about deploying, however, I encountered a problem that everytime I refresh the page other than home page, it gives 404 not found error. Any help regarding this issue please? Here is my nginx code. I am pretty sure I am missing something. server { server_name mloverflow.com www.mloverflow.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/{username}/mloverflow/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/home/{username}/mloverflow/mloverflow.sock; } -
Anybody know how to fix url config only seeing admin in django? [closed]
Picture Picture Im getting the error and I dont know how to fix it but my test path isnt showing up. Only the default admin path!!!? -
How to add attributes manually in a django form before saving it?
I am getting all the attributes from django form template and saving it using form.save() But before using form.save() i want to manually add one attribute (is_scheduled = 1). I tried the following way but it's not working: def add_operation_event(request): form = EventForm(request.POST) form.is_scheduled = 1 form.save() return redirect('/dashboard') Please suggest me an easy way to do it. -
django-bootstrap4 my form always has is-valid tags, how to stop this?
Summary: I am upgrading a django-project from bootstrap3 to bootstrap4, so I am using django-bootstrap4 now. The is-valid tags on form elements are, after upgrade to bootstrap4, rendering a big green tick and making the form fields wider. How do I stop is-valid tags being added? This is even before the form has been submitted. There is no validation logic. more: I have a filter form generated on some of my pages {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} The form fields are generating markup like: <div class="form-group is-valid"> <label class="sr-only" for="id_order_number__icontains">Order number contains</label> <input type="text" name="order_number__icontains" class="form-control is-valid" placeholder="Order number contains" title="order_number__icontains" id="id_order_number__icontains"> </div> The <input> element has been assigned class is-valid. This happens to all elements. Previously this happened too, but there was no visual effect. Bootstrap4 is making the field wider and displaying a big green tick. I don't think the fields should be marked is-invalid before submission, this doesn't make much sense to me. I don't have validation scripts, and if I disable javascript on the page, I get the same result anyway. -
TypeError at /student/ HTTP status code must be an integer
I am fetching data from multiple tables to display in template, but getting type error for the same. kindly help me to find the mistake. Models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) User = settings.AUTH_USER_MODEL User_id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() may be i have not implemented correct logic in views.py views.py @login_required(login_url='login') @allowed_users(allowed_roles=['Student']) def handle_response(request): if request.user.is_authenticated: myuser = User.objects.all() title = quiztitle.objects.all() data = question.objects.all() if request.method == 'POST': Answer=request.POST.get('Answer') response = answer(Answer=Answer) response.User_id = request.user response.Quiz_id = request.quiztitle response.Qid = request.question Answer.save() return HttpResponseRedirect('/student') return render(request, "student.html", {"messages":data},{"topic":title},{"user1":myuser}) -
Django MySQL Lost Connection
I'm working on a URL Shortener (https://cutshort.in) using Django and MySQL. I do realize that it might be overkill to use Django for this purpose. But I'm quite set on using Django for now. For this to work well, I require a persistent connection (if that's the right term) to MySQL. Ever so often when I ping the website I get a Lost Connection error, but upon re-pinging the site once or twice it works again. For persistent connections, the Django documentation suggests using CONN_MAX_AGE=None. But this seems to increase the frequency of Lost Connection errors instead. I'm using the dj-database-url python package for re-setting the SQL connection to use a database URL. Could the problem possibly be caused by the way it handles the None value? https://github.com/jacobian/dj-database-url . No offense to Jacob Kaplan-Moss the creator of dj-database-url. It helped me get started my Django and deploying it. The standard error message I get (while debugging locally): Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1 Python Version: 3.9.0 Installed Applications: ['shortner.apps.ShortnerConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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'] Traceback (most recent call last): File "/Users/rahultandon/Desktop/stuff-made-by-me/projects/cutshort/env/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute …