Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid interpolation format for "environment" option in service "web": "SECRET_KEY
I'm doing a project online book store on django, when i try to setup environment variable I am facing the problem.My docker-compose.yml file looks like version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY=secret_key volumes: - .:/code ports: - 8000:8000 depends_on: - db db: hostname: db image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data environment: - "POSTGRES_HOST_AUTH_METHOD=trust" ports: - "5432:5432" volumes: postgres_data: and my settings.py : SECRET_KEY = os.environ.get('SECRET_KEY') Note That my secret_key doesn't contains "$" sign. Whenever I try to do "docker-console down" it shows error. -
Django - Messages functionality not working in Class based view
Unable to display messages in class based view. In another app's views.py, it is working fine where I used function based view. views.py: class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, DeleteView): model = Post success_url = '/user-profile/' success_message = "Your post has been deleted sucessfully!" def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False urls.py: path('user-profile/', user_views.user_profile, name='user_profile'), html: {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} -
Reverse url problem: template url is giving reverse error
I am getting this error Reverse for 'video_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['video/(?P[-a-zA-Z0-9_]+)/$']. Please help.. #urls.py urlpatterns = [ path('video/<slug:slug>/', views.VideoDetail.as_view(), name='video_detail'), ] #views.py class VideoDetail(DetailView): model = Video template_name = 'video.html' #HTML <a href="{% url 'video_detail' video.slug %}"> #models.py class Video(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=200, unique=True) year = models.CharField(max_length=4) category = models.CharField(max_length=3) genres = models.CharField(max_length=100) poster = models.URLField(default='') plot = models.CharField(max_length=500) trailer = models.URLField(default='') def __str__(self): return self.title def get_absolute_url(self): from django.urls import reverse return reverse("video.html", kwargs={"slug": str(self.slug)}) #urls.py main site urlpatterns = [ path("admin/", admin.site.urls), path("", include("accounts.urls")), path("", include("blog.urls")), path("", include("video.urls")), ] -
Django AllAuth KeyError at /accounts/signup/ 'sociallogin'
I am using Django All Auth for the first time. I have set up all the urls. I haven't setup any social network provider. The login works, but when I click on the signup it comes up with the exception: KeyError at /accounts/signup/ 'sociallogin' I am also trying to make the Firstname and Last name compulsory on the regular SignUp (not the Social Login). Is my forms.py correct? class CustomUserCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') class Meta: model = CustomUser fields = ('email', 'first_name', 'last_name') def save(self, request): user = CustomUserCreationForm(request.POST) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() My All Auth Settings ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False ACCOUNT_SESSION_REMEMBER = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGOUT_REDIRECT_URL ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 300 ACCOUNT_USERNAME_BLACKLIST = ['admin', 'superuser', 'user'] I didn't change anything in the ACCOUNT_FORMS dictionary. Its the default. Thank you very much. -
How to pass parameters of Ajax URL in Django?
I used Ajax to add items to wishlist: <a href="{% url 'listing:wishlist' list.slug %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> the url looks like: path('wishlist/<slug:title_slug>/', wishlist, name='wishlist'), but I don't know how to pass list.slug or title_slug in above url using Ajax: $(document).on('click', '#wishlistbtn', function (e) { $.ajax({ type: 'GET', url: "{% url 'listing:wishlist' %}", data: { title_slug: e.target.getAttribute('data-slug') }, success: function (response) { alert('added to wishlist') } }) }) my above stated solution didn't work? Please help me with this. Thank you. -
TypeError: Object of type Reporter is not JSON serializable
I am trying to add the reporter with ajax but it is not working properly. When I send json data with {'reporter':reporter.name} then it creates the obj in the database successfully but I am not being able to display this newly created obj in the select option. I have to refresh to see this object in the select option. Then I tried sending the object instance as a JsonResponse by dumping with json.dumps(obj) but I am getting this error serializable error. I have to create the reporter object and display in the select option without page refresh. How can I do it ? What's wrong here in my approach ? view class AddReporterView(View): def post(self, request): name = request.POST.get('name') reporter = Reporter.objects.create(name=name) data = { 'reporter': json.dumps(reporter) } return JsonResponse(data) Scripts $(document).on('submit','#target-category-form',function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr("action"), data: { name:$('#name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, type: 'POST', dataType:'json', success: handleFormSuccess, }); }); function handleFormSuccess(data){ $("#id-categories").html(data); $('#modalOpen').modal('toggle'); console.log(data); } I want to display the created data here in this html select element <select class="form-control" name="reporter" multiple="multiple" id="id-categories"> {% for reporter in reporters %} <option value="{{reporter.pk}}">{{reporter.name}}</option> {% endfor %} </select> -
Deploying Django to Elastic Beanstalk, /opt/python does not exist
I'm completely lost & have been trying to fix the same issue for the past 4-5 days while deploying my django app. The issue is as follows. My migration command is failing, the migrate config file is as follows container_commands: 01_migrate: command: "python3 manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: djangomicroblog.settings I've also tried changing the command to a number of different things, including: command: "python manage.py migrate" command: "django-admin.py migrate" command: "/opt/python/run/venv/bin/python3 manage.py migrate" Different commands give me different errors, python manage.py migrate reports: 2020-06-21 13:15:48,639 P8373 [INFO] File "manage.py", line 16 2020-06-21 13:15:48,639 P8373 [INFO] ) from exc 2020-06-21 13:15:48,639 P8373 [INFO] ^ 2020-06-21 13:15:48,640 P8373 [INFO] SyntaxError: invalid syntax I assume this is because it's trying to execute with python2 Python3 manage.py migrate reports: 2020-06-21 13:12:37,445 P8066 [INFO] Traceback (most recent call last): 2020-06-21 13:12:37,445 P8066 [INFO] File "manage.py", line 10, in main 2020-06-21 13:12:37,445 P8066 [INFO] from django.core.management import execute_from_command_line 2020-06-21 13:12:37,445 P8066 [INFO] ModuleNotFoundError: No module named 'django' 2020-06-21 13:12:37,445 P8066 [INFO] 2020-06-21 13:12:37,445 P8066 [INFO] The above exception was the direct cause of the following exception: 2020-06-21 13:12:37,445 P8066 [INFO] 2020-06-21 13:12:37,445 P8066 [INFO] Traceback (most recent call last): 2020-06-21 13:12:37,445 P8066 [INFO] File … -
Messages module urls.py redirect
I get the following warning after creating content. File "C:\bt\products\urls.py", line 2, in <module> from . import views File "C:\bt\products\views.py", line 29 messages.success(request, 'Your profile was updated.') ^ TabError: inconsistent use of tabs and spaces in indentation views.py def create(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Your content was create.') context = { 'form': form } return render(request, "products/create.html", context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='product-index'), path('create/', views.create, name='product-create'), path('<int:id>/', views.detail, name='detail'), #path('<int:product_id>/', views.productDelete, name='delete'), ] Could you help? Thank you. -
How to fix TypeError at /admin/pages/course/add/ in Django admin?
I'd done my models in models.py and run migrations after makemigrations. I'd also registered my model at admin.py and I can see it appearing in the admin panel. But when i clicked add course it gave me the following error: TypeError at /admin/pages/course/add/ function missing required argument 'year' (pos 1) Request Method: GET Request URL: http://127.0.0.1:8000/admin/pages/course/add/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: function missing required argument 'year' (pos 1) Exception Location: C:\Users\ahnaa\OneDrive\Documents\Web Developent\Django\school_app\venv\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 829 Python Executable: C:\Users\ahnaa\OneDrive\Documents\Web Developent\Django\school_app\venv\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\ahnaa\\OneDrive\\Documents\\Web Developent\\Django\\school_app', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\ahnaa\\OneDrive\\Documents\\Web ' 'Developent\\Django\\school_app\\venv', 'C:\\Users\\ahnaa\\OneDrive\\Documents\\Web ' 'Developent\\Django\\school_app\\venv\\lib\\site-packages'] Server time: Sun, 21 Jun 2020 19:50:52 +0600 -
Cannot assign "'post'": "Comment.content_type" must be a "ContentType" instance
I want to create comment option in my Post detail view for blog.I inherited FormMixin to use CommentForm in PostDetailView. Besides I had to inherit HitCountDetailView for hitcount.Now when I try to add comment it is showing this error "Cannot assign "'post'": "Comment.content_type" must be a "ContentType" instance.I tried several times to solve it but failed.How can I solve this error? Any suggetions. Thanks in advance. Here is my code: Views.py: class PostDetailView(FormMixin, HitCountDetailView): model = Post form_class = CommentForm template_name = "blog/published/post_detail.html" context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_initial(self): instance = self.get_object() print(instance.title) return { "content_type": instance.get_content_type, "object_id": instance.id, } def get_success_url(self): return reverse("post-detail", kwargs={"slug": self.object.slug}) def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(*args, **kwargs) stuff = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter_by_instance(stuff) context['comments'] = comments context["form"] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) models.py @python_2_unicode_compatible class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(blank=True, null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(blank=True,null=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') class … -
Is there way to set image file in input file using jquery?
I can compress image but can't upload compress image through ajax. my preview image is compress, but how to send it through ajax post request. I make input field in form and I want to select compress image to that input field. so that compress image can upload through it. But I don't know how to do it? I searched lot from 3 days but didn't find any help. Or if its there any other ways to upload compress image please tell. HTML {{ form.image|as_crispy_field }} //form imagefield has id=file <form action="home_page/mainpost/post/" id="mainpost-form" enctype="multipart/form-data" class="shadow-lg p-3 mb-5 bg-white rounded" method="POST"> {% csrf_token %} <input id="img-hidden" name="image" accept="image/*" type="file" style="display:none"> {{ form.info_post|as_crispy_field }} Preview Image - <br> <div class="hidden-img-div"> <img id="original-Img"/> </div> <br> <input class="btn btn-danger" type="submit" value='Post'> </form> Jquery <script> document.getElementById("file").addEventListener("change", function (event) { compress(event); }); function compress(e){ const width = 300; const fileName = e.target.files[0].name; const reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = event => { const img = new Image(); img.src = event.target.result; img.onload = () => { const elem = document.createElement('canvas'); const scaleFactor = width / img.width; elem.width = width; elem.height = img.height * scaleFactor; const ctx = elem.getContext('2d'); // img.width and img.height will contain the original … -
ModuleNotFoundError: No module named 'oscar.apps.communication'
I was trying to follow django-oscar documentation. Whenever I ran the server it gives me an exception (ModuleNotFoundError: No module named 'oscar.apps.communication') I think it happens due to the misconfiguration of settings.py file. But I can't understand what's wrong is going on there. settings.py """ Django settings for frobshop project. Generated by 'django-admin startproject' using Django 2.2.13. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from oscar.defaults import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ng)eg&5czqn675xe7oi56%ivr%uw^2dy#tv(bglq*drk0oy-&(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar.config.Shop', 'oscar.apps.analytics.apps.AnalyticsConfig', 'oscar.apps.checkout.apps.CheckoutConfig', 'oscar.apps.address.apps.AddressConfig', 'oscar.apps.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig', 'oscar.apps.communication.apps.CommunicationConfig', 'oscar.apps.partner.apps.PartnerConfig', 'oscar.apps.basket.apps.BasketConfig', 'oscar.apps.payment.apps.PaymentConfig', 'oscar.apps.offer.apps.OfferConfig', 'oscar.apps.order.apps.OrderConfig', 'oscar.apps.customer.apps.CustomerConfig', 'oscar.apps.search.apps.SearchConfig', 'oscar.apps.voucher.apps.VoucherConfig', 'oscar.apps.wishlists.apps.WishlistsConfig', 'oscar.apps.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.users.apps.UsersDashboardConfig', 'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig', 'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', 'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig', 'oscar.apps.dashboard.pages.apps.PagesDashboardConfig', 'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig', 'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig', 'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig', 'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig', 'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] SITE_ID = 1 MIDDLEWARE = … -
Django readonly_fields not showing data
My Orders model has 'rate' and 'total_amount' field. I had to derive rate from different model so i created 'unit_rate'. Same way i wanted my 'total_amount' fields should be multiplication of 'quantity' and 'unit_rate' which i tried by doing 'total_pay'. You can see my code for the same below. class OrderAdmin(admin.ModelAdmin): def unit_rate(self,obj): self.rate = Product.objects.get(pk=obj.order_id) return self.rate.price def total_pay(self,obj): self.rate = Product.objects.get(pk=obj.order_id) self.total_amount = self.rate.price * obj.quantity return self.total_amount list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer', 'quantity','unit_rate','total_pay') readonly_fields = ('total_pay','unite_rate') admin.site.register(Orders,OrderAdmin) As 'total_pay' and 'unit_rate' are obtained from other columns, admin doesn't need to enter them. That's why i kept them on readonly_fields'. Problem is whenever is create order through admin interface, 'total_pay' and 'unit_rate' does not shows up in admin. It just shows dash like this -. Doing this since a while. I could really use your help.thanks -
Django view with simple GET method results in TypeError
Using a very simplistic subclass of django.views.View I only get a TypeError with »__init__() takes 1 positional argument but 2 were given« as message. urls.py is: from myapp import views from django.urls import path urlpatterns = [ path('webhook/', views.Webhook, name='myapp-webhook'), ] views.py: from django.http import HttpResponse, HttpResponseForbidden from django.views import View class Webhook(View): def get(self, request, *args, **kwargs): """We don't provide GET access here.""" # return 403 (Forbidden) return HttpResponseForbidden() def post(self, request, *args, **kwargs): # return 200 (OK) return HttpResponse() tests.py: from django.test import TestCase class WebhookTests(TestCase): def test_get_method_is_forbidden(self): response = self.client.get('/webhook') self.assertEqual(response.status_code, 403) Now, either accessing /webhook in a browser or running ./manage.py test results in: Internal Server Error: /webhook/ Traceback (most recent call last): [...] TypeError: __init__() takes 1 positional argument but 2 were given I'm surely missing something here. Pointers to what this is, are much appreciated. -
Django DB design - Book specific unique URLs with unique_together
I have two models with one to many relationship. A Book has many Chapters. Both the models have a slug field. For Book the slug column is UNIQUE. For Chapter the book_id and slug are UNIQUE together. The Chapter model also has a field order. And book_id and order are UNIQUE together. This way, I can generate unique URLs for books automatically and allow duplicate slugs for different books. Current models.py: class Book(models.Model): # other fields slug = models.SlugField(max_length=80) def save(self, *args, **kwargs): if not self.pk: self.slug = unique_slug(self.title) return super(Book, self).save(*args, **kwargs) class Chapter(models.Model): #other fields book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='chapters') slug = models.SlugField(max_length=80) order = models.IntegerField(null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['book_id', 'order'], name='unique_order'), models.UniqueConstraint(fields=['book_id', 'slug'], name='unique_slug')] ordering = ['order'] The downside here is, in my chapter views I have to query the book first and get the chapter slug with the matching book_id. While previously with just the chapter slug UNIQUE, I was just querying the chapter table alone. My goal is to have URLs like this book/rndmstrng-alice-in-the-wonderland/chapter/down-the-rabbit-hole book/rndmstrng-some-other-book/chapter/down-the-rabbit-hole Is there any issue in this design? Are too many UNIQUE constraints bad? Is there a better way to implement this? -
How to send data from custom.py to html - Django
Concept that I'm trying to achieve: A web application with speech enabled that displays what the user says, on UI. Example: If the user says "Hello there!", "Hello there!" should be displayed on the UI. What I have: Files that I have in my app: speech.py (has a variable(displayOnUI) that stores what the user says) speech.html (where I want to display what the user says) Note: speech.py repeatedly keeps listening to user and keeps storing what the user says in a variable(displayOnUI). What I tried: I tried passing the value of the variable displayOnUI which is in speech.py to view.py and then passing it to speech.html using context. speech.py displayOnUI= "Please say something.." def SpeechRecognition(): while 1: try: with sr.Microphone() as source: r.adjust_for_ambient_noise(source, duration=1) audioReceived = r.record(source, duration=3) displayOnUI= r.recognize_google(audioReceived) view.py from SpeechApp.speech import displayOnUI def speech(request): data = displayOnUI return render(request, "speech.html", {"data": data}) speech.html <div> <h3>This is what I heard: {{data}} <h3/> </div> Problem that I'm facing I'm able to display the initial value that is present in displayOnUI (that is "Please say something..") on UI, however I'm not able to display the updated value(user's command) of displayUI in speech.html. (I guess it is because view.py is executed … -
Save file uploaded in Django without a database
I am trying to save a file and do something to it a from in an html file, I am not using django forms but I am using django for backend and I don't need a database since I don't want to keep any of the files. I tried what the django documentation has instructed. html file <input type="file" id="face_files" name="face_files" multiple > save_file.py os.mkdir(folder) counter=1 for file in request.FILES.getlist('face_files'): destination=open(folder +"/face"+str(counter)+".jpg", 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() counter+=1 But I get the error ValueError: seek of closed file Working, what am I doing wrong? -
Django JavaScript fpr bootstrap grid does not work
I deployed website using Django. I used external js code for grid (I want site to be user-friendly for all screens). When running just html using same js code it works fine. But when I actually deployed website grid become unclickable from small screens and you cannot see menu. I couldn't find anything in Google. I am not sure if I have to use load static because I use external script, but tell me if I am wrong <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1"> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <!-- DOCUMENTATION NAVBAR --> <nav class="navbar navbar-default navbar-inverse navbar-fixed-top"> <!-- Inside of a Container --> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <!-- This is the actual code that create the "hamburger icon" --> <!-- The data-target grabs ids to put into the icon --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <!-- Code for the hamburger icon--> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" style="color:white;" href="{% url 'wpb:index' %}"> Mycroft Conspiracy Project</a> </div> <!-- Anything inside of collapse navbar-collapse goes … -
How to run a Django project with .pyc files without using source codes?
I have a django project and i want to create the .pyc files and remove the source code. My project folder name is mysite and I ran the command python -m compileall mysite. The .pyc files are created. After that i tried to run my project with python __pycache__/manage.cpython-37.pyc runserver command but i've got an error such as ModuleNotFoundError: No module named 'mysite' There are two things I would like to ask about this. First, how can I solve this problem and run my project with .pyc file? Secondly, is it enough to move the .pyc files created to a separate folder in accordance with the django project structure? -
Facing issue with Django version and Sqlite3 version compatibility
First of all, the issue which i am posting here was already answered earlier here. But somehow the fixed shared was not working for me. Either i havent applied properly or i am having some other issue too. I am using Django on Centos7 machine. Django version is 3.0.7 while running the server i got error with django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). I have upgraded the sqlite3 version and now it is in 3.32.2. but still when i run the manage.py i am getting the same error. By referring the solutions already mentioned here, i had tried changing the PATH definitions but still i am stuck. thanks in advance. -
Add input in html and form validation in model form
I have a form from modelForm. I have a checkbox that is not part of the model so I included it in the form field. Now, I have added it in the html manual because there will be text in between. My intention is for form validation and not the actual textfield. forms.py understand = forms.CharField(max_length=10, required=False) <form name="form" action="#" method="POST"> {{ form.as_p }} <fieldset> <p>textt</p> <div> <input type="checkbox" name="understand" value="understand" id="understand"><label for="understand" style="display: inline-block;">I Agree</label> </div> <button class="button">Submit</button> </fieldset> </form> The above code adds another Charfield. -
Django, io module for deserialization of data
In Django Rest Framework documentation, there is process of deserialization as mention below import io stream = io.BytesIO(content) data = JSONParser().parse(stream) here content is a JSON object. Why can't we directly deserialize data as data = JSONParser().parse(content), when I did that in localmachine it raised error AttributeError: 'bytes' object has no attribute 'read' -
"message": "expected string or bytes-like object",
#i want the total time taken by a session to get completed,but i am getting the above mentioned error #MODEL class User(models.Model): user=models.CharField(max_length=40) class Sport(models.Model): Sports_Name=models.CharField(max_length=30,null=True,blank=True) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') Start_time=models.TimeField(auto_now=False, auto_now_add=False,null=True) End_time=models.TimeField(auto_now=False, auto_now_add=False,null=True) class Gamification(models.Model): User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE) #viewset users=Gamification.objects.all() b=[] for user in users: b.append({ "User_Name":user.User_Name.user_name, 'Session_Created':Session.objects.filter(Host=user.User_Name).count(), "Session_Joined":Session.objects.filter(Players_Participating=user.User_Name).count(), "Completion_Time(in days)":Session.objects.filter(End_time=user.User_Name), }) return Response({'success':b}) -
Django form list field or json field?
I have a model called participants as below class participants(models.Model): username= models.CharField(max_length =50) votes = models.IntegerField(default=0) voted_by = ? Votes is the total number of votes given by users and single user can vote multiple times. If the user have voted then the user should wait 1 hour to vote again. Now i am wondering, how can i store users id in a way that it would be easier to know who voted how many times and the recent date and time the user have voted. Can someone suggest me or refer some examples that i can solve this problem. -
Django Max & Min pricse filter from models
I created an DJANGO models in my "models.py" contains "Item_Frash_pricse" field in it class Item(models.Model): item_id = models.AutoField(primary_key=True) item_category = models.ForeignKey(Product,on_delete=models.CASCADE) item_subCategory = models.CharField(max_length=30) item_name = models.CharField(max_length=30,default='') item_titile = models.CharField(max_length=30) item_FrashPricse = models.FloatField(max_length=30) the PROBLEM is that i want to fetch all the query set where Item_Frash_pricse <= max_amount andItem_Frash_pricse >= min amount are in my "views.py" def ByPricse(request,filter_by): max_amount = request.GET.get('Maxamount',None) min_amount = request.GET.get('Minamount',None) **filter_item = Item.objects.filter(Item_Frash_pricse <= max_amount and vise versa ????**) return HttpResponse('Ok') But this filter_item = Item.objects.filter(Item_Frash_pricse <= max_amount is wrong syantax cant do >= opration