Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't figure out primary key
Dumb question, but I can't seem to figure it out. I use Djangos User model, with a custome Profile model (OneToOne relation). Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) weight = models.FloatField(max_length=20, blank=True, null=True) height = models.FloatField(max_length=20, blank=True, null=True) goal = models.FloatField(max_length=20, blank=True, null=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save(). I have this code in my view (i want to update data inside the Profile model) def home(request): profile = get_object_or_404(Profile, pk=id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save return render(request, 'Landing/index.html',{'form':form}) My question is that what is my primary key in this situation? -
Unique Id generator based on created date in django?
hello I am A new to software , i am working on id generation in the format- Q/YYYYMM0001 where 0001 is a serial number for which i wrote the following model- from sequences import get_next_value class Queryform(models.Model): querynumber=models.CharField(primary_key=True,editable=False) queryserialnumber=models.CharField(get_next_value=True,initial=0) querydatecreated=models.DateField(auto_now_add=True) def querynumber(self): return '{}/{}{}'.format(str="Q",self.querydatecreated.truncatemonth,self.serial_no.zfill(4)) def save(self, *args, **kwargs): self.generated_id = self.generate_id() super().save(*args, **kwargs) i have a few doubts - have i used get_next_value correctly ? str="Q" will give a string value? what if i delete on row from the table will the serial number vary ? example - i had Q/YYYYMM009 id saved later i deleted one , that is now i have 8 rows. The next id generated will be again Q/YYYYMM009 ? i dont want to repeat the ids to avoid clash . -
How to Get data from single django app models on multiple html page
I'm trying to display data from single django app models to multiple html page but I don't know what the correct steps are anyone can help me and i will be thankful i'm using django -
Can't store a Selenium web driver object to recover it through Django views
After days of research, I wasn't able to properly store a Selenium web driver object to recover it through different Django views. In fact, My project has only one view, and all I need is to recover the same instance of the web driver object every time that view is called. All my app does is making AJAX post requests to the view and updating the frontend and some data in the web driver window. Having initialized the driver as driver = webdriver.Chrome(executable_path=driverpath, desired_capabilities=caps) , these are all the things that I tried: 1) Storing the object in request.session array. Of course this doesn't work, a web driver object is to complex to be JSON serialized. TypeError: Object of type WebDriver is not JSON serializable 2) Pickle Serialize: Didn't work. A code like pickle.dumps(driver, open( "driver.p", "wb" )) throws this error AttributeError: Can't pickle local object '_createenviron.<locals>.encode' 3) Creating a new driver and assigning to its session_id attribute the previous web driver session_id value. Didn't work. This was the approach: request.session['driver_id'] = driver.session_id #And then on another view call: chrome_options = Options() chrome_options.add_argument("--headless") #to prevent opening a new window new_driver = webdriver.Chrome(options=chrome_options) new_driver.session_id = request.session['driver_id'] 4) Using Ctypes: This is … -
Django custom user model with BaseUserManager set is_active=True not working
I'm working on a project using Python(3.7) & Django(3) in which I have implemented a custom user model and inside the User manager, under create_user method I set user.is_active = True but it's not working on signup. Here's my implementation: class MyAccountManager(BaseUserManager): def create_user(self, email, fullname, password=None): if not email: raise ValueError('Users must provide the Email.') user = self.model( email=self.normalize_email(email), fullname=fullname, ) user.set_password(password) user.is_active = True user.save(using=self._db) return user def create_superuser(self, email, fullname, password=None): user = self.create_user( email=self.normalize_email(email), fullname=fullname, password=password ) user.is_admin = True user.is_staff = True user.is_active = True user.is_superuser = True user.save(using=self._db) return user createsuperuser is working fine, mean it setup is_active = True but when signup as other user types it's not working. What can be wrong? -
Django ajax post 200 but no change(post) in database
I am trying to post user location to django(postgres) database. While my ajax request shows message 200 (OK) , this is not reflected on change on the database. I can't seem to figure out why. <html> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/wicket/1.3.6/wicket.min.js" integrity="sha512-7V9RlkyO655oDrkJ7kMXAa4Z+DS0+Kq/eXV0ZKWAv9RJtstw7rHJU1/KgpLovGZtL2FaJ9L24w3qa6L/qy3spg==" crossorigin="anonymous"></script> <head> {% load leaflet_tags %} {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} </head> <body> <div> <strong>Current position: </strong> {{ user_location }}<br/> </div> <label for="locations-status">Locations enabled?</label> <input type="checkbox" id="locations-status"> <script type="text/javascript">window.CSRF_TOKEN = "{{ csrf_token }}"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = Cookies.get('csrftoken'); $(document).ready(function(){ $('input[type="checkbox"]').click(function(){ if($(this).prop("checked") == true){ getLocation() } else if($(this).prop("checked") == false){ console.log("Location services are disabled"); } }); $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { … -
What is the best way to make Live tracking of each user on front-end pages (date-time and other actions)?
Our project is one of the online Shopping Service , built with Django and front-end is made up with Quasar! As you guys know that users' every clicks do not request to The Back-end, but I should track every pages users visit(for analytics)! And if the Data we will be storing gets bigger than we imagine , then we will start storing the data to another Database! 2nd question is how to store data? Should we store in the default DB or a separate Big Data DB? thanks for your answers! -
Django refresh page but dont redirect
On the page /home I created a login button in my navbar and when you click on it it will open a kind of a popup with changing display to block. But my problem is that I cant find out how the user could stay on the page when logging in with wrong data. At the moment it just returns me to the /home page and if I click again on the navbar button the login window opens with the "error" message but I want it to either redirect me to the /home page but the login popup is still opened or just don't redirect me anywhere. So I think I am just looking for a way that this message updates but you stay on the login popup. Here is my part of the views.py: def post(self, request, *args, **kwargs): # form = UserCreationForm(request.POST) # print(form.errors) # <process form cleaned data> username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: print(user, "has successfully logged in") login(request, user) return HttpResponseRedirect('/recipes/all') else: messages.error(request,"Password or username is incorrect") return HttpResponseRedirect('/recipes/all') And here is the part of my HTML file: <div class="login-popup-box" id="login-popup-box"> <div class="user-card-login"> <div class="close-button-box"> … -
How to display ReadOnlyFields without label in Django Admin?
I am trying to display some data in my Django admin ReadOnlyFields, but I am unable to display, I want to display emailid and verify_emailid in the same line in the fields, I can do it using fieldset but it's displaying lable also, please let me know how I can display data without a table. Here is my admin.py file... class MyModelAdmin(ReadOnlyAdminMixin, CustomModelAdmin): fields = (('emailid','verify_emailid),'mobilenumber','type') here emailid and verify_emailid display in the same line but the issue is the verify_emailid display label, and I don't want the label of verify_emailid, please let me know how I can remove the verify_emailid label... -
How can i use django allauth token in next steps for authorization?
I used the Django-allauth login,but i can not use token for next steps for authorization,and i do not know how to change views of login and logout method that are in Django-allauth. -
which gitignore file shall i use when uploading a django project which contain a secret key?
i am new in github, i uploaded a django project without a git-ignore file & github community banned my account. That's why i need to know how to use a git-ignore file & also license. -
Django 3.1 not closing postgres db connection after tests
The following method is called as part of a test (the test tries to find an external api call in the DB and if it can't find it it will do a real API call) def _ask_transliterate(self, content): found = APITransliteration.objects.filter( source_text=content, from_lang=self.from_lang, to_lang=self.to_lang ) if len(found) == 0: my_json = self._ask_actual_api(content, TRANSLIT_PATH, self.translit_params()) my = APITransliteration( source_text=content, response_json=my_json, from_lang=self.from_lang, to_lang=self.to_lang ) my.save() return my.response_json return found.first().response_json When I just call the class that inherits from TestCase it runs fine, which I believe is because it doesn't find the value in the DB so follows the inner if. If I do a full run of the tests, django refuses to destroy the test database due to an open connection, and SELECT * FROM pg_stat_activity; Reports that it is the query that corresponds to the first() call. This would make sense because the method gets called with the same parameters by two tests, so would find the value for the second run (which is the last test that gets executed). What doesn't make so much sense to me is why the connection is in ClientRead and Idle after my successful complete test run. Is it me that is doing something wrong … -
Subprocess.run not reading file contents from stdin in Django
I'm working on a University project where we are developing a competitive coding platform using Django. We're saving the user's code in a text file and comparing the generated user output with the ideal output all while reading ideal input from a text file. views.py def compileAndRun(request, username, qno,testcase, lang): defaultDir = os.getcwd() os.chdir("questions/") with open("standard/output/question{}/output{}.txt".format(qno,testcase), "r") as idealOutput, open("usersub/newuser/question{}/output.txt".format(qno), "r+") as userOutput, open( "standard/input/question{}/input{}.txt".format(qno,testcase), "r") as idealInput, open("usersub/newuser/question{}/error.txt".format(qno), "w+") as e: os.chdir("usersub/{}/question{}/".format(username, qno)) # CHANGE DIR BASED ON USERNAME AND QUESTION arg1 = arg2 = arg3 = arg4 = '' if lang == 'c': arg1 = 'gcc' arg2 = 'question{}.c'.format(qno) arg3 = './a.out' elif lang == 'cpp': arg1 = 'g++' arg2 = 'question{}.cpp'.format(qno) arg3 = './a.out' elif lang == 'py': arg3 = 'python3' arg4 = 'question{}.py'.format(qno) compileCode = [arg1, arg2] runCode = [arg3, arg4] compiled = True try: if lang != 'py': a = subprocess.run(compileCode, stderr=e) if a.returncode != 0: compiled = False if (compiled): userOutput.truncate(0) # EMPTY OUTPUT FILE TO PREVENT UNNECESSARY CONTENT FROM PREVIOUS RUNS. p = subprocess.run(runCode, stdin=idealInput, stdout=userOutput, stderr=e) userOutput.seek(0) o1 = userOutput.readlines() o2 = idealOutput.readlines() if (o1 == o2): os.chdir(defaultDir) return HttpResponse("SUCCESS") else: os.chdir(defaultDir) return HttpResponse("FAILED") os.chdir(defaultDir) return HttpResponse("FAILED") except: os.chdir(defaultDir) return HttpResponse("ERROR") question1.cpp … -
Django won’t let me query a table by any attribute bar ‘pk’
So I’m trying to query my ‘Profile’ table by the relation attribute ‘owner’, which links to another table ‘User’. However, when I attempt to query by this attribute, I get the following error: 'AssertionError: Expected view UserProfile to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.' To query the table I used: Profile.objects.filter(owner__username = username) Models.py: class User(models.Model): username = CharField(max_length = 80) class Profile(models.Model): owner = models.OneToOneField('User', related_name = 'profile', on_delete = models.CASCADE) Views.py: class UserProfile(generics.GenericAPIView, mixins.RetrieveModelMixin): def get_queryset(self): username = self.kwargs['username'] return Profile.objects.filter(owner__username=username) serializer_class = UserProfileSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) Urls.py: urlpatterns = [ path('user/<str:username>/profile/', views.UserProfile.as_view()), ] Why am I getting this error, how would I fix it? Any help would be much appreciated. Thanks, Grae. -
Django wont load static .css files error: 404 1689
Django was able to load a static .png file but not the static .css file, why? settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] css file h1{ color: red; } html <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8"> <title>Django Guitar Page</title> <link rel="stylesheet" href="{% static "css/mysyle.css" %}"/> </head> <body> <<h1>Hi, this is text</h1> <img src="{% static "images/a_picture.png" %}" alt="Uh oh, didn't show"> </body> </html> file path first_app/static/css/mystyle.css first_app/static/css/images/a_picture.png -
How to make collapsible and non collapsible elements in navbar?
I want that in mobile view my search form shows but it collapsed please help. My Navbar with the search form inline 60. I want to make my search form non-collapsible in mobile view. Please improve my code for this purpose. please please please please please please please, please please please please please please please please, please please please please please please please please, please please please please please please please please, please please please please please please please please, please {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>EasyJournal</title> {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> </button> <a class="navbar-brand" href="{% url 'learning_logs:index' %}"> EasyJournal</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'blog:home' %}"> <span class="glyphicon glyphicon-home"></span> Home</a></li> <li> <a href="{% url 'blog:new_post' %}"> <span class="glyphicon glyphicon-pencil"></span> Create Post</a></li> <li><a href="{% url 'blog:my_post' %}"> <span class="glyphicon glyphicon-list-alt"></span> My Posts</a></li> <li> <a href="{% url 'learning_logs:topics' %}"> <span class="glyphicon glyphicon-file"></span> My Notes</a></li> <li><a href="{% url 'diary:diaries' %}" > <span class="glyphicon glyphicon-list"></span> My Diary</a></li> <li> <a href="{% url 'idea:ideas' %}"> <span class="glyphicon … -
If one form filled, the others is not required in Django
I have this model: from django.db import models class Summarizer(models.Model): url = models.URLField() text = models.TextField() and this form: class SummarizerForm(forms.ModelForm): class Meta: model = Summarizer fields = ['url', 'text'] labels = {'url':'', 'text':''} widgets = { 'url': Textarea(attrs={'cols': 80, 'rows': 1}), 'text': Textarea(attrs={'cols': 100, 'rows': 12}), } I want to make it if the url is filled, the text is not required. Vice versa. I've tried this and it requires both of them to be filled: class Summarizer(models.Model): url = models.URLField(blank=True) text = models.TextField(blank=True) if url: url = models.URLField() elif text: text = models.TextField() It should only require one of the forms, not both. What can I do? Thanks in advance -
Django - how to get all the users in team when using a costumised user model
I am new to django and have a question: I created a CustomUser model within a users app. I tried from users.models import CustomUser, Team team1= Team.objects.first() users_team1= team1.user.objects.all() and it doesnt get me the list of users in this Team class CustomUser(AbstractUser): bio= models.CharField(max_length=300, null= True, blank=True) class Team (models.Model): title = models.CharField(max_length=200) user= models.ManyToManyField(get_user_model()) date_created= models.DateTimeField(auto_now_add=True, blank=True, null=True) date_updated= models.DateTimeField(auto_now=True,blank=True, null=True ) def __str__(self): return self.title def get_absolute_url(self): # new return reverse('team_detail', args=[str(self.pk)]) I want created a HTML page {% extends '_base.html' %} {% block title %}{{ object.title }}{% endblock title %} {% block content %} <div class="team-detail"> <h2><a href="">{{ team.title }}</a></h2> <p>Team tile : {{ team.title }}</p> <p>user: {{ team.user }}</p> </div> {% endblock content %} how can i show all the users in a specific Team? Thanks in advance. -
Django page not found, help would be appreciated
I was taking a youtube tutorial on making a basic website using django and I got this error when coding: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: app/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my code: For urls.py/mysite: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('app/', include('myapp.urls')), path('admin/', admin.site.urls), ] For views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello, world!") For urls.py/myapp: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Any help would be appreciated. -
Possible to run 10,000+ multiprocess, all running together in Python & Django
I have got a specific problem I need to run 10,000+ multiprocess and all should be running together as they communicate in run time. I tired Django with celery using the prefork method which limits me to use as per my CPU capacity that is 10-15 processes. Current Server Resource - 8 core with 8 GB RAM (Digital Ocean Droplet) I need guidance or direction on how to resolve this issue. Should I use any other technology like Redis Queue or merge any other technology with Celery. Thanks for your help. -
Jinja2 for PyCharm?
I am new to both python and django. I am following a tutorial where the teacher is using Jinja in Visual Studio. I tried to download it from plugins in PyCharm, but there is nothing called Jinja. Is there any way I can use Jinja in PyCharm? Is there any alternative? Thanks -
Celery sqs tries to connect to amqp: Cannot connect to amqp://guest:**@127.0.0.1:5672//
I want to use Celery with SQS. But, connection error is amqp://guest:**@127.0.0.1:5672// . What's wrong is my setting? celery[sqs] ==4.4.7 kombu ==4.6.11 billiard ==3.6.3.0 broker_url = 'sqs://%s:%s@' % (safequote(AWS_ACCESS_KEY_ID), safequote(AWS_SECRET_ACCESS_KEY)) broker_transport_options = { 'region': 'ap-northeast-1', 'visibility_timeout': 3600, 'polling_interval': 1, 'queue_name_prefix': 'pre-', } result_backend = None accept_content = ['pickle'] beat_schedule = { "add": { "task": "tests.tasks.insert_task", "schedule": crontab(minute=0, hour='*', day_of_week='0,5,6'), }, } -
Python Django Filefield 404
Got a interesting issue outside my capabilities. Have searched the whole interwebz but could not find anything suitable. Here we go. The issue: The GET image file returns 404. In this particular case the file is uploaded using the model filefield. The call made from the template differs from the physical location of the file which, well a 404. Due to the dynamic pattern of the app I am confused how to approach this. In short, I need some help ?!?! Python Django latest versions, good start. Project: MySite App: Main Model: class Product_images(models.Model): product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True) image = models.FileField(upload_to='productimages/', null=True) name = models.CharField(max_length=50,unique=False,blank=True) class Meta: verbose_name = 'Product Image' verbose_name_plural = 'Product Images' def __str__(self): return '{} - {} - {}'.format(self.pk, self.product, self.name) View: def products_view(request, *args, **kwargs): return render(request, "products.html") products.html: Includes tag {{ product_section }} context_processors.py: Lots of loops and coding here, the important bit is. html_value += u'<img class="d-block w-100" onclick="openModal();currentSlide(1)" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.image,productimages_obj.name) The productimages_obj is the queryset the html value is used within the products.html template url.py: urlpatterns = [ path('home/', views.home_view, name='home'), path('products/someproduct', views.products_view, name='some product'), ] Outcome: http://127.0.0.1:8000/products/someproduct [12/Sep/2020 01:02:37] "GET /products/productimages/Finance1.png HTTP/1.1" 404 3228 I understand why … -
How to change another field when i actualize one in ManytoMany relationship?
i have two models and i need to know how to change two values when i change one of this class Universidad(models.Model): nombre = models.CharField(max_length=64) carreras = models.ManyToManyField('Carrera', related_name="universidadesSelf", blank=True) class Carrera(models.Model): titulo = models.CharField(max_length=64) universidades = models.ManyToManyField('Universidad', related_name="carrerasSelf") The Universidad class can have many Carrera, and the Carrera class can be in differents Universidad, so what i want to know is if a actualize one Carrera in Universidad, it changes in Carrera too, where the Universidad value is. -
Django databases: problems with the test database
I am learning about Django testing. I wrote a simple App with a simple model and would like to run tests to check the validity of a model method, but I get an error message when I run the test: here's models.py from django.db import models class Trip(models.Model): origin = models.CharField(max_length=20) destination = models.CharField(max_length=20) def __str__(self): return self.origin def is_valid(self): return self.origin != self.destination Here's test.py from django.test import TestCase from .models import Trip # Create your tests here. class TripModelTests(TestCase): def test_trip(self): a = Trip.objects.create(origin='a', destination='a') self.assertIs(a.is_valid(), True) here is settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'd57r9kcrhthdc7', 'USER': 'sdqxaruartlvrd', 'PASSWORD': 'e7b8f85611596ed125fe3ed4ea590f821f65e317c17ee7871be75b8130d72378', 'HOST': 'ec2-3-214-46-194.compute-1.amazonaws.com', 'PORT': '5432', 'TEST': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } } and here is the error message i get when I run python manage.py test transport Creating test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\test.py", line 23, in run_from_argv super().run_from_argv(argv) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\fabia\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File …