Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to configure apache-airflow with Django project for use of ORM's
I want to configure apache-airflow with the Django project. But I didn't find any resources that help me to set up this. Basically, I want to use Django Orm for scheduling tasks. -
Auto refresh cache DRF
I cache my rest-api with the rest_framework_extensions like: class UpdatedAtKeyBit(KeyBitBase): def get_data(self, **kwargs): basename = kwargs['view_instance'].basename.lower() key = f'api_updated_at_timestamp_{basename}' value = cache.get(key, None) if not value: value = datetime.datetime.utcnow() cache.set(key, value=value) return force_text(value) class CustomListKeyConstructor(DefaultKeyConstructor): list_sql = ListSqlQueryKeyBit() pagination = PaginationKeyBit() updated_at = UpdatedAtKeyBit() def change_api_updated_at(sender=None, instance=None, *args, **kwargs): cache.set(f'api_updated_at_timestamp_{sender.__name__.lower()}', datetime.datetime.utcnow()) for model in [Address, Order, Permission, User]: post_save.connect(receiver=change_api_updated_at, sender=model) post_delete.connect(receiver=change_api_updated_at, sender=model) this works perfect! I cache the GET-list responses from the Models. Now I would like to automatically refresh those views after a update or a save. So that the following requests are already in the cache. How can i solve this? -
Static files on Django 404 with static_root and static_url both set
I know this question has been answered a lot but I can't seem to work this out. My static files are there, at the location I've told django they are. Debug is set to True, and static_url is set to '/static/' but the static files are 404ing. development(settings).py DEBUG = True logger.info(f"Debug is {DEBUG}") STATIC_URL = "/static/" STATIC_ROOT = "/home/phillyharper/dask/static" logger.info(STATIC_ROOT) Running python manage.py runserver using these settings produces this result: 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:4 - Debug is True 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:47 - Debug is True 2021-05-09 07:17:03.197 | INFO | dask.settings.development:<module>:50 - /home/phillyharper/dask/static 2021-05-09 07:17:03.198 | INFO | dask.settings:<module>:7 - DEV SETTINGS SETTINGS 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:4 - Debug is True 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:47 - Debug is True 2021-05-09 01:47:03.417 | INFO | dask.settings.development:<module>:50 - /home/phillyharper/dask/static 2021-05-09 01:47:03.417 | INFO | dask.settings:<module>:7 - DEV SETTINGS SETTINGS However, when I click onto the page - none of the static files load. They all 404, giving this:~ [09/May/2021 01:47:51] "GET / HTTP/1.1" 200 22203 [09/May/2021 01:47:51] "GET /static/src/assets/lib/perfect-scrollbar/css/perfect-scrollbar.css HTTP/1.1" 404 1800 [09/May/2021 01:47:51] "GET /static/src/assets/lib/material-design-icons/css/material-design-iconic-font.min.css HTTP/1.1" 404 1854 [09/May/2021 01:47:51] "GET /static/src/assets/css/app.css HTTP/1.1" 404 1692 [09/May/2021 01:47:51] "GET /static/src/assets/lib/jquery/jquery.min.js HTTP/1.1" 404 … -
NoReverseMatch Error in Django project: Bootstrap link causing problem? Can't see how or why though
I'm really stumped on how to fix this. I've dealt with NoReverseMatch errors before and I'm aware that it's usually an issue with the URL path or the function related to it in views.py, but this particular page I'm trying to render keeps returning NoReverseMatch saying that there's a line in my layout.html template that contains my link to Bootstrap that's the problem. I've tried editing this line out but no good. I've checked the URL path and the relevant function in views.py but I can't see anything that suggests an error. Here's what I mean... Error message Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Error during template rendering In template C:\Users\Leigh\Desktop\Coursework\CS50Web\project4\network\templates\network\layout.html, error at line 7 Reverse for 'register' not found. 'register' is not a valid view function or pattern name. Here's an image of line 7 being referred to. As I've mentioned, I've checked out line 160 in views.py which calls on the URL in urls.py. Here is the URL path for "register.html" in urls.py path("register", views.register, name="register") I'm at a loss really. I can't see anything that would be causing the NoReverseMatch. "register.html" definitely exists despite Django saying that there … -
loading two html pages linked to different urls in same page(iframe)
I have a page 1.html linked to /registration in urls.py, now I have a another page 2.html linked to /verify. Now I want to display /verify as a pop in /registration page it self. So far I have used iframe to do this but it says 127.0.0.1 refused to connect. <iframe id="theFrame" src="/verify" style="width:100%;" frameborder="0"> </iframe> Iam using djnago btw. Basically I want to display one html page as a pop in another. Thank you! -
Django-q: WARNING reincarnated worker Process-1:1 after timeout
I've installed and configured Django-Q 1.3.5 (on Django 3.2 with Redis 3.5.3 and Python 3.8.5). This is my Cluster configuration: # redis defaults Q_CLUSTER = { 'name': 'my_broker', 'workers': 4, 'recycle': 500, 'timeout': 60, 'retry': 65, 'compress': True, 'save_limit': 250, 'queue_limit': 500, 'cpu_affinity': 1, 'redis': { 'host': 'localhost', 'port': 6379, 'db': 0, 'password': None, 'socket_timeout': None, 'charset': 'utf-8', 'errors': 'strict', 'unix_socket_path': None } } where I have appropriately chosen timeout:60 and retry:65 to explain my problem. I created this simple function to call via Admin Scheduled Task: def test_timeout_task(): time.sleep(61) return "Result of task" And this is my "Scheduled Task page" (localhost:8000/admin/django_q/schedule/) ID Name Func Success 1 test timeout mymodel.tasks.test_timeout_task ? When I run this task, I get the following warning: 10:18:21 [Q] INFO Process-1 created a task from schedule [test timeout] 10:19:22 [Q] WARNING reincarnated worker Process-1:1 after timeout 10:19:22 [Q] INFO Process-1:7 ready for work at 68301 and the task is no longer executed. So, my question is: is there a way to correctly handle an unpredicted task? -
Is there a convention for tightness of database relations vs ease of testing in Django?
Say I have a model with a foreign key: class Thing(models.Model): related_stuff = models.ForeignKey('app.stuff', blank=True, null=True, related_name='things', on_delete=models.PROTECT) def method_of_thing(self): pass This is pretty easy and fast to test, I just create a Thing and away I go testing method_of_thing. However, strictly speaking a Thing should always have related_stuff so in terms of correct constraints this is the relation I should have: class Thing(models.Model): related_stuff = models.ForeignKey('app.stuff', related_name='things', on_delete=models.PROTECT) BUT, when it comes to testing, this means I have to do a hell of a lot of setup in tests, creating the related_stuff. Even using model_bakery or factory_boy this leads to a lot of extra lines and time in my tests. What are the key things to think about when deciding if I should make this tradeoff of data integrity for speed of development and test? Is there a convention / emerged dominant opinion on this within the django community? -
How do I call Datatables draw() method in Ajax?
I am trying to implement datatables draw() method in my Django application using AJAX. I have implemented both datatables and AJAX, which are working fine. However, I am facing a lot of challenges anytime I create a new object and call the draw() method so that datatables can refresh the table and show the newly created data the proper way. If I add the draw() method, the table does not get populated at all except I refresh the page. main.js //datatables $(document).ready(function() { $('table').on('click', ".dropdownDatatableButton" ,function() { $( this ).toggleClass( "active"); }); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); var table = $('#boardsTable').DataTable({ "autoWidth": false, "info": false, "lengthChange": false, "processing": true, "hover": true, "serverMethod": 'post', "searching": true, "ajax": "/boards/api/data/?format=datatables", "pagingType": "full_numbers", "order": [[ 0, "asc" ]], language: { search: "", "zeroRecords": '<img class=' + '"dataTables-error-image"' + 'src=' + "'/static/media/images/empty-search.jpg'" + '/>' + '<p class=' + '"dataTables-error-text"' + '>' + 'No boards were found that match your search' + '<p/>', "loadingRecords": '<div class="spinner-border m-5" role="status">' + '<span class="sr-only d-block">Loading...</span> </div>' + '<p class="d-block text-center mt-3">Pulling board information...' + '</p>', "processing": '<p class="d-block text-center … -
Run Django in DEBUG mode with Daphne
Need help to run django app with daphne in DEBUG mode with pycharm. Is there any way? -
How can i get this value? DJANGO
I would like to collect this value and pass it by post to the database I want to pass {{qs.nombre}} and {{ user.user }} but i try this and not run.. When i try request.POST['maquina']: img My code here: .html <form action="" method="POST"> {% csrf_token %} <div class="container"> <div class="row"> {% for qs in queryset %} <div class="col-xl-12 col-lg-12"> <fieldset class="scheduler-border"> <legend class="scheduler-border">EMPLEADO</legend> <b><p class="black">Identificado: </b>{{ user.username }}</p> <b><p class="black">Empleado: </b>{{ user.first_name }} {{ user.last_name }} </p> <b><p class="black">IP: </b>{{ qs.ip }}</p> <b><p class="black">Maquina: </b><input type="text" name="maquina" value="{{ qs.nombre }}" disabled /></p> <b><p class="black">Nº Maq: </b><input type="text" name="rec_" value="{{ qs.rec }}" disabled/></p> <b><p class="black">Usuario: </b><input type="text" name="user" value="{{ user.user}}" disabled/></p> </fieldset> </div> {% endfor %} -
How to measure usage in a video chat app?
I have a group video chat application where users can randomly pop into rooms to have a conversation. Imagine something like a video reddit This is more of an architecture question than a code question. How do I measure usage? I want to track how long users spend in each room, which rooms are popular, get a history of every room that a user has visited to understand their user profile The most naive thing that I can think of is to create a new table in the database called usage where I log every event such as user entering a room with timestamp, user leaving a room with timestamp that would look something like this for eg - | user | room | event | timestamp |------|----------|---------------|------------ | 1 | bitcoin | join_room | 1620632092 | 2 | comedy | join_room | 1620632094 | 1 | bitcoin | leave_room | 1620632292 | 3 | politics | join_room | 1620632295 | 3 | politics | leave_room | 1620632296 | 4 | dogs | join_room | 1620632296 | 5 | python | join_room | 1620632296 | 4 | dogs | leave_room | 1620632296 | 5 | python | leave_room | 1620632296 … -
Django MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs -- it returned 2
I was coding a song viewing website with Django then suddenly came across this error MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs -- it returned 2! I was trying to set up my website such that when users click on the name of the author of any song, they will be redirected to another page where there are songs of that author only. But unfortunately, my code is running into this error. My models.py: class Songs(models.Model): title = models.CharField(max_length = 100) lyrics = models.TextField() author = models.CharField(max_length = 100) track_image = models.CharField(max_length=2083) def __str__(self): return self.title def get_absolute_url(self): return reverse('/', kwargs={'pk': self.pk}) My views.py: def home(request): context = { 'songs': Songs.objects.all() } return render(request, 'home.html', context) class AuthorSongListView(ListView): model = Songs template_name = 'author_songs.html' context_object_name = 'songs' paginate_by = 2 def get_queryset(self): author = get_object_or_404(Songs, author=self.kwargs.get('author')) return Songs.objects.filter(author=author) My html: {% block content %} <h1 class="mb-3">Songs by {{ view.kwargs.author }}</h1> {% for song in songs %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a> </div> <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2> <p class="article-content">{{ song.lyrics }}</p> </div> </article> {% endfor %} {% endblock content %} -
Django: pass some paremeter to view in Django urls
I want to pass some string for some urls to my views in django Suppose i have path('someurl/', someview , name='someurl'), I want to pass some string to someview, when this url is called so is this possible path('someurl/', someview(somevar="test") , name='someurl'), and then i have the view def someview(request, somevar): access somevar here Is this possible in Django urls. -
Django migrations raw SQL update not working
I have a very simple migration which updates a table, when I run it on pgadmin, it just executes fine the values change, but in migration nothing is saved. # Generated by Django 3.0.5 on 2021-05-10 06:36 from django.db import migrations class Migration(migrations.Migration): atomic = False dependencies = [ ('api', '0073_fill_grid1000'), ] operations = [ migrations.RunSQL(""" UPDATE api_grid125 SET parent_grid_id = intersections.parent_id FROM ( SELECT api_grid125.id as id, api_grid250.id parent_id FROM api_grid250 JOIN api_grid125 ON ST_Intersects(api_grid250.area, api_grid125.area) AND ST_Area(ST_Intersection(api_grid250.area, api_grid125.area)) > 0.01 ) as intersections WHERE api_grid125.id = intersections.id """, ""), ] My database is PostgreSQL, thanks! -
How to set default values on django admin site for extended user model?
I want to create a user profile model as an extension of the original django user model. I implemented the model in models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) solved = models.IntegerField(default=0) profile_pic = models.ImageField(upload_to='profile_pic', default="/media/profile_pic/default-profile.jpg") school = models.CharField(max_length=200, blank=True, null=True) However, when I create a new user in the admin site, there is no default value for the profile_pic field. In addition, although the solved field shows a '0' on the form, the value is not saved after I pressed save: I registered the extended user model like this in admin.py: class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'User Profile' class UserAdmin(BaseUserAdmin): list_display = ('username', 'is_staff', 'solved') inlines = (UserProfileInline,) def solved(self, obj): return obj.userprofile.solved admin.site.register(User, UserAdmin) Am I doing something wrong? Is the default value only used when creating a user using python but not the admin site? Please help. Thanks. -
django - How to upload file to local and remote server directory at same time
I am implementing a feature in django where file uploaded by user should be saved in both local system and remote server location also. I am able to do both the process individually but not together. Is there any way we can upload a file to both the location local and remote? Django version - 3.0 -
ValueError at /student/ : save() prohibited to prevent data loss due to unsaved related object 'Qid'
models.py class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.OneToOneField(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) User = settings.AUTH_USER_MODEL User_id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() views.py : Trying to save Answer text field along with 1 One-to-One Field and 2 Foreign key fields in the database.but getting error when user saves answer through form. @login_required(login_url='login') @allowed_users(allowed_roles=['Student']) def handle_response(request): if request.user.is_authenticated: myuser = User.objects.all() title = quiztitle.objects.all() ques = question.objects.all() if request.method == 'POST': Answer = request.POST.get('{{x.Qid}}') Quiz_id = request.POST.get('Quiz_id') Qid = request.POST.get('Qid') quizid = quiztitle(Quiz_id=Quiz_id) quesid = question(Qid=Qid) response = answer(Answer=Answer) response.User_id = request.user #tried to save Foreign key field response.Quiz_id = quizid #tried to save Foreign key field response.Qid = quesid #tried to save one to one field response.save() return HttpResponseRedirect('/student') return render(request,"student.html",context={"ques": ques ,"title": title ,"myuser": myuser}) -
KeyError: 'postgraduate-course' in django webapp
I have used django to develop a web app. However, I got a key error, which is very confused. HTML: <form action="/content_checklist_name_url/" method="POST" onsubmit="return confirm('Do you want to confirm entries?');"> <label> Postgraduate Course: </label> <select id="postgraduate-course" name="postgraduate-course"> <option value="">--Select--</option> <option value="Yes">Yes</option> <option value="No">No</option> </select> </form> view.py: def content_checklist_name_url(request): if request.method == 'POST': Course_Form = ContentChecklistForm(data=request.POST) if Course_Form.is_valid(): postgraduate_course = Course_Form.cleaned_data["postgraduate-course"].map({'Yes': 1, 'No': 0}) I got the error: KeyError: 'postgraduate-course' at this line: postgraduate_course = Course_Form.cleaned_data["postgraduate-course"].map({'Yes': 1, 'No': 0}) -
How do I delete data on button click from django database?
I need to delete data on click of a button in django here's my view page views.py here's my button code html button onclick of that button data should get deleted. this button works as a refresh button. So even if I do not click on the button only do page refresh data get deleted -
cannot access user data from social-auth-app-django
I am overwhelmed by the authentication of Django and trying to wrap my head around it for a while. i have used social-auth-app-Django to use OAuth for authorization from GitHub and Facebook. GitHub worked and Facebook didn't worked, after log-in using GitHub I checked the admin page, in the user social auths part i wasn't able to access the provider name using the template syntax in the html Page didn't showed up! can someone explain what really going on here, and what is associations and nonces too? this is my html. -
Django Email Settings for different purposes
How to set django to have multiple EMAIL Settings. Example: Email for registration and email for reset password: if registration: # EMAIL SETTINGS EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'XXX' EMAIL_PORT = 'XXX' EMAIL_HOST_USER = 'registrationemail@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True # EMAIL_USE_TLS = False else: # EMAIL SETTINGS EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'XXX' EMAIL_PORT = 'XXX' EMAIL_HOST_USER = 'resetpassword@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_USE_SSL = True # EMAIL_USE_TLS = False Note: I can send email without problems. Should I send a parameter to my settings.py? If so, how should I do it? -
django admininstrator register accpetion
Now, I'm using django's basic form of registration. However, I want to make customed administrator site that can accpet registration and refuse it. I really need some help. basic form: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') return redirect('login') else: form = UserRegisterForm() return render(request, 'home/register.html', {'form': form}) -
AuthFailed at /oauth/complete/github/ Error in Django for social login
Authentication failed: The redirect_uri MUST match the registered callback URL for this application. I have registered i my github account and the callback url i have set is: http://localhost:8000/oauth/complete/github/ and homepage url http://localhost:8000/ but the error is still there. and redirect Url in settings.py LOGIN_REDIRECT_URL = 'home' I have tried many other techniques please help me out my urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings from developer import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name='home'), path('profileEdit',views.profile_edit_form,name='profileEdit'), path('accounts/', include('accounts.urls')), path('<int:pk>', views.profile_view, name='profileview'), path('invites/', views.invites_view, name='invitesview'), path('invites/<int:pk>', views.inviter_view, name='inviterview'), path('oauth/', include('social_django.urls', namespace='social')), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) -
Using get_natural_key and AbstractUser: "ValueError: Field 'id' expected a number but got <String>"
I'm trying to loaddata a yaml fixture using natural foreign key. The thing is: the foreign key in question is an AbstractUser. models.py: from django.contrib.auth.models import AbstractUser, BaseUserManager class MyUserManager(BaseUserManager): def get_by_natural_key(self, username): return self.get(username=username) class MyUser(AbstractUser): ... objects = MyUserManager() # use for serialization def __str__(self): return self.username def natural_key(self): return (self.username) class Cars(models.Model): owner = models.ForeignKey(MyUser, null=True, on_delete=models.CASCADE) My fixture is a yaml file: (I've already a MyUser account with the username "Franck" in the database). - model: myapp.Cars fields: owner: - Franck But when doing: ./manage.py loaddata myfixture.yaml, I've got the error: ... ValueError: invalid literal for int() with base 10: 'Franck' The above exception was the direct cause of the following exception: ... ValueError: Field 'id' expected a number but got 'Franck'. -
Djongo DateTrunc returns nothing
Django 3.0.5 + Djongo 1.3.4 Database function (Trunc) as per below URL in Django returned nothing. https://docs.djangoproject.com/en/3.0/ref/models/database-functions/#trunc My context_processors.py as below, from .models import Article from django.db.models import Count, F, DateField from django.db.models.functions import Trunc # Reference: https://stackoverflow.com/questions/49440657/django-blog-archive-display-list-of-years-and-months-that-include-post # https://www.jianshu.com/p/3f846ecbd945 # return dictionary for parsing side menu def Side_Menu_Context(request): breakpoint() Year_Month = Trunc(Article.objects.all()[0].time_publish,'month', output_field=DateField()) Dict_Context = {'QS_YM_BlogCount': Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())).values('Year_Month').annotate(num_of_article = Count('id'))} return Dict_Context DEBUG output as below: [29] > /usr/src/app/IoTSite/context_processors.py(16)Side_Menu_Context() -> return Dict_Context (Pdb++) pp Article.objects.all()[0].time_publish datetime.datetime(2021, 5, 10, 1, 44, 4, 619000, tzinfo=<UTC>) (Pdb++) pp Year_Month Trunc(Value(2021-05-10 01:44:04.619000+00:00)) (Pdb++) pp Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())) (Pdb++) pp Dict_Context (Pdb++) whatis Dict_Context <class 'dict'> (Pdb++) whatis Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())) <class 'django.db.models.query.QuerySet'> (Pdb++) l. 11 def Side_Menu_Context(request): 12 breakpoint() 13 Year_Month = Trunc(Article.objects.all()[0].time_publish,'month', output_field=DateField()) 14 15 Dict_Context = {'QS_YM_BlogCount': Article.objects.annotate(Year_Month = Trunc('time_publish','month', output_field=DateField())).values('Year_Month').annotate(num_of_article = Count('id'))} 16 -> return Dict_Context [EOF] (Pdb++) Year_Month = Trunc() returned something, but Dict_Context = {} returned nothing, why so since they use the same function Trunc() ??