Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django csv upload trough FormView or CreateView
So, I try to upload a csv with a name and an emailaddress to populate my voting app and I am really stuck. There are options around, but none of them actually use a CBV to do it (as it seems). I am sure it can be done, but I can't figure out how. The main purpose is to upload the data from the csv and add the details to the database. This is what I tried: Option 1: def form_valid(self, form, **kwargs): formfile = csv.DictReader(self.request.FILES['file'].read().decode("utf-8")) print(formfile) try: for row in dictreader: print(row) field = row.split(";") print(field[1]) except Exception as e: print("buggedy bug in dictreader") return super().form_valid(form) This throws the exception and the print(formfile) gives OrderedDict([('user1@usedmail.com', ';')]) Option 2: def form_valid(self, form, **kwargs): formfile = self.request.FILES['file'].read() dictreader = csv.DictReader(formfile) print(dictreader) try: for row in reader: print(row) field = row.split(";") print(field[0]) except Exception as e: print('buggedy bug in reader') return super().form_valid(form) The print command prints <_csv.reader object at 0x0000020048B4E388> and it throws the exception. Options 3: def form_valid(self, form, **kwargs): csv_load = self.request.FILES['file'].read() print("csv is read") print(csv_load) csv_file = csv.reader(csv_load) print(csv_file) num = csv_file.replace('\r','').replace('b','').replace("'",'') print("stuff is replaced") for line in num: print(line) print("line is printed") field = line.split(";") print(field[0]) return super().form_valid(form) … -
Why is my Django custom form field's to_python() not working?
Fairly new to Django and I've been struggling with this problem for a bit now. I'm trying to create a custom form field that inherits from CharField. I want it to process input from a form so that double spaces in strings are replaced with single spaces. However, it seems that the custom form's to_python() is never called because whenever I input something like 'a a' in the form, the double spaces still make it through to the database. I've also noticed that the input is properly stripped as if CharField.to_python is still being called. My understanding is that to_python() is called whenever form.is_valid() is called. I'm not sure if I've done that properly in the form view. Here is the custom field: class NameField(forms.CharField): def to_python(self, value): """ Remove extra spaces in input. """ if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if ' ' in value: value = value.replace(' ', ' ') if value in self.empty_values: return self.empty_value return value The form: class ProductForm(forms.Form): name = NameField() quantity = forms.IntegerField(validators=[MinValueValidator(0)]) cost = forms.DecimalField( max_digits=5, decimal_places=2, validators=[MinValueValidator(0.0)], ) _quality = models.DecimalField( blank=True, default=0.0, max_digits=2, decimal_places=1, validators=[MinValueValidator(0.0), MaxValueValidator(5.0)] ) And the view: def form(request): product_form_set … -
Django Protected View Based On If Model Has Object + Specific User Access
This is a bit more theoretical as I'm not fully decided yet on the best way for this to be done. Part 1 A user can create portfolios and link posts to these portfolios. If a portfolio is set to private then only the user should be able to see the post. Since a post can have more than 1 portfolio, if ANY of those linked portfolios is set to private the post will not be accessible to the public. Ideally, where would this be done - In the template or view? How would the code there look like? This should be ready to integrate with Part 2 Part 2 I need a user to be able to have the ability to add other users to a portfolio. That way if a user is logged into the app they can still view the post if the portfolio owner added their name to the list of users who "have access" to the private portfolio. What would be the best way to implement this? I'm guessing I'd possibly need another class and or field inside the Portfolio class. models.py class Portfolio(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=20) description = models.CharField(max_length=250, blank=True, … -
How to get name(database field) from primary key when using django and react-redux?
I have created a list in Django using react-redux and Django rest framework. I just want to replace id with the name for users. I want to run a query or REST API to get the name from primary key. Any way to accomplish this would be appreciated. -
autofit column width using xlswriter || Django
I am generating excel in my Django views.py but since column names are a bit long, I am having a hard time to set auto column fit width manually every time I/user downloads the excel. Below is my working code snippet for excel generation using xlswriter. def excel(request): ans = request.POST.getlist('ans[]') ans_final=[] rows = request.POST.get('rows') for each_ele in ans: each_ele = each_ele.split('.') each_ele[0] = each_ele[0][:-2] each_ele[1] = each_ele[1][:-2] fin = each_ele[0]+' - '+each_ele[1] ans_final.append(fin) workbook = xlsxwriter.Workbook('/home/Desktop/status.xlsx') worksheet = workbook.add_worksheet('Test_Data') bold = workbook.add_format({'bold': True}) for i in range(len(ans_final)): worksheet.write(0, i,ans_final[i],bold) row_index=1 row_count = int(rows) while(row_count): col_index=0 for each_ele in ans: worksheet.write(row_index, col_index, eval(each_ele)) col_index += 1 row_index += 1 row_count -= 1 workbook.close() return JsonResponse({'ok':'ok'}) Please suggest a work around for setting Auto-fit column width in the above code. -
Django - NoReverseMatch no arguments not found at create view when initializing form
I'm trying to initialize a form with some data passed as parameters. I have already in the Model the get_absolute_url but I don´t believe the error is going that way, here is the traceback: Traceback (most recent call last): File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\loader_tags.py", line 62, in render result = block.nodelist.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\base.py", line 903, in render_annotated return self.render(context) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\template\defaulttags.py", line 443, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\urls\base.py", line … -
Django 404 error when loading static files in debug false
I try everthing but i cant find solution. My Django app is cant find .css .js and media images. All files giving 404 error My settings file; BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') My url file; urlpatterns = [ path('admin/', admin.site.urls), path('ckeditor/', include('ckeditor_uploader.urls')), path('', include("wallpapers.urls")), path('', views.index, name="index"), path('search/', views.search, name="search"), path('wallpapers/<slug:slug>/', views.tagged, name="tagged"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my base.html; <head> {% load static %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>{% block title %}title {% endblock %}</title> <meta name="description" content="{% block description %} {% endblock %}"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=11"/> <link rel="shortcut icon" href="{% static 'img/favicon.ico' %}"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Quicksand&display=swap" rel="stylesheet"> <link href="{% static 'css/style.css' %}" rel="stylesheet" > <script src="{% static 'js/custom.js' %}"></script> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </head> im using pycharm ide and django 3.0.3 when i turn debug = true everthing going fine... -
Django - user.userprofile.image
I have a serializer that looks like this: class CommentSerializer(serializers.ModelSerializer): user = SerializerMethodField() image = SerializerMethodField() class Meta: model = Comment fields = [ 'user', 'content', 'timestamp', 'image' ] def get_user(self,obj): return str(obj.user.username) def get_image(self,obj): return str(obj.user.userprofile.image) But I get this error: AttributeError at /posts/Post1/view/\n'User' object has no attribute 'userprofile' This is the UserProfile: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) # user.profile image = models.ImageField(upload_to=upload_image_path,null=True,blank=True, default="False") username = models.CharField(max_length=200,blank=True) objects = UserProfileManager() How can I access the userprofile from the comment user in this case? Thank you -
Bootstrap JS dynamic tabs- every nav-link change the same element
I'm trying to create list of dynamic cards. I've almost finished but one problem appear. When I change links on last object nav-links works fine, but when i want to change another objects, the same last object changes. HTML {% extends "post/base.html" %} {% block title %} <title>Home Page</title> {% endblock title %} {% block content %} {% for obj in EveryPost %} <div class="card text-center"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="PL-tab" data-toggle="tab" href="#PL" role="tab" aria-controls="PL" aria-selected="true">PL</a> </li> <li class="nav-item"> <a class="nav-link" id="RU-tab" data-toggle="tab" href="#RU" role="tab" aria-controls="RU" aria-selected="false">RU</a> </li> </ul> </div> <div class="card-body tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="PL" role="tabpanel" aria-labelledby="PL-tab"> <h5 class="card-title"><a href="{% url 'detailpost' obj.pk %}">{{ obj.title_pl }}</a></h5> <p class="card-text">{{ obj.text_pl|truncatechars:350 }}</p> <a href="{% url 'detailpost' obj.pk %}" class="btn btn-dark float-right">Zobacz całość</a></div> <div class="tab-pane fade" id="RU" role="tabpanel" aria-labelledby="RU-tab"> <h5 class="card-title"><a href="{% url 'detailpost' obj.pk %}">{{ obj.title_ru }}</a></h5> <p class="card-text">{{ obj.text_ru|truncatechars:350 }}</p> <a href="{% url 'detailpost' obj.pk %}" class="btn btn-dark float-right">Zobacz całość</a></div> </div> <div class="card-footer text-muted"> <span class="float-left">{{ obj.date|date:"d M y" }}</span> <span class="float-right">Przesłane przez: {{ obj.User }}</span> </div> </div> {% endfor %} {% endblock content %} -
How to make Django model to make a JSON Field in MySQL and store Json Data?
I am using Quill Rich Text editor which produces a JSON object and i want to store all the info of the editor in a MySQL data base. The Code that generates this object and i am checking the data type of the data which comes out to be object type. var draft = quill.getContents(); console.log(draft); console.log(typeof draft); and here is another screenshot that shows how the object changes which change in the data in Editor. I want to save this data object in the database and i want to make model fields in the Django Models to implement the same in MySQL. I found that https://dev.mysql.com/doc/refman/8.0/en/json.html ,MySQL already have a JSON data type but i am not able to use this info to my advantage. -
how to exclude the django libraries from coverage
Learning django as a part of it developing an app with TDD approach, after going through many internet pages I have chosen unittest for testing and coverage library to know the test covered. The problem is after executing the coverage run and generating the html report, it created a htmlcov folder in which I see it included the test coverage for all the django libraries too.. which is overwhelming for me to look into the folder and search for the test results of my app results. I have installed the coverage as per the docs $ pip install coverage and executed this command $ coverage run manage.py test -v 2 then generated the html report $ coverage html which resulted in 423 items of html pages How I can overcome this, I could see online tutorial using the pytest to generate nice reports but it is not possible when using unittest and coverage.. tried below options too.. 2) $ coverage run -m unittest discover && coverage report $ coverage html 3) $ coverage run manage.py unittest feed, users $ coverage html same result, how can I get the desired files which includes only my project and it's app files (models, … -
Link to stylesheets in django template
I am working on a large Django site and am currently adding the html templates. this is the file tree for the main part C:. +---forums | | admin.py etc | | | +---migrations | | | ... | | | +---templates | | \---forums | | help-style.css | | help.html | | home-style.css | | home.html I have been using <link rel="stylesheet" type="text/css" href="home-style.css"> to link to the stylesheet byt when i do it results in this error Not Found: /forums/home-style.css [22/Feb/2020 07:38:14] "GET /forums/home-style.css HTTP/1.1" 404 2702 I have tried using {% static 'home-style.css' %} and {% load staticfiles %} but they didn't work Thanks in advance! -
wagtail longclaw Reverse for 'longclaw_basket' not found. 'longclaw_basket' is not a valid view function or pattern name
When i start longclaw demo from GitHub I get this error. ALso with my local project I get this error. Wat does it Mean? What do I need to change? Stacktrace below NoReverseMatch at /microbit/producten/ Reverse for 'longclaw_basket' not found. 'longclaw_basket' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/microbit/producten/ Django Version: 3.0.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'longclaw_basket' not found. 'longclaw_basket' is not a valid view function or pattern name. Exception Location: /Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 Python Executable: /Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/bin/python3 Python Version: 3.6.7 Python Path: ['/Users/timvogt/Software_projects/Backend/longclaw_demo', '/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python36.zip', '/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6', '/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_venv/lib/python3.6/site-packages'] Server time: Fri, 21 Feb 2020 16:25:14 +0000 Error during template rendering In template /Users/timvogt/Software_projects/Backend/longclaw_demo/longclaw_bakery/templates/base.html, error at line 34 Reverse for 'longclaw_basket' not found. 'longclaw_basket' is not a valid view function or pattern name. 24 <div class="layout"> 25 {% wagtailuserbar %} 26 <div class="header"> 27 <div> 28 <a href="/products">Products</a> 29 </div> 30 <div> 31 <a class="header-brand" href="/">Longclaw Bakery</a> 32 </div> 33 <div> 34 <a href="{% url 'longclaw_basket' %}"><span id="basket-item-count"> </span><i class="fas fa-shopping-basket fa-lg" aria-hidden="true"></i></a> 35 </div> 36 </div> 37 38 <div class="main"> 39 {% block content %}{% endblock %} 40 </div> 41 </div> 42 43 {# Global javascript #} 44 … -
Django Pass parameters to Form, getting KeyError
I'm trying to pass two parameters to initialize my form, I have tried different ways to achieve this but I get the same error over an over, this is the error that I'm getting (Traceback): Traceback (most recent call last): File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 168, in get return super().get(request, *args, **kwargs) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\jorge.lopez\.virtualenvs\Carros-ZVuxKBiy\lib\site-packages\django\views\generic\edit.py", line 33, in get_form return form_class(**self.get_form_kwargs()) File "C:\Users\jorge.lopez\Documents\Personal\Carros\carros\AC\forms.py", line 100, in __init__ self.carro = kwargs.pop('carro') Exception Type: KeyError at /payments/addtoexistingweek/1/2020-W07 Exception Value: 'carro' urls.py path('payments/addtoexistingweek/<int:carro>/<slug:semana>', views.AgregarPagoSemana.as_view(), name='pagoaexistente'), views.py class AgregarPagoSemana(CreateView): template_name = "AC/add_paymentexistingweek.html" model = Pagos form_class = AgregarPagoTransaccionExistente forms.py class AgregarPagoTransaccionExistente(forms.ModelForm): def __init__(self, *args, **kwargs): self.carro = kwargs.pop('carro') self.semana = kwargs.pop('semana') super(AgregarPagoTransaccionExistente, self).__init__(*args, **kwargs) class Meta: model = Pagos fields = ('carro', 'pago', 'fecha', 'semana', 'renta') widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}), 'semana': forms.DateInput(attrs={'type': 'week'}) } I don´t know if I'm … -
Django API TypeError: string indices must be integers, not str
I'm writing an API to save data to a model and am currently dealing with the error that string indices must be integers, not str. I've looked online for solutions, including the many questions on this site regarding this error, and have not found a solution so far. I've included a try-except statement in my code for now because the server just says the error is internal and the try-except provides a little more insight into why the code is erroring out. I've double-checked and am fairly certain that my castings are correct. I've included my code below. Any suggestions are appreciated. views.py def send_data(request): API_ENDPOINT = "http://127.0.0.1:8000/data" my_dict = { 'eventtransactions_id': 0000111, 'profitcenter_id': 7, 'customer_gender': 'F', 'customer_firstname': 'Jan', 'customer_lastname': 'Smith', 'actualdatetime': "02-15-2020 18:54:58", 'custnum': 8880005643, 'birthdate': "02-15-2000 18:54:58", 'membertype': 'Student', 'eventname': 'Location', },{ 'eventtransactions_id': 1234567, 'profitcenter_id': 7, 'customer_gender': 'M', 'customer_firstname': 'Joe', 'customer_lastname': 'Smith', 'actualdatetime': "02-15-2020 18:54:58", 'custnum': 8880005643, 'birthdate': "07-15-1999 18:54:58", 'membertype': 'Student', 'eventname': 'Location', } json_dict = json.dumps(my_dict) requests.post(API_ENDPOINT, data=json_dict) return HttpResponse("I'm broken.") @csrf_exempt def receive_data(request): if request.method == 'POST': my_data = request.body data = json.loads(my_data) json_data = json.dumps(data) try: new_swipe = FitnessCenterSwipe.objects.create( profitcenter_id= int(json_data['profitcenter_id']), eventtransactions_id= int(json_data['eventtransactions_id']), custnum= int(json_data['custnum']), customer_lastname= json_data['customer_lastname'], customer_firstname= json_data['customer_firstname'], actualdatetime= datetime.datetime.strptime(json_data['actualdatetime'], '%m-%d-%Y %H:%M:%S'), eventname= … -
Materialize Card Makes Image Full Width
I set up a django project to try out materialize. I followed the CDN set up example from the materialize site and added a horizontal card using their example as well. The image I used is 152x152px. The resulting page makes the image the full width of the screen (iMac) and displays the text below. I rooted around for example code and found that there is a container class, which is not metioned on the site that I could see. When I added that, the card image filled the full width of the container. I added a width to the image class. It had no effect. I add class="responsive-img" to the image. It also had no effect. Other than the standard Django framework, this is my entire site: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django Materialize Sandbox</title> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"> </script> </head> <body> <div class="container col s8"> <h1>It's a start</h1> <div class="col s12 m7"> <h2 class="header">Horizontal Card</h2> <div class="card horizontal"> <div class="card-image"> … -
Restricting url to group 'argument of type 'ManyRelatedManager' is not iterable'
I'm trying to restrict certain urls to only be accessible to certain groups. I have added my user to the staff group and have a view to check with user_passes_test if the user is in the staff group. However when I go to this url I get argument of type 'ManyRelatedManager' is not iterable views.py def in_staff_group(user): return 'Staff' in user.groups @login_required @user_passes_test(in_staff_group) def my_view(request): return render(request=request, template_name="main/template.html", context=context) -
My update view class based view is not working. How to fix this?
Whenever I click the update button, it does not takes me to the update page. But the create page is working fine. Here are the code snippets from my project. Please help me! I want to update my school values and i have created the corresponding files and views. Whenever I click the update button the url changes to /myapp/update/1 (where 1 is primary key) from /myapp/1/ , but the page content does not change. #models.py class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse('myapp:detail',kwargs={'pk':self.pk}) #views.py class SchoolUpdateView(UpdateView): fields = ('name','principal') model = models.School class SchoolCreateView(CreateView): fields = ('name','principal','location') model = models.School # urls.py from django.urls import path,re_path from myapp import views app_name = 'myapp' urlpatterns = [ path('create/',views.SchoolCreateView.as_view(),name='create'), re_path('update/(?P<pk>\d+)/', views.SchoolUpdateView.as_view(),name = 'update'), ] $school_detail.html {% extends 'myapp/basic_app_base.html' %} {% block body_block %} <div class="jumbotron"> <h1>Welcome to School Detail Page!</h1> <h2>School Details:</h2> <p>School Name : {{school_details.name}}</p> <p>Principal : {{school_details.principal}}</p> <p>Location : {{school_details.location}}</p> <h3>Students: </h3> {% for student in school_details.students.all %} <p>{{student.name}}</p> {% endfor %} </div> <div class="container"> <p><a class = 'btn btn-warning' href="{% url 'myapp:update' pk=school_details.pk %}">Update</a></p> </div> {% endblock %} #school_form.html {% extends 'myapp/basic_app_base.html' %} {% block body_block %} … -
How can i lock specific rows to load in django forms
I came across scenario where i need to lock a selected row for editing, considering that when the form loads an instance of the object is sent (GET) and when the object is edited an instance of the edited object is sent for further processing(POST). I need to make sure that there is no one able to load the edit form if it is being edited by someone else. I looked at select_for_update() method in Django but it didn't help since the transaction that wraps the view of the edit form finishes its execution once the form is loaded. Any ideas? -
Where is the distinction between a web application and an API?
This question is highly related to this over question. I'm asking another question between I still am a bit confused on the topic. The Issue I Ran Into I currently have a Django web application where users can have a list of their hobbies and can increment a counter each time they do one of their hobbies. My issue is, I want to extend this functionality outside of a front-end experience. In other words, I want users to be able to increment their hobbies using a POST request, say, from the terminal or from their own script or something. Where I'm Confused Do I have to create an API for my webapp to add this functionality? Another way to put is, do I have to handle requests coming from the front-end differently than requests coming from somewhere else? Would front-end requests go to the URL www.hostname.com/hobbies/1 and other requests go to the URL www.hostname.com/api/hobbies/1? If I do route the POST requests to the same URL as the requests coming from the front end (i.e. www.hostname.com/hobbies/1), then how come google has external APIs for Google Maps? It seems like if other web applications are calling Google Maps functionality then Google has … -
Django Session Cookie & Apache Restart Invalidating Cookies?
My django app works without issue with one strange caveat. Our settings are essentially basic, out of the box settings with nothing special. In our settings we recently added the following setting : SESSION_EXPIRE_AT_BROWSER_CLOSE (set to True) We noticed something odd however and I'm not sure if it's Apache that is doing this or Django - so I'm in need of some help. If I open a fresh browser that has never been to the site before - I can get logged into the admin. No worries (yet). I can see that the browser gets and sets the sessionid cookie (for my example we will say the value of that cookie is foo). I can see that in the django_session table the cookie is added there, too. The expire is set for 2 weeks out (default behavior). If I restart Apache and do a hard refresh on the browser, I can no longer access the /admin URL unless I delete the sessionid cookie in the browser. I can access the frontend of the site, and it recognizes that I've been logged in before and it works as expected - but I cannot get into the admin any longer. My questions … -
Configuring NGINX + uWSGI + Django in a multi-tenancy application
I have a single application in django hosted on AWS. But, in these days, I turned It into multi-tenancy, using django-tenant-schemas. Locally, It runs normally. I can create my tenants and access them on my local django server. However, I'm not getting to run on AWS. My .conf file for NGINX looks like this: upstream django { server unix:///home/ubuntu/folder_my_projct/mysite.sock; # for a file s$ } # configuration of the server server { listen 80; address or $ server_name ssh *.example.com.br; charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /media { alias /home/ubuntu/folder_my_projct/media; # your Django project's$ } location /static { alias /home/ubuntu/folder_my_projct/static; # your Django project's$ } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/ubuntu/folder_my_projct/uwsgi_params; # the uwsgi$ } } I did pull for my project that runs on AWS, everything worked in my Virtual Machine (makemigrations and migrate_schemas). However, when I try to access the subdomain, It doesn't work. My only change to access the subdomains was in the file above, pasting the * before the dot: * .example.com.br. I tried using regex, but it didn't work as too (server_name ~ ^ (? <subdomain>. +) … -
Why do I keep getting Sqllite: near % syntax error
I working on a website on my laptop and I keep getting this error when i move to another computer everything is fine enter image description here -
Filtering django model with input parameters from html template
I have a model in the below format model.py raccntname = models.TextField(max_length=100) raccntnum = models.TextField(max_length=100) rLMV = models.DecimalField(max_digits=10, decimal_places=2, null=True) rSMV = models.DecimalField(max_digits=10, decimal_places=2, null=True) rcash = models.DecimalField(max_digits=10, decimal_places=2, null=True) requity = models.DecimalField(max_digits=10, decimal_places=2, null=True) rLOMV = models.DecimalField(max_digits=10, decimal_places=2, null=True) rSOMV = models.DecimalField(max_digits=10, decimal_places=2, null=True) rhousereq = models.DecimalField(max_digits=10, decimal_places=2, null=True) rhouseexcess = models.DecimalField(max_digits=10, decimal_places=2, null=True) rregtexcess = models.DecimalField(max_digits=10, decimal_places=2, null=True) date = models.TextField(max_length=100) entity = models.TextField(max_length=100) I want to filter this model based on the selection from the below object lists forms.py class Datechoicefield(forms.Form): date = forms.ModelChoiceField( queryset= BNPPBMrgnDecmp.objects.values_list('date', flat=True).distinct(), initial='2/10/2020', empty_label = None, ) class entitychoicefield(forms.Form): entity = forms.ModelChoiceField( queryset= BNPPBMrgnDecmp.objects.values_list('entity', flat=True).distinct(), initial='VNI3', empty_label = None, ) html template <form method='GET' action="{% url 'update' %}"> {{ date_list }} {{ entity_list }} <input type='submit'> </form> The selections from the object list is passed into the view via the below view.py def myview(request): date_list = Datechoicefield() entity_list = entitychoicefield() if request.GET.get('date'): selected_date = request.GET.get('date') obj = BNPPBMrgnDecmp.objects.filter(date=selected_date) if request.GET.get('entity'): selected_entity = request.GET.get('entity') obj = BNPPBMrgnDecmp.objects.filter(raccntname=selected_entity) else: obj = BNPPBMrgnDecmp.objects.filter(date='2/10/2020', entity='VNI3') The above model should filter by date and by entity. However, when the objects from the form are selected from the html template, the results are only filtered by date and … -
Can not to properly define url path for main page
I have project with multiple apps. #my project directory forecast #app authorization views.py #project directory where settings forecast settings.py urls.py #here html templates located templates main base.html Inside forecast/urls.py i defined the following from django.contrib import admin from django.urls import path,include,re_path from django.contrib.auth import views as auth_views from authorization.views import index_page_view urlpatterns=[ path(r'^$',index_page_view,name='home')] In authorization/views.py defined view to render main page def index_page_view(request): return render(request,'main/base.html',{}) When i am open http://127.0.0.1:8000 i see the 404 error with following message ^$ [name='home'] The empty path didn't match any of these. What is wrong inmy setup ?