Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does mock patch only work when running specific test and not whole test suite?
I'm using Django and Pytest specifically to run the test suite and am trying to test that a specific form shows up with expected data when a user hits the site (integration test). This particular view uses a stored procedure, which I am mocking since the test would never have access to that. My test code looks like this: #test_integrations.py from my_app.tests.data_setup import setup_data, setup_sb7_data from unittest.mock import patch ... # Setup to use a non-headless browser so we can see whats happening for debugging @pytest.mark.usefixtures("standard_browser") class SeniorPageTestCase(StaticLiveServerTestCase): """ These tests surround the senior form """ @classmethod def setUpClass(cls): cls.host = socket.gethostbyname(socket.gethostname()) super(SeniorPageTestCase, cls).setUpClass() def setUp(self): # setup the dummy data - this works fine basic_setup(self) # setup the 'results' self.sb7_mock_data = setup_sb7_data(self) @patch("my_app.utils.get_employee_sb7_data") def test_senior_form_displays(self, mock_sb7_get): # login the dummy user we created login_user(self, "futureuser") # setup the results mock_sb7_get.return_value = self.sb7_mock_data # hit the page for the form self.browser.get(self.live_server_url + "/my_app/senior") form_id = "SeniorForm" # assert that the form displays on the page self.assertTrue(self.browser.find_element_by_id(form_id)) If I run this test itself with: pytest my_app/tests/test_integrations.py::SeniorPageTestCase The tests pass without issue. The browser shows up - the form shows up with the dummy data as we would expect and it all … -
Apache2 virtualhost is activated but not listening
I have 3 Django apps, app1, app2 and app3 running on a DigitalOcean droplet. I am using nginx as a reverse proxy for domains, domain1, domain2 and domain3 that point to apache2 virtualhosts listening on ports 8081,8082 and 8083 respectively. They are all using mod_wsgi. When I try to access each on their respective domains, I am getting 503 bad gateway nginx error on app3's domain3 /var/log/nginx/error.log has this error at the bottom: .... 2020/12/14 13:16:48 [error] 3173#3173: *4 connect() failed (111: Connection refused) while connecting to upstream, client: <mylocalip>, server: "<domain3>", request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8083/", host: "<domain3>" Running sudo netstat -plant | grep apache gives: tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 3165/apache2 tcp 0 0 0.0.0.0:8081 0.0.0.0:* LISTEN 3165/apache2 tcp 0 0 0.0.0.0:8082 0.0.0.0:* LISTEN 3165/apache2 I have not configured anything configured for port 8080 It seems to me like apache2 is not listening on port 8083 for connections when it should be. When I run sudo less /var/log/apache2/app3-err.log I get: [Mon Dec 14 13:11:14.326120 2020] [wsgi:info] [pid 3168:tid 140698250652736] mod_wsgi (pid=3168): Attach interpreter ''. [Mon Dec 14 13:11:14.342745 2020] [wsgi:info] [pid 3168:tid 140698250652736] mod_wsgi (pid=3168): Adding '/path/to/app3' to path. app3-access.log is empty /var/log/apache2/error.log has the following: … -
How to import cache setup into views.py
I have a seperate code for cache creation in another file in my project directory... authentication.py caches_folder = "./.spotify_caches/" if not os.path.exists(caches_folder): os.makedirs(caches_folder) def session_cache_path(): return caches_folder + request.session.get("uuid") oauth = SpotifyOAuth( redirect_uri="http://127.0.0.1:8000/spotify/authorize", scope='user-library-read', show_dialog=True, cache_path=session_cache_path() ) So I am trying to use the oauth in views.py by importing from .authentication import oauth views.py def login(request): if not request.session.get("uuid"): request.session["uuid"] = str(uuid.uuid4()) authorize_url = oauth.get_authorize_url() return redirect(authorize_url) ERROR : return caches_folder + request.session.get("uuid") NameError: name 'request' is not defined I reckon it is because request.session.get("uuid") is defined outside a view but I do not want to be creating oauth in separate views all the time. How do I manage this best? edit: def session_cache_path(uu_id): return caches_folder + uu_id oauth = SpotifyOAuth( redirect_uri="http://127.0.0.1:8000/spotify/authorize", scope='user-library-read', show_dialog=True, cache_path=session_cache_path(uu_id) ) -
how to filter on a field from another Model in nested Serializer
I have the following 3 models (third model Shop not important). There are shops, products, and shopitems (which shop has which item and at which price they offer it). class Product(models.Model): name=models.CharField(max_length=100) class Shopitem(models.Model): product = models.ForeignKey(Product, related_name='shopitems', on_delete=models.CASCADE) price=models.IntegerField() #shop field is not important to my question shop = models.ForeignKey(Shop, related_name='shopitems', on_delete=models.CASCADE) In my ProductSerializer, I made a nested serializer to ShopItemSerialzer, which works great. But how can I get list of all products, which are filtered by the shopitem price? And most importantly, the price is a query parameter, which I will get in my get_queryset() in the viewset, with the GET request 127.0.0.1/?price=500. Similar questions are asked a lot on stackoverflow, but none of them sadly didn't solve it for me. One solution I saw was to add this function to my Product model, and call it from the serializer: class Product(models.Model): name=models.CharField(max_length=100) def some_function(self): return ShopItem.objects.filter(product=self, price__gt=340) class ProductSerializer(serializers.ModelSerializer): shopitems=ShopItemSerializer(many=True, read_only=True,source="some_function") And this works good, but not great. The value 340 that I filter on the price must be hard coded into that function. How can I pass any parameter to it, that I get with self.request.query_params['price'], to this some_function? I also saw other solutions, that … -
Why Django doesn't find a modules which PyCharm finds well?
I tries to build my first Django project. I've created 'superlist' project and 'lists' app inside. My project tree: pycharm_project_folder | superlist | lists superlist manage.py ... | venv My lists/views.py: from django.shortcuts import render def home_page(): """home page""" pass My superlist/urls.py from django.urls import path from superlist.lists import views urlpatterns = [ path('/', views.home_page, name='home') # path('admin/', admin.site.urls), ] My lists/test.py from django.test import TestCase from django.urls import resolve from superlist.lists.views import home_page class HomePageTest(TestCase): """тест домашней страницы""" def test_root_url_resolves_to_home_page_view(self): """корневой url преобразуется в представление домашней страницы""" found = resolve('/') self.assertEqual(found.func, home_page) So, when I run python3 manage.py test I see ModuleNotFoundError: No module named 'superlist.lists' I don't understad why I got it because paths were suggested by PyCharm -
Django passing argument missing ) javascript
I'm having a trouble why this keep telling me Uncaught SyntaxError: missing ) after argument list I have a list and I want to retrieve it through passing into javascript. Is there anyone know what's the problem? Please give me some help. This is what it looks like: views.py: def sample(request): getlist = request.POST.getlist('batch[]') format = {'list': getlist} return render(request,'sample.html', format) sample.html: {% if list %} <button type="button" id="reports_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" onClick = "reports('{{list}}')" >sample</button> {% endif %} javascript: function reports (list) { console.log(list) } Updated my function views.py: @login_required(login_url='log_permission') def sap_payroll(request): classifications = Person.objects.all().values('classification').distinct() category = Person.objects.all().values('category').distinct() payroll_batch = Person.objects.all().values('payroll_batch').distinct() batch_it = Person.objects.all().values('batch_it').distinct() paid = Person.objects.all().values('paid').distinct() type_payout = Person.objects.all().values('type_payout').distinct() paid_with = Person.objects.all().values('paid_by').distinct() province = request.POST.get('province', False) municipality = request.POST.get('municipality', False) barangay = request.POST.get('barangay', False) payout_type = request.POST.get('type_payout', False) status = request.POST.get('stats', False) dte_from = request.POST.get('dte_from', None) dte_to = request.POST.get('dte_to', None) getlist = request.POST.getlist('batch[]') if request.method=='POST': shes = ['1','2'] # sample testing print("doda") print(type_payout) if getlist and dte_from and dte_to : user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to] , payroll_batch__in = getlist ) bene = UserFilter(request.POST, queryset=user_list) elif getlist: user_list = Person.objects.filter(payroll_batch__in = getlist) bene = UserFilter(request.POST, queryset=user_list) elif dte_from and dte_to: user_list = Person.objects.filter(date_receive__range=[dte_from, dte_to]) bene = UserFilter(request.POST, … -
Django translation redirect back to the current page
How to redirect back to the current page. In my site I'm implementing two language which is 'en' and 'fa' right now It's working but doesn't redirect to current page like docs.djangoproject.com we have instead it redirect me to home 'localhost:8000/fa/' or /en here is the code: for template hearders.py <li class="dropdown default-dropdown"> <form action="{% url 'selectlanguage' %}" method="POST">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="{% trans 'Go' %}"> </form> </li> code for urls.py is: path('selectlanguage', views.selectlanguage, name='selectlanguage'), and for views.py is: def selectlanguage(request): if request.method == 'POST': # check post cur_language = translation.get_language() lasturl= request.META.get('HTTP_REFERER') lang = request.POST['language'] translation.activate(lang) request.session[translation.LANGUAGE_SESSION_KEY]=lang #return HttpResponse(lang) return HttpResponseRedirect(lang) -
Django - Select a specific pk at a view where multiple pk's are available
I'm currently building a support page where people can open each ticket as a box. Problem now is that I need to seperate the pk for each opened suppot ticket where people can reply on as I have everything on a single page and a single view and a single form but with multiple pk's, as all support tickets of the user are getting displayed: def support(request, pk=None): template = 'App_Support/support.html' form = SupportTicketMessagesForm() if request.method == "POST": support_ticket = get_object_or_404(SupportTickets, pk=pk) form = SupportTicketMessagesForm(request.POST) if form.is_valid(): support_ticket_reply = form.save(commit=False) support_ticket_reply.author = request.user support_ticket_reply.content_object = support_ticket support_ticket_reply.save() messages.success(request, 'Reply has been added successfully') return redirect('support') else: messages.error(request, 'Something went wrong') return redirect('support') else: list_support_tickets = sorted( chain( SupportTickets.objects.filter(requester=request.user, status=0) ), key=attrgetter('creation_date'), reverse=True ) paginator = Paginator(list_support_tickets, 10) page = request.GET.get('page') support_tickets = paginator.get_page(page) args = {'support_tickets': support_tickets, 'form': form } return render(request, template, args) My problem is at the following two lines: support_ticket = get_object_or_404(SupportTickets, pk=pk) support_ticket_reply.content_object = support_ticket As I'm unable to properly access the pk of just one object/Support Ticket, as in this view I only have multiple pk's I can potentially reply onto. So how to select? In addition, please also see my models.py logic: referential_models = … -
How do I show checkbox value checked if it already exists in Database?
If user checks Orange and banana then save it. The value Orange and Banana will be stored in Database(Postgresql). Now when I open the checklist page(As shown In the image),Checkbox Orange and banana should be checked and Kiwi, Apple and Grapes should be unchecked Here is models.py class details(models.Model): name = models.CharField(max_length = 20) class savedata(models.Model): checked_value = models.CharField(max_length=50) Here is views.py def choice(request): list = details.objects.values('name') done = savedata.objects.get(pk = 16) temp = done.checked_value print(list) print(done) print(temp) if request.method == "POST": data = savedata() data.checked_value = request.POST.get('checked_values') data.save() return render(request, 'choice.html',{'list':list,'data':data,'done':done,'temp':temp}) else: return render(request, 'choice.html',{'list':list,'done':done,'temp':temp}) When I print list I get: <QuerySet [{'name': 'Orange'}, {'name': 'Kiwi'}, {'name': 'Banana'}, {'name': 'Apple'}, {'name': 'Grapes'}]> When I print done I get: savedata object (16) When I print temp I get: Orange, Banana Here is Django Template choice.html {% for l in list %} {%if temp in list.name %} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}" checked> {{l.name}}<br /> {%else%} <input style="font-weight: bold;display:inline-block;" type="checkbox" class="chkcvalues" name="ip" value="{{l.name}}"> {{l.name}}<br /> {%endif%} {% endfor %} <input type="text" name="checked_values" id="txtvalues" /> <button id="but1" type="submit" class="save"> Save</button> <a id="but2" type="submit" class="home" href="{% url 'fruit' %}"> Home</a> The problem with this code is it always goes into else … -
django form choicefield update after every query
i have created a webapp. this is how it works user inputs a number mapped with a product csv file corresponding to that product gets downloaded you are presented with a form which contains one property name along with choices available for that property issue i am facing is, this whole process works for first search only after that whenever user enters any different number for any other product ideally choicefield in the form should get updated, but it dont get updated, i have deployed this app on heroku,if i restart all dynos this fixes the problem but just for time being. i mean for only one search, again same problem happens link to the app: https://abcd4.herokuapp.com/ link to the code: https://drive.google.com/drive/folders/1zlKowvcpK5NOnmAZFstDPC1oWTH97WmX?usp=sharing problem is not about the deployed platform i.e heroku i faced same issue when i ran app on localhost on localhost also restarting app solved the problem forms2.py from django import forms from django.core import validators def mergefunction(s1,s2): merged = [] for i in range(0, len(s1)): tup = (s1[i],s2[i]) merged.append(tup) return merged class GeeksForm(forms.Form): import csv import pandas as pd filename = r"downloaded1.csv" data = open(filename, encoding = "utf8") csv_data = csv.reader(data) data_lines = list(csv_data) total_row = (len(data_lines)) … -
How to use reverse filtering and removing duplicates in annotate using Django ORM
Hello I am having flowing model structure class TestModelA(AuditFields, Model): id = models.AutoField(primary_key=True) modelb = models.ForeignKey( TestModelB, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelB(AuditFields, Model): id = models.AutoField(primary_key=True) modelc = models.ForeignKey( TestModelC, on_delete=models.SET_NULL, blank=True, null=True ) class TestModelC(AuditFields, Model): id = models.AutoField(primary_key=True) value = models.charfield(max_length=255, blank=True) I'm making a query like this qs = TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct() Later some other filters applied to this initial queryset "qs" For that I am having another model class TestModelD(AuditFields, Model): id = models.AutoField(primary_key=True) modela = models.ForeignKey( TestModelA, on_delete=models.SET_NULL, blank=True, null=True, related_name="associated_modela") rating = models.charfield(max_length=255, blank=True) Then this is out new qs qs = (TestModelA.objects.values('modelb__modelc__value').annotate( count=Count('modelb__modelc__value'), ).distinct()).filter(associated_modela__rating = 'Sample') But the issue is that if two TestModelD objects under a single TestModelA object , it duplicating In the above scenario (if two TestModelD objects under a single TestModelA object) Currently I am getting output like this <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 2}]> But my expected output is <SoftDeletionQuerySet [{'modelb__modelc__value': 'Large', 'count': 1}]> -
Transfer Class-based view to another
I created a DetailView class that can receive links from categories or posts from a website. In the “get_object ()” method, I identify if it is Category or Post models (by url slug). The URLs for this class are listed below: /category/ /category/subcategory/ /category/post/ /category/subcategory/post/ The class got too long because the categories and posts have specific behaviors. I was wondering if it is possible to "transfer" one class to another to handle specific information? For example: GenericView redirect to CategoryView after identifying that it is the url: / category / or for PostView, if it is / category / post / NOTE: I am transferring the Wordpress site to Django, so I cannot change the url structure. Is there any way to do this? Do you suggest another better solution? -
how to overwrite dj_rest_auth registration package on django rest project
I'm creating a full stack app using django rest + react. (backend) config.urls sign up path path('accounts/signup/', include('dj_rest_auth.registration.urls')), i need to overwrite the package so i can sign up using: password + password_confirm instead of the built in password1 + password2 Hopefully someone will know how to do it -
How to pull a Serializer object into def create() function separately?
class ArticleCreateSerializer(serializers.ModelSerializer): images_set = ArticleImagesViewSerializer(source='images',required=False,many=True) tags_set = ArticleTagViewSerializer(source='posttags',required=False,many=True) class Meta: model = Article fields = ('images_set','tags_set','id') def create(self,validated_data): images = self.context['request'].FILES.getlist('images_set') articleinit = Article.objects.create(**validated_data) tags = validated_data.pop('tags_set', None) for imageinit in list(images): m2 = ArticleImages(article=articleinit , image= imageinit ) m2.save() for taginit in list(tags): m3 = ArticleTags(article=articleinit , tag = taginit ) m3.save() return articleinit I am trying to post request array of tags and I have to pull them into create function separately for obvious reasons, I have to work them one by one in another serializer. My only request here is that how can U pull them correctly?This code does not work as intended(it pulls data as null value): tags = validated_data.pop('tags_set', None) Does anybody have a clue? -
How do set default values in django for an HttpRequest.POST?
how can i set a default value If the field is not sent?! for example my code: class SampleViewSet(ParentListAPIView): def post(self, request, *args, **kwargs): _email = self.request.data['email'] -
Issue with Paginiation
I am quite new to python/django and I am following CoreyMSchafer's youtube tutorials. However, when trying to get pagination to work it displays the elif command on the webpage itself and doesn't render it server side.elif code being displayed home.html {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add: '3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a> {% endif %} {% endif %} {% endblock content %} -
count likes in ManyToManyField - django rest framework
in models.py: class Post(models.Model): body = models.TextField(max_length=10000) date = models.DateTimeField(auto_now_add=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by') class Meta: ordering = ['-date'] in serializers.py: class PostSerializer(serializers.ModelSerializer): user = UserSerializers() class Meta: model = Post fields = ('body','date','user') how to count likes of a single post? and also show which user liked the post. -
Digitalocean spaces too slow to upload even from the droplet of same region
I am using django-storages to upload my static and media files to digital-ocean spaces. Problem is it was really slow. All of the sudden, requests started becoming too slow. Then I started debugging with django-silk, and found that boto3 function was taking too much time. then inside the droplet itself, I tried to upload the s3cmd function. truncate -s 20M sample_file.txt #created a 20 mb file s3cmd put sample_file.txt s3://disbug-media The output was upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 1 of 2, 15MB] [1 of 1] 15728640 of 15728640 100% in 26s 584.56 KB/s done upload: 'sample_file.txt' -> 's3://disbug-media/sample_file.txt' [part 2 of 2, 5MB] [1 of 1] 5242880 of 5242880 100% in 41s 123.58 KB/s done The 15mb part upload took 26 seconds and 5MB part took 41s 😱. My droplet and the spaces are in the same region. Is there anyway I could speedup the upload ? Or is this performance issue common in digitalocean spaces. I am really starting to regret for choosing DO as my infrastructure 😭. -
web developpement in python [closed]
I have a project where I need to build a website that keeps track of orders. The client just needs to enter the order number and it gives him the information that I want. I used python Django to build the website and request to get the data (API) I don't know how I can display the different orders. If you have an example of something similar or advice, please send it to me. Thanks -
Django Flask - Exception happened during processing of request
I'm getting this issue when I'm communicating with my app. At present I'm using flask and it is running on my local port. Here is the code which causes the first error: def _handle_request_noblock(self): """Handle one request, without blocking. I assume that selector.select() has returned that the socket is readable before this function was called, so there should be no risk of blocking in get_request(). """ try: request, client_address = self.get_request() except OSError: return if self.verify_request(request, client_address): try: self.process_request(request, client_address)(#error occuring at this line) except Exception: self.handle_error(request, client_address) self.shutdown_request(request) except: self.shutdown_request(request) raise else: self.shutdown_request(request) 2nd error: def process_request(self, request, client_address): """Call finish_request. Overridden by ForkingMixIn and ThreadingMixIn. """ self.finish_request(request, client_address)(#error occuring at this line) self.shutdown_request(request) 3rd error: def __init__(self, *args, directory=None, **kwargs): if directory is None: directory = os.getcwd() self.directory = directory super().__init__(*args, **kwargs) #error at this line when I start communicating with the app it is showing error 503 the following error in the console: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 316, in _handle_request_noblock self.process_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 347, in process_request self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/server.py", line 647, in __init__ super().__init__(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ … -
Django AllAuth does not extend 'base.html', despite base.html existing in templates
base.html works for all other url links, but as soon as I load localhost:8000/accounts/ (e.g. logout or login), the css template does not work at all. The functionality still works, it's just the css that isn't working. This is as per the tutorial (From 8:22 to 10:44): https://www.youtube.com/watch?v=bopkZBbIa7c. I have followed the tutorial step by step, yet it gives a different result than the tutorial. (Just want to reiterate the functionality is fine, just plain django css) My current settings.py is: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tinymce', 'posts', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', ] Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog, name='post_list'), path('post/<id>', post, name = 'post_detail'), path('search/', search, name = 'search'), path('tinymce/', include('tinymce.urls')), path('accounts/', include('allauth.urls')), path('accounts/profile/', blog, name='post_list') ] Any help would be appreciated. Thanks. Django version 3.1.4 Python 3 -
NoReverseMatch Error in Django when mapping items
I am trying to map different items using the pk(primary key). I have used it in my urls.py, views.py as well as the templates file. But I am a NoReverseMatch Error. I have also tried changing the str to int in the urls.py file but it still gave the same error. I hope I could get someone to kindly help. Thanks error log Environment: Request Method: GET Request URL: http://localhost:8000/update-reservation/1/ Django Version: 3.1.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'dashboard', 'widget_tweaks', 'phonenumber_field'] Installed 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'] Template error: In template C:\Users\Habib\Documents\django\FIVERR\adam_mailk\templates\dashboard\super\admin\base.html, error at line 41 Reverse for 'updatebar' with keyword arguments '{'updatebar': ''}' not found. 1 pattern(s) tried: ['updatebar/(?P<pk>[^/]+)/$'] 31 : <aside class="left-panel"> 32 : <div class="logo"> 33 : <a href="{% url 'dashboard' %}" class="logo-expanded"> 34 : <img src="{% static 'logo.png' %}" style="background-color: white; width: 140px; height: 65px;" alt="logo"> 35 : </a> 36 : </div> 37 : <nav class="navigation"> 38 : <ul class="list-unstyled"> 39 : <li {% if request.path == '/dashboard/' %} class="active" {% endif %}><a href="{% url 'dashboard' %}"><i class="ion-home"></i> <span class="nav-label">Dashboard</span></a> 40 : </li> 41 : <li {% if request.path == '/updatebar/' %}class="active"{% endif %}><a href=" {% … -
.sql to ER diagram
i am trying to create a er diagram from a .sql file which was originally a sqlite file PLEASE HELP!!!! i tried to create an ER Diagram in mysql workbench but i got these errors PLEASE HELP!!!! PLEASE HELP!!!! PLEASE HELP!!!! ERROR: (1, 27) "django_migrations" is not valid at this position for this server version, expecting a new table name ERROR: (1, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (1, 1) "app" is not valid at this position for this server version, expecting an identifier ERROR: (1, 20) "NOT" is not valid at this position, expecting EOF, ';' ERROR: (8, 27) "auth_group_permissions" is not valid at this position for this server version, expecting a new table name ERROR: (8, 1) "id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "group_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 1) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 13) "permission_id" is not valid at this position for this server version, expecting an identifier ERROR: (8, 41) "auth_permission" is not … -
convert django url with '|' (or) regex to modern Django path
I have a question regarding conversion of pre - Django 2 urls to path If I have an url like this: url( r'^some_path/(?P<type>type_one|type_two)/', views.SomeViewHere.as_view(), name='important_name', ), Question is how to convert this url to modern Django path keeping same functionality and keeping same name? Important aspect: kwargs type_one and type_two should be passed into view. Name parameter can’t be changed or split. What I have done: path('some_path/', include( [ path('type_one/', views.SomeViewHere.as_view(), kwargs={'type': 'type_one'}), path('type_two/', views.SomeViewHere.as_view(), kwargs={'type': 'type_two'}), ] ), name='important_name', ), But reverce doesn’t work with this configuration Thank you. ps. type is a string -
Django_filters and apache2 500 internal server Error
I'm try to use Django_filters for filtering in my app and use apache2 , so after I install Django_filters using below documentation https://django-filter.readthedocs.io/en/stable/guide/install.html then add INSTALLED_APPS = [ 'django_filters', ] the app crash and return 500 internal server error ,then try to update ubuntu and apache2 , nothing is change so what is the solution for it ?