Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model_to_dict stack overflow crash
In my app, I use a common Base model for all my models. I'v encountered a behaviour I can't explain with the Campus and Hall models: class Base(models.Model): id: int = models.AutoField(primary_key=True, editable=False) class Meta: abstract = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._initial = self.as_dict ... @property def as_dict(self) -> dict: fields = [field.name for field in self._meta.fields] res = model_to_dict(self, fields=fields) return res ... class Campus(Base): name: str = models.CharField(max_length=100) class Meta: verbose_name_plural = "campuses" def __str__(self): return self.name class Hall(Base): name: str = models.CharField(max_length=100) campus: Campus = models.ForeignKey(Campus, on_delete=models.SET_NULL, null=True) def save(self, *args, **kwargs): if self.campus is not None and isinstance(self.campus, str): self.campus = Campus.objects.get_or_create(name=self.campus)[0] super().save(*args, **kwargs) def __str__(self): return f"{self.name}{f' ({self.campus})' if self.campus else ''}" On the admin console, when I try to delete a certain Campus instance, the server crashes. This is a very small part of the (very long) trace: Fatal Python error: Cannot recover from stack overflow. ... Current thread 0x00000bdc (most recent call first): ... File "P:\Python\Coursist\academic_helper\models\base.py", line 142 in as_dict File "P:\Python\Coursist\academic_helper\models\base.py", line 98 in __init__ File "C:\Venvs\Coursist\lib\site-packages\django\db\models\base.py", line 512 in from_db File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 75 in __iter__ File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 1261 in _fetch_all File "C:\Venvs\Coursist\lib\site-packages\django\db\models\query.py", line 258 in __len__ … -
At first time If I enter wrong enroll_no error display, but if i enter second time after entering right enroll_no do error
models.py contains code: class Entexaminfo(models.Model): entexamses = ( ("June Session", "June Session"), ("December Session", "December Session"), ) approve_choice = ( ("p", "Pending"), ("a", "Accepted"), ("r", "Rejected"), ) ename = models.CharField(max_length=16, choices=entexamses) enrollno = models.OneToOneField(Student, on_delete=models.CASCADE) #programs = models.ManyToManyField(Programs, related_name='proNames', default=0) program = models.ManyToManyField(Programs, default=0) center = models.ForeignKey(Excenter, on_delete=models.CASCADE) remarks = models.CharField(validators=[max_len_check], max_length=256, default="-") #status = models.BooleanField() status = models.CharField(max_length=1, choices=approve_choice, default="p") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.ename def get_absolute_url(self): return reverse('show', kwargs={'pk': self.pk}) #For Table Name in DBMS class Meta: db_table = 'entexaminfo' #For Database table name verbose_name = "intexaminfo" #For Database table singular name verbose_name_plural = "intexaminfos" #For Database table plural name ordering = ['created_at'] #For table data sorting views.py contains: def hall_ticket(request): if request.user.is_authenticated: try: query = request.GET['enrollno'] except MultiValueDictKeyError: enrollno = False #query = request.GET['enrollno'] entedetail = Student.objects.filter(enrollNo=query) for obj in entedetail: global id #To avoid 'local variable 'id' referenced before assignment' error message id = obj.id ent1 = Entexaminfo.objects.filter(enrollno=id) esch = Ex_schedule.objects.filter(programs=2) params = {'entedetails': entedetail, 'ent1': ent1, 'query': query, 'esch': esch, 'title': 'Entrance Exam Hall Ticket'} return render(request, 'hall_ticket.html', params) else: messages.info(request, 'You need to Login first.') return redirect('/user/logout') urls.py … -
best place to host an e-commerce website other than heroku [closed]
which is the best place to host an e-commerce website other than heroku -
Django cannot find all my files in static files
I'm totally fresh to django. I downloaded a template to presents a well structured web page. But after I put all the template's file in to static dir then just didn't show any image or run any js css files. Here is my dir: Here is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] # URL prefix for static files STATIC_URL = '/static/' # Absolute path to the directory in which static files should be collected STATIC_ROOT = os.path.join(BASE_DIR, 'root') # Additional locations for static files (optional) STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),] This is what I got at terminal: [31/May/2020 07:55:02] "GET /static/assets/vendor/aos/aos.css HTTP/1.1" 404 1699 [31/May/2020 07:55:02] "GET /static/assets/vendor/owl.carousel/assets/owl.carousel.min.css HTTP/1.1" 404 1786 [31/May/2020 07:55:02] "GET /static/assets/vendor/icofont/icofont.min.css HTTP/1.1" 404 1735 [31/May/2020 07:55:02] "GET /static/assets/vendor/boxicons/css/boxicons.min.css HTTP/1.1" 404 1753 [31/May/2020 07:55:02] "GET /static/assets/vendor/venobox/venobox.css HTTP/1.1" 404 1723 [31/May/2020 07:55:02] "GET /static/assets/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 1759 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery/jquery.min.js HTTP/1.1" 404 1726 [31/May/2020 07:55:03] "GET /static/assets/css/style.css HTTP/1.1" 404 1684 [31/May/2020 07:55:03] "GET /static/assets/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 1774 [31/May/2020 07:55:03] "GET /static/assets/vendor/jquery.easing/jquery.easing.min.js HTTP/1.1" 404 1768 [31/May/2020 07:55:03] "GET /static/assets/vendor/php-email-form/validate.js HTTP/1.1" 404 1744 [31/May/2020 07:55:03] "GET /static/assets/vendor/waypoints/jquery.waypoints.min.js HTTP/1.1" 404 1765 [31/May/2020 07:55:03] "GET /static/assets/vendor/counterup/counterup.min.js HTTP/1.1" 404 1744 [31/May/2020 07:55:04] "GET /static/assets/img/portfolio/portfolio-9.jpg HTTP/1.1" 404 1732 [31/May/2020 07:55:04] … -
TypeError: UserCreateForm() got an unexpected keyword argument 'initial'
I am new to django and I am developing a social media site following the course and I am facing this weird error when I try to open signup page from the site, which after a lot of search and experiments wasn't able to get away with.Thus, I came here so if anyone could help me. My forms.py file where i think the actual culprit is from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm def UserCreateForm(UserCreationForm): class Meta: fields = ['username', 'email', 'password1', 'password2'] model = get_user_model() def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Username' self.fields['email'].label = 'Email Address' views.py file from django.shortcuts import render from django.views.generic import CreateView from django.urls import reverse_lazy from . import forms # Create your views here. class SignUpView(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy('login') template_name = 'accounts/signup.html' urls.py file in the application directory i.e. accounts/urls.py from django.urls import re_path from django.contrib.auth.views import LoginView, LogoutView from . import views #code here urlpatterns = [ re_path(r'^login/$', LoginView.as_view(template_name='signin.html'), name='login'), re_path(r'^logout/$', LogoutView.as_view(), name='logout'), re_path(r'^signup/$', views.SignUpView.as_view(), name='signup'), ] full log of error I am facing File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_ data kwargs['form'] = self.get_form() File "C:\Users\dell\Anaconda3\envs\pyEnv\lib\site-packages\django\views\generic\edit.py", line 33, … -
How can i create a dynamic dropdown form using jquery
i am working on a Django project and i am trying to implement a dropdown form on button click. I have a dropdown form when a button is clicked and each form has its own button, the problem is that when i clicked on a particular form button, all other forms dropdown as well. I want only the particular form to dropdown while the others do not. I think this has to do with passing the id of the form to each button clicked. This is what i tried. Template: {% for comment in all_comments %} <ul> <li class="float-right"> <!--Dropdown--> <div class="dropdown dropdown-commentdeleteedit"> <a data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-ellipsis-h grey-text"></i> </a> <!-- Menu --> <div class="dropdown-menu font-small z-depth-1"> <a class="dropdown-item material-tooltip-email editform-dropdown" data-toggle="tooltip" data-placement="top" title="Edit"> <img src="{{ '/static/' }}images/edit24px.png" width="18" height="18"></a> </div> </div> <!--Dropdown--> </li> {% endif %} <h6 class="comment editcomment-text ml-5"> {{ comment.comment_post }} </h6> <!-- DROPDOWN EDIT COMMENT FORM --> <form method="POST" enctype="multipart/form-data" class="ajaxcomment-editform editcommentform editcomment-form mb-4" id="" action="{% url 'site:comment_update' post.id comment.id %}"> {% csrf_token %} <textarea name="comment_post" cols="20" rows="5" required="" id="id_comment_post{{ comment.id }}">{{ comment.comment_post }}</textarea> <button type="submit" class="btn btn-sm waves-effect z-depth-1">Save</button> </form> </ul> {% endif %} Jquery: <script type="text/javascript"> //HIDE AND SHOW COMMENT EDIT FORM … -
Getting Internal Server Error when calling view view for dependent dropdown
I am getting data In first dropdown(countries) and second dropdown is dependent on countries dropdown. So I am select country then make an ajax call for language then it give me error "Internal Server Error: /language/" while If call this in countries then it works it means data is available in models and work fine. I am learner urlpatterns = [ path('admin/', admin.site.urls), path("", views.home, name="home"), path("login/", views.login_user, name="login"), path("post/", views.post, name="post"), path("language/", views.language, name="language"), path("logout/", views.logout_request, name="logout"), ] @login_required(login_url='/login/') def post(request): if not request.user.is_authenticated: return redirect('/login/') countries = Countries.objects.all() print(countries) context = {'countries': countries} return render(request, 'post.html', context) def language(request): print("call language") countryId = request.POST.get('country_id') print('country id: ' + countryId) languages = Languages.objects.filter(country_id=countryId) print("obj "+languages) context = {'languages': languages} return render(request, 'post.html', context) <script type="text/javascript"> function getSelectedCountry() { d = document.getElementById("countries").value; <!--alert(d);--> var token = '{{csrf_token}}'; $.ajax({ headers: { "X-CSRFToken": token }, type: 'POST', url: "{% url 'language' %}", data: {"country_id": d}, success : function(json) { $("#id_city").html(data); console.log("requested access complete"); } }) } </script> -
Unable to connect to server: FATAL: password authentication failed for user "xxxx" FATAL: password authentication failed for user "xxxx"
I'm building a Django app and I'm trying to create a connection from AWS. The password is right and the hostname/address link is the but it says "Unable to connect to server: FATAL: password authentication failed for user 'xxxx'" Here's a screenshot of the error: https://prnt.sc/sqziuq Other screenshots for another details of the connection: https://prnt.sc/sqzm9z https://prnt.sc/sqzlx7 -
Correctly export column headers from Django to csv
New to Django and python as well. Issue that I am having while maintaining a Django app is when exporting records from django, one of the field names is showing up as get_mobile instead of mobile. code for the get_mobile function is def get_mobile(self): if self.mobile: return str(' '.join([self.mobile[:4], self.mobile[4:7], self.mobile[7:]])) else: return self.mobile get_mobile.short_description = 'Mobile' code for writing the header data is # Write header. header_data = {} for name in headers: if hasattr(self, name) \ and hasattr(getattr(self, name), 'short_description'): header_data[name] = getattr( getattr(self, name), 'short_description') else: field = None try: field = self.model._meta.get_field(name) except FieldDoesNotExist: pass if field and field.verbose_name: header_data[name] = field.verbose_name else: header_data[name] = name header_data[name] = header_data[name].title() writer.writerow(header_data) I kind of have a general idea of where the issue lies - the header is using the function name instead of the short_description. Being new, I am kind of stuck at getting my head around the header code itself. Would greatly appreciate if someone could help me understand the header code please and explain why it is currently not working as expected - my understanding is it should be using the short_description for mobile instead of function name get_mobile when exporting the records. TIA -
How to diplay number of blog posted per category in Django
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage. models.py: class Category(models.Model): CATEGORY = ( ("Un-categorized", "Un-categorized"), ("Machine Learning", "Machine Learning"), ("Data Science", "Data Science"), ("Programming", "Programming"), ("Latest Trends", "Latest Trends") ) category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True) def __str__(self): return self.category class Post(models.Model): title = models.CharField(max_length=20) # title of the post content = models.TextField() # content of the post date_posted = models.DateTimeField(auto_now_add=True) # when the post is created date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved. author = models.ForeignKey(User, on_delete=models.CASCADE) # Referring the django's inbuilt User model. category = models.ForeignKey(Category, on_delete=models.CASCADE) # one post can have only one category whereas under one category there can be multiple post. img = models.ImageField(default='default.jpg', upload_to='post') # tag = to store important tags related to the post def __str__(self): return self.title views.py : def home(request): # Home page of the website. post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order. categories = Category.objects.all() '''categories_count = [] i = 1 for item in categories.count(): categories_count[item] = Categories.objects.filter(id=i).count() i += 1 ''' context = { 'posts':post, # 'count' : categories_count, 'categories': … -
Different pieces of web development
I would like to start learning web development for an e-commerce website that includes a chat option. I have been daunted by the new terms that I no longer know what I need to learn. So I know there is backend and frontend, but where do things like django, rest API, ajax, apache, msquery, vue and other stuff fall into the puzzle. What exactly do I need to know for full-stack development. Could someone walk me through different pieces needed? Thanks!! -
How to add placeholders in or near the input fields in django models
I am trying to build a blog app in Django. The problem is that i am not able to mention any thing near the input field. For example There is an image field and i want mention "Only upload images of size 300px x 250px" near it. Thanks in advance -
Preventing Users From Submitting A Form More Than Once
I have a multi-part form that users can leave mid-way through and come back to at any time. However, users can only submit it once so I want to prevent them from even being able to view any part of it once they have completed the final section. I figured I could either: 1 Have a boolean within the user model (False == havent submitted the form, True == have submitted). 2 Create two user groups, a default group for users who havent completed the form, and another for those who have - which users would be allocated to using a signal triggered when they submit the final form. I could then add checks for these in the template and not display the button if they fail, and add checks to the views to prevent users from accessing the form by typing it directly into the url bar. Which (if either) of these methods is best? Or is there another way more suitable / less hacky / more aligned with Django conventions. Thank you. -
How can I connect a model to a user model in Django?
I've created two different users and I want those users to have access to the same model called user_data. class user_1(Account): first_name=models.CharField() last_name=models.CharField() class user_2(Account): first_name=models.CharField last_name=models.CharField class user_data(models.Model): Data_1=models.IntegerField() Data_2=models.IntegerField() -
i want to create clock on my website can anyone please
here is my website url enter link description here i want to add clock using python using django framework. refer above url, also it shoud be fully functional in deployment of the webapp. kindly refer below snap. kindly help us to create this type of webapp. -
page not found 404 django
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/about/ Using the URLconf defined in Hello.urls, Django tried these URL patterns, in this order: admin/ admin/ [name='home'] service [name='service'] contact [name='contact'] about [name='about'] The current path, about/, didn't match any of these.[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/jZMW9.png -
I'm getting an error while running a code which includes Django's built in DetailView
It is showing that the reverse for the detail has no arguments. I'm not sure what it means. I'm uploading the snippets of my files.This is the picture of my browser with the error displayed Please help me if you find my error. Snippet of the urls.py file in the app(class_app) -
Django DRF: save data in different models in a single request
Lets say I have two models such as class A(models.Model): field_1 = models.CharField(max_length=200, blank=False) field_2 = models.CharField(max_length=200, blank=False) class B(models.Model): field_1 = models.ForeignKey(A, on_delete=models.DO_NOTHING) field_2 = models.CharField(max_length=200, blank=False) I need to write a view and serializer with three fields . Save 2 fields on model A, then the primary key of the saved data on model B along with third field data. Can someone tell me how can I get this done.Iam using django 2.7. -
writing djnago test for __str__ in a model
I want to test my blog app. After running coverage, I have about 91% with 4 missing. The coverage pointed out the lines of code below to be missing. def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title Thus, I decided to write a test for str(self). Here is what the test looks like class PostTest(TestCase): def create_post(self, title="only a test", text="Testing if the created title matches the expected title"): return Post.objects.create(title=title, text=text, created_date=timezone.now()) def test_post_creation(self): w = self.create_post() self.assertTrue(isinstance(w, Post)) self.assertEqual(str(w), w.title) The test fails with the following error. django.db.utils.IntegrityError: null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (1, only a test, Testing if the created title matches the expected title, 2020-05-31 05:31:21.106429+00, null, null, 0, null, 2020-05-31 05:31:21.108428+00, ). This is what the model looks like: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True, blank= True, null=True) updated_on = models.DateTimeField(auto_now= True) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) status = models.IntegerField(choices=STATUS, default=0) photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) class Meta: ordering = ['-published_date'] def publish(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title How do you suggest I write the test to fix this error and improve the coverage? -
Как получить логин пользователя в models или views
Я новичок в Django, не могу сообразить, как через request получить логин пользователя. Делаю сайт типа словаря, и нужно, чтобы каждая добавленная запись помечалась тем, кто ее добавил. Вот мой models.py from django.db import models class EngDict(models.Model): orig_word = models.CharField(max_length=500, null=False,blank=False, verbose_name='Слово') translate = models.CharField(max_length=500,null=False,blank=False, verbose_name="Перевод") remarks = models.TextField(null=True, blank=True, verbose_name="Примечания") published_by = models.CharField(max_length=50, verbose_name="Добавлено", initial=request.user) published_date = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Дата добавления") category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.PROTECT, verbose_name = 'Категория') class Meta: verbose_name = ("Перевод") verbose_name_plural = "Англо-русский словарь" ordering = ['-published_date'] А это views.py from django.shortcuts import render from django.template import loader from .models import EngDict, Category from django.views.generic.edit import CreateView from .forms import EngDictForm from django.urls import reverse_lazy from django.views.generic import TemplateView, ListView, FormView from django.db.models import Q from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login class EngDictCreateView(CreateView): template_name = 'dict/create.html' form_class = EngDictForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['categories'] = Category.objects.all() return context Я так понимаю, мне надо написать функцию типа def user_name(request) , но я не могу сообразить где должна быть эта функция и как она должна выглядеть. Мне по идее надо, чтобы в published_by автоматом подставлялся логин пользователя при создании новой записи. -
middleware updates request.user, but request.user becomes AnonymousUser in view
I wrote a simple JWT middleware to get user from the JWT. The method get_user_from_jwt returns a User object. # app.middlewares.py class JwtMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self.process_request(request) return self.get_response(request) def process_request(self, request): request.user = self.get_user_from_jwt(request.headers) ... In settings: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', 'app.middlewares.JwtMiddleware', ] When I log, request.user is set to the proper User instance at the middleware level, but once at the view, request.user becomes AnonymousUser. I tried switching the orders of the middlewares too. Any ideas how I can update what request.user means inside my views using a middleware? -
Unit Test: How To Mock MEDIA_ROOT But Still Access A File That Is Stored In My Normal MEDIA Folder
Im testing one of my webpages POST functions. if request.method == 'POST' it generates a pdf and attaches it to the user. Every time I ran tests I was generating pdf files which were building up in my MEDIA folder and I had to manually delete them. I decided to look for ways to prevent this from happening and what seems to me to be the best way is to override my MEDIA_ROOT with a tempfile. I am getting the following error message FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Acer\\AppData\\Local\\Temp\\profile_pics\\default.jpg' I am sure this is due to the fact that I must create and log-in a user prior to running the test (I dont want to do this in setup as I must generate different types of users for different tests). Every time a user is created their profile picture is set to profile_pics\\default.jpg'. My understanding is that the mocked MEDIA_ROOT is empty and doesnt contain the default profile pic, so the error is thrown. My question is how can I circumvent this? I found other solutions besides mocking the MEDIA_ROOT folder, but they seem quite hacky and id prefer to do it properly and hopefully learn from … -
Django CRM Need to invite agents by admins using email address
I have an uncompleted django CRM. I have 2 types of users: Agents: can post and view data. Admins: can view and edit data. The thing is i need each admin to invite the users to CRM. i need it to work as following: Admins will have access to a form where they can write down the agents name and email, once theysubmit the form and an email will be sent to the agent. The agent will receive an email with another form to set their username and password so they can login do you have any idea what i should look for or how can i do that? -
Javascript Errors when loading Bootstrap Modal a second and third time that contains a form with drop downs
I'm a complete beginner...please excuse the mess. Only been learning for about a month. The structure is like this. I have a nav.html template I've created for a top level menu across the site. It contains a drop down for creating New entries...and in this case a 'New Job' Job has two special parts. I've used Django-autocomplete-light for finding/creating new customers in the one form. This leverages select2 and some other javascript wizards A google places autocomplete for finding site addresses Everything worked fine as just opening in a fresh page. Then I decided I wanted to put the New Job form in to a modal instead. I'm an idiot. I'm using non-modified bootstrap css and the js for it as well...but pulled them down to be local copies in my static folder. Same goes for jquery and popper. Got it to actually work/pop up fine but then these happened in the background. Grabs from the google chrome console. These are the errors I see when just opening and closing without entering any data. I started learning about the javascript event loop and it hurt my brain...but does this all have something to do with that? This kind of feels … -
How can I define a function in django so that stays active in background?
How can I define a function that stays active in background? For example, I want django to update all of the movies in database using IMDB information. If there are too many movies in database, It can take too long for django to update them. So I want the process of updating to stay active in background and don't stop if I close web browser. 1) How is this possible? 2) Can I add a progress bar to see how many movies are updated so far ?