Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku constantly change url for my heroku-redis addon
Im using the heroku-redis addon as a message broker for my django app, which is hosted on a VPS. The problem is that Heroku constantly change de URL of the service, so my app keep crashing from time to time, when the url is changed. Anyone knows a way to fix this? Is there a way of getting automatically the updated URL for my heroku-redis addon? -
How to get rid of this weird error in django?
I had migrated an app to Heroku recently and everything was going well until I hit a Server Error today, a normal 500 error that occurred due to requests being an old version. Once I had upgraded requests, the error still persisted and the site came only after I turned DEBUG=True in my settings.py file which is absurd because DEBUG should not be true but when I change it to False it triggers the same error and the problem is: 2020-06-03T15:13:41.896001+00:00 heroku[router]: at=info method=GET path="/" host=know-ur-level.herokuapp.com request_id=d4fd68f3-5111-493e-b75c-c4f5a9f2e519 fwd="49.37.194.191" dyno=web.1 connect=1ms service=618ms status=500 bytes=649 protocol=https 2020-06-03T15:13:41.893360+00:00 app[web.1]: 10.10.68.189 - - [03/Jun/2020:15:13:41 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36" I do not know what to make of this output. Can someone tell me what's wrong?. The reason I tagged this as python-requests is that maybe this error is somehow related to this? I'll put up the necessary files. Let me know if I can add anything more. My settings.py import os import django_heroku import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) SECRET_KEY = '******' DEBUG = True #area of absurdity … -
How to create Django application with User and ActivityPeriod models with help of RESTAPI for the below output?
This is an expected output JSON format. -
Django - Unable to import npm module from js file
I'm trying to import Vue as a npm module in my js file using this syntax : import Vue from 'vue'; But I get this error : Uncaught TypeError: Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../". But when I try any of these examples, it can't even find the folder node_modules in my application. Any idea ? -
Starting up an existing Django project by one command after cloning from git
Lately I have come across a requirement to facilitate the ability to start a Django project by one command. That is, they want to clone a Django project from git, go to the project root directory and run some majic command like python manage.py start_me_magically without going through all that tedious manage.py migrate, pip install -r requirements.txt stuff. I know that this sort of things are best solved by Docker, but I am looking for a vanilla solution in a form of a python script or a management command. I should also be able to automatically create a virtualenv, and run the project with this virtual env activated. Now I am going to write a simple python script like 'setup.py' and put it in the root directory of the project, but I am afraid to do something which would look like a novice "junk" solution, or to invent a wheel. After googling around, I wasn't able to find something similar, but I am sure there should be a ready-to-use solution for that. Any hints ? -
How should i save the data that i'm getting from a script into db (Django)?
So i'm new to django and i have a python Script which get's some data from an api and does some tasks on it and prints out a list with two variables. I get new data everyday from the api and i want to save the output of this script into the database automatically every time it runs. Can u guys give me a overall guide on how should i do this ? -
How to set field via m2m-changed?
I have a receiver function waiting for a m2m field to be changed. This receiver is called, but I can't set these fields in my model? My receiver looks like this, by the print option, I can see that is is called. @receiver(m2m_changed, sender=targetAdress.neighbours.through) def setNeighs(sender, instance,pk_set, action, **kwargs): if action == "post_add": objs = sender.objects.all() instance.neighbours.set(objs) For this I get a typeError because a DWDstation object is expected as neighbour. Instead I get a targetAdress.neighbours object. How do I transfer this into something that works? -
when i try to execute my code,i am getting this error?How to resolve this issue?
ProgrammingError at / (1146, "Table 'multi_traffic.django_session' doesn't exist") Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 1.11.5 Exception Type: ProgrammingError Exception Value: (1146, "Table 'multi_traffic.django_session' doesn't exist") Exception Location: C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages\MySQLdb\connections.py in query, line 277 Python Executable: C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts\python.exe Python Version: 3.6.2 Python Path: ['F:\projects\MULTI_TRAFFIC\MULTI_TRAFFIC\Code\Multi_Traffic_Scene_Perception', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts\python36.zip', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\DLLs', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\Scripts', 'C:\Users\SAI RAM\AppData\Local\Programs\Python\Python36\Lib', 'C:\Users\SAI RAM\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv', 'C:\Users\SAIRAM~1\PYCHAR~1\SAMPLE~1\venv\lib\site-packages'] -
Conditional for loop in Django template
I'm using the same template for two different queryset. view: def events_list_view(request, type): events_NMS = dateEvent.objects.filter(a filter) events_all = dateEvent.objects.filter(another filter) context = { 'events_NMS': events_NMS, 'events_all': events_all, } return render(request, 'events/events_list.html', context) urls: path('events/<type>/', events_list_view, name='events_list'), How can I, depending on which type is in the URL, use events_NMS or events_all? I'd like do do something like this in my template: {% if "/events/nms/" in request.path %} {% for event in events_nms %} {% else %} {% for event in events_all %} {% endif %} ...rest of for loop... -
OSError in django
I'm trying to load my trained TensorFlow model in Django for some reason I'm not able to load it. I'm not sure how to load a TensorFlow model in django this is my code in the view.py file enter code here if request.method=='POST': enter code here file_path_enc=request.FILES["file_path"] enter code here new_file_path = file_path_enc enter code here fs=FileSystemStorage() enter code herename=fs.save(new_file_path.name,new_file_path)enter code here enter code here url=fs.url(name) enter code here DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) enter code here filepath=DIR+url enter code here IMG_SIZE = 250 enter code here img_array = cv2.imread(filepath) enter code here new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE)) enter code here reshape=new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3) enter code here print(reshape) enter code here path=DIR+"AI_detector/plant.model" # model name enter code here model = tf.keras.models.load_model(path) -
Sum If Another Column Is Distinct Djagno
I have a two tables in djagno class Item(models.model): name = models.TextField() type = models.ForeignKey(ItemType) quantity = models.IntegerField() and class ProductionRecord(models.model): item = models.ForeignKey(Item) done = models.IntegerField() What i am wanting to do is group the items by its type, sum the total quantity of items needed, and then sum the total quantity of items produced. I was fairly close but the issue i ran into was that when doing .annotate(Sum("quantity")) if an item has multiple production records, it will sum the quantity again, per record. Below is an example of my current data set after joining the tables and before grouping. +--------+--------+--------------+----------------------+ | ItemId | TypeId | ItemQuantity | ProductionRecordDone | +--------+--------+--------------+----------------------+ | 1257 | 7 | 4 | 1 | | 1257 | 7 | 4 | 4 | | 1259 | 7 | 4 | 4 | | 1261 | 7 | 4 | 0 | | 1263 | 7 | 4 | 4 | | 1265 | 7 | 4 | 0 | +--------+--------+--------------+----------------------+ When doing a normal sum on the quantity column, it returns 24 because it is summing for item id=1257 twice. But what i would like to return after grouping is: +--------+--------------+------+ | … -
How can I use a variable from views.py in a base template for multiple templates?
In a Django application I have several html pages with a similar structure. I am already using a base_site.html template for all my project but for these other pages I would like to use a second template to create tables. These tables could have more or less rows and columns than others. My idea was that the functions in views.py would send a list of the headers for any given page together with a dict of the data to populate the table, then in the html page I would iterate the list of headers to place the headers in the table then I would iterate the dict to populate the table with the data. How can I have a table-template.html to use a variable say headers from every function in views.py whenever they are called? Something like table-template.html <h1>TEST</h1> <table> <tr bgcolor="#ccc"> <th>{% for h in headers %} {{ h }} {% endfor %}</th> </tr> </table> Considering that every function in views.py would return its own headers list Then how can I use it in any of the html pages {% extends "admin/base_site.html" %} {% load static %} {% block content %} {% include "table-template.html" %} {% load static %} … -
Django Rest Framework: Custom IsReadOnly Permission
I create a custom permission which authorizes GET, HEAD and OPTION for everyone and which authorizes NO other requests. But my code doesn't work. I can make a POST request despite my permission ... Anyone have a idea to solve my problem ? My views.py: class IsReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return False class ViewPollViewSet(viewsets.ModelViewSet): permission_classes = [ IsReadOnly, ] serializer_class = ViewPollSerializer queryset = ViewPoll.objects.all() My serializers.py: class ViewPollSerializer(serializers.ModelSerializer): class Meta: model = ViewPoll fields = '__all__' My models.py: class ViewPoll(models.Model): ''' view poll ''' class Meta: unique_together = ('poll', 'user') poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="views", null=True) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="views_poll", null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.poll.question)[:30] -
Including JavaScript in a Django template through the static folder
In my Django project, I am storing my JavaScript function in a folder in the path: root/static/js/js_function When I include the JavaScript directly in the .html file, it runs as expected. But when I move the JS to this static folder, the HTML does not recognize the Javascript. settings.py (relevant static section): # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(BASE_DIR("staticfiles")) # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = [str(APPS_DIR.path("static"))] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] index.html: <div id="odds_calculator"> <p>Placing $<input type="number" name="hypothetical_bet" v-on:input= "update_hypothetical_bet"> on this bet would win you $[[ result() ]] if you were to win the bet.</p> <p>Bet Amount: [[ number1 ]] </p> <p>Odds: {{ basketballbet.odds }}</p> <hr> <p>Result: $[[ result() ]]</p> </div> {% load static %} <script src = "{% static 'js/odds_calculator.js' %}"></script> odds_calculator.js: new Vue({ delimiters: ['[[',']]'], el: '#odds_calculator', data: { hypothetical_bet: 0, odds: {{ basketballbet.odds }}, }, methods: { update_hypothetical_bet: function (event) { this.hypothetical_bet = event.target.value; }, result: function () { return this.odds < 0 ? (this.hypothetical_bet*(-100/this.odds)).toFixed(2) : (this.hypothetical_bet*(this.odds/100)).toFixed(2); }, }, }); -
How can I programaticaly create a directory on file upload and save the uploaded file to that direcotry using django?
I'm trying to create a directory programmatically on file upload. I'm able to create the directory using date and time stamp at the same time the file also getting uploaded. But I'm not able to save the file inside the directory during the upload. My views.py def uploadfile(request): dirname = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() os.mkdir(os.path.join('uploads', dirname)) #'uploads' is my media root folder name = fs.save(uploaded_file.name, uploaded_file) ##** this file need to be saved inside the /uploads/2010.08.09.12.08.45/files_name **## context['url'] = fs.url(name) return render(request, 'upload.html', context) The above code uploads the file using the form from the template using POST and the and it also creates a folder with current timestamp. But the issue is that I'm not able to save the file inside the folder. -
Django auto populate Drop Down with CSV data
I am using below code to populate unique data from the CSV file on the Django template. This is my view.py code df = pd.read_csv("statics/chicago_crime_2016.csv") columns = df.columns primary_type = df['Primary Type'].unique() def index(request): context = {'primary_type': primary_type, 'columns': columns} return render(request, 'index.html', context) Django And this is my HTML code: <div class="container-fluid mt-4"> <select> {% for column in columns%} <option value="{{ column }}">{{ column }}</option> {% endfor %} </select> <select> {% for type in primary_type%} <option value="{{ type }}">{{ type }}</option> {% endfor %} </select> </div> HTML Picture Next what I want when I choose a column from the first dropdown, then it shows me in the second dropdown that column value which chooses in the first dropdown. Now it's showing only one column value and it is static and I want a dynamic dropdown that makes changes according to the situation. -
Python Django NoReverseMatch Template
I configured the path and made the template but when I try to run server it gives NoReverseMatch at /password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 3.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error. My urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name= 'register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done '), path('password-reset-confirm///', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm '), path('', include('blog.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class = "content section"> <form method="POST"> {% csrf_token %} <fieldset class= "form-group"> <legend class = "border-bottom mb-4">Reset Password</legend> {{form|crispy}} </fieldset> <div class = "form-group"> <button class="btn btn-outline-info" type ="submit"> Reset Password </button> </div> </form> </div> {% endblock content %} Could you please tell me what is … -
Django 3.0.5 User Authenticate with Username or Email
i'm struggling a bit with this problem, some says i have to override AuthenticationForm but i don't know how cause i got a custom user registration and login, i'll post it: urls.py urlpatterns = [ path('login/', LoginView.as_view(), {'template_name': 'accounts/login.html'}, name='login'), Note im using default loginview right now. So in views.py i must have this def login(request): return render(request, '/login.html') ... ... Of course login.html is just like this <div class='container'> <h1>Welcome</h1> <p> you can login here! </p> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type='submit'>Login</button> </form> </div> In models.py my custom user is this one: class ProfiloUtente(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) utente = models.ForeignKey(Utente, on_delete=models.CASCADE) studio = models.ManyToManyField(Studio) telefono_fisso = models.CharField(max_length=20, default=None, blank=True) telefono_mobile = models.CharField(max_length=20, default=None, blank=True) indirizzo = models.CharField(max_length=40, default=None, blank=True) citta = models.CharField(max_length=50, default=None, blank=True) cap = models.CharField(max_length=5, default=None, blank=True) provincia = models.CharField(max_length=30, default=None, blank=True) cod_fiscale = models.CharField(max_length=16, default=None, blank=True) p_iva = models.CharField(max_length=27, default=None, blank=True) def __str__(self): return self.user.username And the fields i use from The default django user are these: forms.py class RegistrationForm(UserCreationForm): """docstring for RegistrationForm""" email = forms.EmailField(required=True) first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=100, required=True) class Meta: # define a metadata related to this class model = User fields = … -
Django 'TestMiddleware' object has no attribute 'get_response'
I have a problem with my django TestMiddleware code My djando version Django 3.0.6 My code middleware.py from django.utils.deprecation import MiddlewareMixin class TestMiddleware(MiddlewareMixin): '''中间键类''' def __init__(self, request): '''服务器重启之后,接受第一个请求时调用''' print('--init--') def process_request(self, request): '''产生request对象后,url匹配之前调用''' print('--process_request--') def process_view(self, request, view_func, *view_args, **view_kwargs): '''url匹配之后,视图函数调用之前''' print('--process_view--') def process_response(self, request, response): '''视图函数调用之后,内容返回浏览器之前''' print('--process_response') return response setting.py MIDDLEWARE = [ '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', # 'booktest.middleware.BlockedIPSMiddleWare', 'booktest.middleware.TestMiddleware', ] Error System check identified no issues (0 silenced). June 03, 2020 - 13:38:28 Django version 3.0.6, using settings 'test5.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. --init-- --process_request-- Session data corrupted Internal Server Error: /index Traceback (most recent call last): File "/home/coco/.virtualenvs/bj19_py3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/coco/.virtualenvs/bj19_py3/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in call response = response or self.get_response(request) AttributeError: 'TestMiddleware' object has no attribute 'get_response' I am new for python , pls I need some help -
Django filter and update atomicity
When updating filtered records, is there a need for select_for_update if you want to make sure that the filtered rows won't get changed by some other process before this update is done, or is this filter + update atomicity guaranteed out-of-the-box? I.e., is this: with transaction.atomic(): Foo.objects.select_for_update().filter(id=1).update(**kwargs) equivalent to: Foo.objects.filter(id=1).update(**kwargs) ? I'm using Django 1.6.x. -
How and where to run (heavy) functions in the server for a django web app / where to store them
I am quite beginner to Django and I am confronted with this question. provided I have the following structure: django_app/ django_app/ __init__.py asgi.py settings.py urls.py views.py wsgi.py loaddata_app/ >migrations __init__.py admin.py apps.py models.py test.py urls.py views.py >static >templates loaddata.html My loaddata app is a super easy app that contains a text field to enter (paste) text. The app should send the text to the server where a series of methods are applied to extract information out of the text and generate output data that will be presented to back to the user. The first question is: If you have a bunch of methods in various files, where do you actually "store" those methods. And where are those methods supposed to be imported (if they need at all to be imported)? What happens if those methods take (so to say) 10 minutes to run? is the connection still maintained with the browser of the user in the meanwhile? So looks the simple app: NOTE: The question is partially answered here. But it is not entirely clear where those utils are imported and run in order to process the data. Django: where to store functions common to all apps -
How to open window with html or dialog box in middle view django
I have the following scenario: In a view I do a get in an external api with the data that the user provides me via form, with this get I get a series of images, the user then needs to write the code of the image he wants and send it to me, I need then capture the answer and make new get and finally finish my view. Note: I cannot close my view before user interaction because I have a session object that cannot be lost, if this occurs the code entered will not actually match the image if request.POST['action'] == 'get_images': name = request.POST.get('name') birthday = request.POST.get('birthday') gender = request.POST.get('gender') preferences = preferences.Preferences(gender, birthday, name) preferences.login_page() preferences.add_page() images = preferences.get_images() #get images #need display dialog box with image in di response = #input user in dialog box resp = preferences.search_page(response)#new get to know some info user print(resp) -
How to save folium map in Django templates,
when I tried "In your code map is a folium.Map object, not yet a string with html/javascript. You need to render it first. Normally, this creates a single, full HTML page. For Jupyter notebooks this HTML page is put into an iframe. So there are two options: If you don't want or need to put the map in a template, you can directly render the page: m.get_root().render() returns a string with the full HTML/JS page. If you want to embed the map into a template you can use an iframe: m._repr_html_() returns a string with an iframe with the HTML/JS page." map is empty -
django-rest-framework – how to serialize nested objects?
I am trying to create an api endpoint that pulls all the FeaturedProvider and Testimonial objects from the database, serialize it and return it as a new serialized object HomepageContentSerializer I've tried multiple ways but I'm getting empty {} when I try to hit the endpoint. I'm not sure where to initialize or pass the FeaturedProvider and Testimonial objects to the HomepageContentSerializer to be serialized serializers.py class FeaturedProviderSerializer(serializers.ModelSerializer): class Meta: model = FeaturedProvider fields = '__all__' class TestimonialSerializer(serializers.ModelSerializer): class Meta: model = Testimonial fields = '__all__' class HomepageContentSerializer(serializers.Serializer): providers = FeaturedProviderSerializer(many=True, read_only=True) testimonials = TestimonialSerializer(many=True, read_only=True) views.py class HomepageContent(APIView): renderer_classes = [JSONRenderer] def get(self, request): content = HomepageContentSerializer().data return Response(content) My goal is to get this representation back { "providers": [ { ... }, { ... }, { ... }, ], "testimonials": [ { ... }, { ... }, { ... }, ], } -
How to see all the notifications in html using Django-notification package
I have implemented this django notification package in my project, but I am not able to understand how can I see those notifications in html. I can see the nofications in admin panel, as it is working fine in the views. with their template tag I can even see that I have these many unread notifications as well, but I want to see what those notifications are as wee see in facebook or twitter. Can anyone explain how to get the html for that? This is the package: https://github.com/django-notifications/django-notifications this is my view for posts likes def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True create_action(request.user, 'liked the post', post) notify.send(sender=user, recipient=post.user, verb='liked your post', target=post) # return redirect('posts:myhome') context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) Thanks