Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Django in root and phpMyAdmin in apach2
I want to serve my Django app from mysite.com and PHPMyAdmin from mysite.cm/phpmyadmin. So I have tried some methods to achieve so with modwsgi. It's / directory seems to take precedence over all directories. How can I set up my apache config to get expected output? I don't want to run my project in a subdirectory, instead, PHPMyAdmin should be in a subdirectory. Here is my apache config. ... <Directory /home/tareq/djproject/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djapp python-path=/home/tareq/djproject python-home=/home/tareq/djproject/dj_env WSGIProcessGroup djapp WSGIScriptAlias / /home/tareq/djproject/config/wsgi.py Alias /phphmyadmin /var/www/html/phpmyadmin <Directory /var/www/html/phpmyadmin> Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all </Directory> </VirtualHost> I tried placing WSGIScriptAlias top and bottom, no change. But everything works just fine if I use WSGIScriptAlias anything other than /. This settings throws error 404 by django app when I visit mysite.com/phpmyadmin -
clearing and seeding database from endpoint in django
I'm trying to set up a rest API that can be cleared and then have the data in my postgres db re-seeded via an endpoint. I'm doing this with Django with json data in a fixtures file, executing a series of functions in my views. This has worked great so far, but now I'm trying to add data with foreign key fields. models.py: class Profile(models.Model): name = models.CharField(max_length = 100) profile_name = models.CharField(max_length = 100) email = models.CharField(max_length = 100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length = 250) body = models.TextField(max_length = 4000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) def __str__(self): return self.title class Comment(models.Model): title = models.CharField(max_length = 200) body = models.TextField(max_length = 1000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) post = models.ForeignKey(Post, on_delete = models.CASCADE) def __str__(self): return self.title in views.py def seed(request): Profile.objects.all().delete() reset(Profile) for profile in all_profiles: add_profile(profile) Post.objects.all().delete() reset(Post) for post in all_posts: add_post(post) Comment.objects.all().delete() reset(Comment) for comment in all_comments: add_comment(comment) return HttpResponse('database cleared and seeded') def add_profile(new_profile): profile_instance = Profile.objects.create(**new_profile) profile_instance.save() def add_post(new_post): post_instance = Post.objects.create(**new_post) post_instance.save() def add_comment(new_comment): comment_instance = Comment.objects.create(**new_comment) comment_instance.save() def reset(table): sequence_sql = connection.ops.sequence_reset_sql(no_style(), [table]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) some example seed … -
Getting the currently logged in user from django view form
This is my model. class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20) total = models.DecimalField(max_digits=7, decimal_places=2, default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) def __str__(self): return self.name And this is my model form: class ProjectForm(ModelForm): required_css_class = 'required' class Meta: model = Project fields = '__all__' def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['user'].initial = self.user and then here's my view: def add_project(request): submitted = False if request.method == "POST": form = ProjectForm(data=request.POST, user=request.user) if form.is_valid(): form.save() return HttpResponseRedirect('/add_project/?submitted=True') else: form = ProjectForm() if 'submitted' in request.GET: submitted = True return render(request, 'add_project.html', {'form': form, 'submitted': submitted} ) I am trying to get the "user" filled by getting the logged in user but when loading the url "add_project/" where the form should load and let me submit I get an error that traces back to KeyError at /add_project/ 'user' Request Method: GET Request URL: http://127.0.0.1:8000/add_project/ Django Version: 3.1.2 Exception Type: KeyError Exception Value: 'user' Exception Location: /ArtistShop/homepage/forms.py, line 12, in init Python Executable: /usr/local/bin/python Python Version: 3.8.6 Python Path: ['/ArtistShop', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages'] Server time: Sat, 30 Jan 2021 19:16:12 … -
I need to hash a PIN in Django that will always be the same
I am making a Django project. I want users to be able to login by just entering a PIN. I need to store a PIN for users. I want the PIN to be hashed. The PIN (and therefore its hash) be unique. I need to know how to change a user-entered integer and hash it to save in the database. Then I need to know how to compare it when a user enters the PIN. -
Wagtail/Django: Is it possible to populate a given admin fields options out of the results of an API?
I'm working on a Django project and specifically a Wagtail project. I want to switch this code that I have below, to contain a prepopulated admin field, which will be populated by an API response. Here is the code I am currently using: """Flexible page.""" from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) bannerImage = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) audioUrl = models.URLField() content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ImageChooserPanel('bannerImage'), FieldPanel('audioUrl'), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" This would enable me to create a standard Wagtail URL field and I could set up a URL to an MP3 file. What I would like to do instead is pre-populate a drop-down menu out of an API response like the following: { "id":"83ee98f6-3207-4130-9508-8f4d15ed7d5c", "title":"some random description", "description":"some random description.", "audio":"https://somerandomurl.mp3", "slug":"some random description", "draft":false }, { "id":"83ee98f6-3207-4130-9508-8f4d15ed7d5c2", "title":"some random description2", "description":"some random description2.", "audio":"https://somerandomurl2.mp3", "slug":"some random description2", "draft":false2 }, I'm wondering how I would go … -
Django: send emails in local language
I'm trying to send a language in local language. Let's say, a user fills up the registration form on the French website, I would like to send him an email in French. I have tried with translation.override but it didn't work. What's the correct way of sending localized emails? subject = _('Please Activate Your Account') email_context = {'domain': current_site.domain, 'uid': reset_uid, 'token': token,} html_body = render_to_string('email/activation-request-email.html', email_context) text_body = render_to_string('email/activation-request-email.txt', email_context) send_mail(subject=subject, message=text_body, from_email='no-reply@example.com', recipient_list=[user.email], html_message=html_body) -
not a valid UUID , how to catch wrong UUID?
I am having a validation error when I set a random string in my url as token. How can i catch this validation error? For example: when accesing: https://www.example.com/stream/8e258b27-c787-49ef-9539-11461b251ffad The error is ValidationError at /stream/8e258b27-c787-49ef-9539-11461b251ffad ['“8e258b27-c787-49ef-9539-11461b251ffad” is not a valid UUID.'] my code is this: def stream(request, token): user = Creador.objects.filter(stream_token=token).first() if user: return render(request, 'app1/stream.html', { 'token':token, 'user':user }) else: return HttpResponse("Token no existe") any ideas? thanks -
Redirect after comment submission to post
I am trying to redirect my comment form submission to the post details page where all comments should be displayed. How do I pass in the unique id for post that the comment is related to into my URL for redirecting to that post? post_detail.html ... <p><a href="{% url 'comment_new' comment.post.pk %}">Create New Comment</a> ... urls.py ... path('comment_new/', views.CommentCreateView.as_view(), name = 'comment_new'), path('<int:pk>/', views.PostDetailView.as_view(), name = 'post_detail'), ... views.py ... class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'comment_new.html' form_class = CreateCommentForm login_url = 'login' def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) ... model.py ... class Comment(models.Model): post = models.ForeignKey( Post, on_delete = models.CASCADE, related_name = 'comments' ) comment = models.CharField(max_length = 280) author = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('post_detail', args = [str(self.post.id)]) ... -
Django/channel_redis Slow memory leak
I have tried various configurations for channel_redis, and my views.py. Using tracememalloc I found nothing missed by the garbage collection. I used tracememalloc in the websocket connection function. Whether I set a timeout for the connections or not memory still grows. I also use django_prometheus. Currently here is my ASGI.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "panoptes.settings") django.setup() application = get_default_application() Here is my redis settings. CHANNEL_LAYERS = { "default": { # Use InMemoryChannelLayer for testing only # "BACKEND": "channels.layers.InMemoryChannelLayer" "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], "capacity": 1500, "expiry": 60, "group_expiry": 42300, }, } } relevant views.py class NewAlert(View): def post(self, request): raw = request.body.decode("utf-8") data = json.loads(raw) for new_alert in data.get("alerts"): status = new_alert.get("status") new_alert["status"] = { "state": status, } create_or_update_alert(new_alert).save() gc.collect() return HttpResponse() urls.py urlpatterns = [ path("graphql/", csrf_exempt(GraphQLView.as_view(graphiql=True)), name="graphql"), path("alert/webhook/", csrf_exempt(views.NewAlert.as_view())), path("check", csrf_exempt(views.check_login), name="check_login"), path( "favicon.ico", RedirectView.as_view(url=staticfiles_storage.url("panoptes.ico")) ), path("", views.index, name="index"), path("post_login", csrf_exempt(views.post_login), name="post_login"), path("post_logout", csrf_exempt(views.post_logout), name="post_logout"), ] I am using react.js as a frontend. Tracememalloc only found "" as the largest blocks. https://docs.python.org/3/library/tracemalloc.html#get-the-traceback-of-a-memory-block I built part of the project, but I am taking over the websockets from a former coworker who had never solved the problem. It is a very slow growth. We never have more than 10 connections and … -
Django View: Avoid waiting for post_signal to improve request response time
It seems that before a response is sent back for particular request to an endpoint. All related signals must complete before request is complete. I have a function that takes quite a bit of time to process. How can I delay the function to be called AFTER the response has been sent? @receiver(post_save, sender=User) def user_post_save_func(sender, instance, created, **kwargs): update_user_related_objects(instance) -
Creating a views function that will find the single desired instance from the database and send it to the template using Django
I am working on a library web app using Django. Right now a user can create as many libraries as they want and add books to the created libraries. The user is able to choose any library and view the contents of that table on a template. I would like the user to be able to jump to another template that has the full details of any book in the database. I am passing through a request with the pk and getting errors. Do I need to add anything about the library object in here? my views function currently: def single_detail(request, pk): book_details = get_object_or_404(AddBook, pk=pk) context = {'book_details': book_details} return render(request, 'library/details.html', context) AddBook is the name of the class that determines the attributes of the entry and i didn't manually add a primary key to it since with Django you don't have to. The user is already on the page where only the contents of the chosen library are displayed. I know my URL path needs to be this, but the whole app breaks when i have int:pk inside the details path. urlpatterns = [ path('', views.lib_home, name='homeLib'), path('create/', views.create_library, name='create'), path('add/', views.add_book, name='add'), path('<int:pk>/library/', views.your_library, name='libraryList'), path('details/<int:pk>', … -
Got stuck on a bug in posgresql using django, when i fix the bug and the re migrate nothing happens
i did mistake which is setting a True as a default value in a ArrayField(models.CharField(...)) which should be in characters only (the bug isn't the import part) so anyway when i fixed it then tried to migrate it got stuck on that bug and didn't reload, i even changed it to another database and nothing happened, it happened to me the last time and i just created another project i am tired of that, is there any solution to fix this? -
Django ModelForm and Objects id
I'm building forms with forms.ModelForm and I need to pass the Client id in this form. Models.py class DocumentTypeForm(forms.ModelForm): client = forms.IntegerField(widget=forms.HiddenInput(), initial=Client.pk) class Meta: model = DocumentType fields = [ 'code', 'name', 'client', ] Models.py class DocumentType(models.Model): code = models.CharField(max_length=10, verbose_name=_("Code")) name = models.TextField(verbose_name=_("Name")) client = models.ForeignKey( "Client", on_delete=models.CASCADE) That is returning AttributeError 'DocumentTypeView' object has no attribute 'object_list' -
Custom permissions in Django REST API don't raise any error even when print() function returns False in the terminal
I wrote a permission: class IsParticipant(permissions.BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): if isinstance(obj, Message): return request.user in obj.chat.chat_participants.all() elif .... return False I checked, conditions work correctly (now I need just the first if condition), the program enters the if condition, and returns False or True (I've written print() function, so it showed in terminal that program returns False of True depending on values). But it doesn't change anything, even if returns False, it doesn't forbid anything for user. It even doesn't raise any default error. Here is the view class (although I don't think it is necessary here): class WriteMessageCreateAPIView(generics.CreateAPIView): permission_classes = [IsAuthenticated, IsParticipant] serializer_class = WriteMessageSerializer #the model is named as 'Message' def perform_create(self, serializer): serializer.validated_data['author'] = self.request.user serializer.validated_data['chat_id'] = self.kwargs['pk'] return super(WriteMessageCreateAPIView, self).perform_create(serializer) So the questions are: Why the permission class doesn't do anything? How can I fix this issue? -
Can I delete old versioned staticfiles?
I am using Django with whitenoise and django-compression-middleware. When I do changes and run manage.py collectstatic I get new normal and compressed static files with new versions. After some changes the folder size gets too much. But when I delete all before running collectstatic I get the same version again so browser cache doesn't change and it runs the old code. How can I renew the cache with versioning by using collectstatic and also have less files in static folder? -
Is there a way to build dynamic models in Django?
I am currently building a project in Django, and I was wondering if is there a way to build a dynamic model. I want to create a model with a group of user, and the table structure is the following: Group Name User 1 User 2 User 3 User ... But I want to make users dynamic, I mean, if the group has only 2 users the model will only put 2 users fields in the model, and if the group has 10 user the model put 10 users fields in the model. Does someone know a way to do this? Is it even possible? I hope I made it clear enough for you guys! If you have any questions please post in the comments and I will answer as fast as I can. Sorry for the english tho! Not my main language. -
Django runserver command failed
I've been learning Python for a couple of months and a couple days ago i decided to learn one of Web frameworks. I found some tutorials on Django and it was looking really cool until i tried to use "runserver" command. As you can see i used the basic line "python -m django runserver manage.py" and got a lot of calls. I've just installed Django and i wasn't changing anything in it's scripts. I only started by creating a new project that worked perfectly with "python -m django startproject djangoLearn". Do you have any thoughts on how can i fix this problem? This problem prevents me from further learning beacuse i can't see my project. Thanks in advance. Hope y'all have a great day. Calls that i get while trying to run server: D:\Projects\djangoLearn>python -m django runserver manage.py Traceback (most recent call last): File "C:\Program Files\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Program Files\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\__main__.py", line 9, in <module> management.execute_from_command_line() File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\norml\AppData\Roaming\Python\Python39\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) … -
I wanna set time(second countdown in html page in Django. How can I do it?
I wanna create a Django project. Where I set some quiz's and set countdown, like (30sec, 3 min). User will need to solve during that end of the countdown. -
Multiple modals in template ruins layout and enters dark screen on post
I am using django and I am making update modals for each object in a for loop in my html. I am also making a new script for each update modal. The problem is that the layout of the table is scrambled. And everytime I update a object I get a dark screen like when opening a modal just without a modal. Can anyone help? Here is my html: <div id="authors-candidates-div"> <table id="authors-table" class="table"> <thead> <tr> <th class="text-center" scope="col">ID</th> <th class="text-center" scope="col">Name</th> <th class="text-center" scope="col">Name original language</th> <th class="text-center" scope="col">Extra info</th> <th class="text-center" scope="col">Update/ Link</th> </tr> </thead> <tbody> {% for author in authors.all %} <tr> <th class="text-center" scope="row">{{ author.pk }}</th> <td class="text-center">{{ author.name }}</td> <td class="text-center">{{ author.name_original_language }}</td> <td class="text-center">{{ author.extra_info }}</td> <td class="text-center"> <!-- Update author buttons --> <button type="button" id='init-btn{{ author.pk }}' class="btn btn-primary btn-danger" data-toggle="modal" data-target="#UpdateAuthorModal{{ author.pk }}" data-form-url="{% url 'author-proces' publication.pk author.pk %}"> <span class="fa fa-pencil"></span> </button> <!-- Modal --> <div id="UpdateAuthorModal{{ author.pk }}" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title col-md-10">Update Author</h5> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <div class="form-group"> <label for="id_name_t">Name</label> <input type="text" name="name" maxlength="100" value="{{ author.name }}" class="form-control name" id="id_name{{ author.pk }}"> <div class=""> </div> … -
Is there a way to define in Mypy a Django model reversed field?
Suppose you have the following simple models: class User(models.Model): name = models.CharField(max_length=10) class Article(models.Model): title = models.CharField(max_length=50) user = models.ForeignKey(User, related_name='articles') I'll have an auto generated field called articles in my User model. Now, it's not being inferred by Mypy of PyCharm so the IDE warns me about non existing field. Is there a way to define in Mypy that field? -
i am unable to change profile pic in django
views.pyI created a profile form in models.py for and form.py to update it but all thing got updated expect profile picture models.py -
Django, CSS is loading, however images and js return a 404
I am creating a Django website and have created a login pages for the website. When I run this on the development server the CSS for the page loads but the images and JavaScript are returning a 404 error. but they are in the same assets folder. Folder Structure: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets')] Login.html: <div class="h-center"> <img class="logo" src="{% static 'assets/base/img/logo/logo.jpg' %}"> </div> I don't understand why it is only loading the CSS files. -
Django - How to use Pagination with filter function?
I am trying to use Pagination with the Django Filter function, But I am getting this error. http://127.0.0.1:8000/product_search/?page=2&search=e Cannot use None as a query value product = Product.objects.filter(productName__contains=name) Here is The view.py function def searchProduct(request): name = request.POST.get("search", None) try: product = Product.objects.filter(productName__contains=name) paginator = Paginator(product, 2) page = request.GET.get('page') page_product = paginator.get_page(page) if page_product: context = { 'searchResults': page_product, 'name': name } return render(request, "Amazon/searchResult.html", context) else: return render(request, "Amazon/searchResult.html", {'message': "No Product Found"}) except Product.DoesNotExist: return HttpResponse("Page Not Found") Here is HTML/Jinja code <nav aria-label="..."> {% if searchResults.has_other_pages %} <ul class="pagination justify-content-center"> {% if searchResults.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.previous_page.number }}&search={{ name }}" tabindex="-1"> Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" tabindex="-1">Previous</a> </li> {% endif %} {% for i in searchResults.paginator.page_range %} {% if product.number == i %} <li class="page-item active"> <a class="page-link" href="#">{{ i }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="?page={{ i }}&search={{ name }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if searchResults.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ searchResults.next_page_number }}&search={{ name }}">Next</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">Next</a> </li> {% endif %} </ul> {% endif %} </nav> I have a rough … -
How to use a list field in django
lets say we have model which is an exam (am making an educational website), and the exam has a list of people who have done it, the question is what filed type should i use? class Exam(models.Model): difficulty = models.CharField(max_length=10, choices=[('ez','easy'),('hrd', 'hard')]) module = models.CharField(max_length=10, choices=[('math','math'),('physics', 'physics')]) completed_by = ???????????? (lets assume that there an other module callded user and i want this field to be a list of that users) ` -
How to design database for online examination
I'm working on a project using Django, MySQL in which I need to store the information about the Students and information about the Courses, Subjects, Questions, Result and etc. My goal is to give the services to the students for giving online examinations to know how good they are at the particular Subject just like the JEE, IEEE. I have created these tables in my project : 1. Student_tbl : stuId(PK), name, email, password, mobile, course 2. Course_tbl : courseId(PK), Course_name 3. Subject_tbl : subId(PK), class_id(FK), Subject_name 4. Topic_tbl : topicId(PK), class_id(FK), subject_id(FK), Topic_name 5. Question_tbl : quesId(PK), subjectId(FK), topicId(FK), Question_text, Answer_text, Marks(per question i.e. 2marks for 1 question etc.) 6. Result_tbl : id(PK), studentId(FK), subjectId(FK), Total_Marks My Requirement is: Register the students in the Student_tbl Show them the test paper just like JEE or any other online exams Once they complete the test then based on the performance they can get result from the Result_tbl we're storing the info. Please help me out to achieve this features and also suggest me what the extra column with Foreign Keys or tables should be there , if I have committed any mistakes