Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating new object returns field with None value
I'm trying to create a new object of my model, but keep on getting a value of none for one field. My models look like this: class KeyCategory(models.Model): program = models.ForeignKey('Program', verbose_name='Programm', on_delete=models.CASCADE) name = models.CharField('Name', max_length=100) events = models.ManyToManyField('Event', through='EventQuota') class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' ordering = ['name'] unique_together = ("program", "name") permissions = ( ('view_key_category', 'Have access to categories'), ) class EventQuota(models.Model): key_category = models.ForeignKey(KeyCategory, on_delete=models.CASCADE, related_name='key_quota') event = models.ForeignKey('Event', on_delete=models.CASCADE, related_name='key_quota') quota = models.PositiveIntegerField('Quota', default=0) class Meta: verbose_name = 'Quota' verbose_name_plural = 'Quotas' unique_together = ('key_category', 'event') When I try now to create a KeyCategory and my EventQuota, the field "events" for KeyCategory always returns core.Event.None if program.pk == 1: for _ in range(0, 2): access_code_category = AccessKeyCategory( program=program, name=random.choice(self.eventList) ) access_code_category.save() event_quota = AccessKeyEventQuota( access_key_category=access_code_category, event = random.choice(eventList), quota = random.randint(0,100) ) event_quota.save() Note: the eventList in the random.choice is a queryset list of objects. I tried to follow Djangos Extra fields on Many-to-Many relationships example, but somehow it seems that I'm missing something here or doing something not the right way? Would appreciate any help! Thanks in regard. -
Phantom style in django project
I'm working on my first real django project, and was fiddling around with the css, but the changes I made did not have any effect on the site. I tried changing things on all 3 of the css files but nothing changed. I then deleted the files (from the project I still have them), and still nothing changed. My site is getting styled, I checked all of my html to make sure there was no inline style in there. All the html files are working, when I change them the site changes. Is this some weird caching thing? I've tried rerunning the server several times and still my site is getting style, seemingly from nowhere. Anyone have any ideas? -
File splitting and writing to database
How can I write the data in several tables at once? I have 9 fields in Excel file, the format is as follows: 05/16/2015 8:00 | KG6418.040 | M153 | 400600052850 | EXC | 106 | 43 429 | Changierung_Ein / Aus | 1 But 2,3,4 fields are always the same made connection 1 to many. I tried to break the data like this: wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) data = [] for row in ws.iter_rows(row_offset=1): parameter = Parameter() And my models: class Line (models.Model): id_line = models.IntegerField(primary_key=True) par_machine = models.CharField(max_length=200) class Order (models.Model): id_order = models.IntegerField(primary_key=True) par_fa = models.CharField(max_length=200) class Recipe (models.Model): id_recipe = models.IntegerField(primary_key=True) par_recipe = models.CharField(max_length=200) class Parameter (models.Model): id_parameter = models.IntegerField(primary_key=True) par_rollennr = models.IntegerField(default=0) par_definition_id = models.IntegerField(default=0) par_name = models.CharField(max_length=200) class Measurements (models.Model): id_measurement = models.IntegerField(primary_key=True) par_value = models.IntegerField(default=0) line = models.ForeignKey(Line, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) parameter = models.OneToOneField(Parameter, on_delete=models.CASCADE) Where in Measurements line,order,recipe,params this is just one entry in the respective tables. For example, if you break the given string, you should get: Line: 1 M153 Order: 1 400600052850 Recipe: 1 KG6418.040 Parameter: 1 106 43429 Changierung_Ein / Aus Measurements: 1 1 1 1 1 … -
Django select_related queryset in template not rendering
I have a simple view like so: def classticker(request): tickermodel = Tickers.objects.all().select_related('subsector_fk') form = TickerForm() return render(request, 'feeds/main.html', {'v': 10, 'form': form, 'tickermodel': tickermodel}) tickermodel is successfully returning a queryset with all of the fields in the Tickers table and the Subsector table (through the subsector_fk field). This includes the fields 'ticker', 'company_name' and 'subsector' that I'm using in the template below. When I render my template and iterate through the tickermodel queryset I cannot seem to access fields that are coming from the Subsector table. Below tic.ticker and tic.company_name are rendering as expected but tic.subsector is not. I have no idea why?? My template looks like this: <table class="tbllist"> <tr><th>Current Tickers</th></tr> {% for tic in tickermodel %} <tr> <td><input type="checkbox" name="myclass" value="{{tic.ticker}}"/></td> <td class="selectable" data-tik="{{tic.ticker}}"><span class="uppercase">{{ tic.ticker }}</span> - {{ tic.company_name }}</td> <td>{{ tic.subsector }}</td> /*<<<< this will not display >>>>>*/ </tr> {% endfor %} </table> -
how to make a circular level meter django
I am trying to implement a level circular that looks like this circular level meter I rotate the meter by -90deg - works fine I adjust color to red - works fine I use border radius to clip it circular, just like photos - it doesn't work. The background gets clipped, but the foreground (the red level) remains rectangular, no clipping. The CSS definitive guide book mentions that the object continues to be rectangular, no matter how it is rendered or how it looks to you. An example shows that text inside a square container whose corners are rounded, sticks out of the circle, because it lives in the square. Any clues on how to do this? Any help will be greatly appreciated. Best, Juan -
How to change datetime value via functions in django?
I have code within a context processor that displays the date in a navbar via the {{date}} tag using the function I created: import datetime def date(request): nav_date = datetime.date.today() return { "date" : nav_date } However, I would like to create a function to change the date so that whenever a button is clicked in the html code, the function would push the date from the nav_date variable 1 day forward. -
Django static files templatetags.static
I am trying to open a json file in python. It is in a directory called json in static directory of my app. I configured the static files as per the given documentation. But I get this error on opening files in python using open() function def send(request): file = static('accounts/json/credentials.json') f = open(file, "r") return HttpResponse("click here <a href='" + file + "'> asd</a>") The above code generates a FileNotFoundError No such file or directory: '/static/accounts/json/sample.json' I also used this code def send(request): file = static('accounts/json/credentials.json') return HttpResponse("click here <a href='" + file + "'> asd</a>") The above code successfully gave me the response. And On clicking the link asd it is working fine and opens the JSON file. I have googled a bit and also went through few stackoverflow questions but not sure what the actual error is, Can anyone help me in finding out. Thanks -
django-tables2 Adding template column, which content depends on condition
Working with Django framework django-tables2 I have a table for which I add 2 additional template columns (buttons). I want to display only these buttons depending on the condition on other column. Lets say grade is G2 then edit/delete buttons are visible or active. Else they are not displayed or disabled. Here it how it looks now: Is it possible to do that in table class? Or do I need to write some fancy jquery code? Here is my tables.py import django_tables2 as tables from .models import Person from django.urls import reverse_lazy class PersonTable(tables.Table): T1 = '<button type="button" class="btn js-update" update-link="{{ record.get_absolute_url_update }}">update</button>' T2 = '<button type="button" class="btn js-delete" delete-link="{{ record.get_absolute_url_delete }}">delete</button>' edit = tables.TemplateColumn(T1) delete = tables.TemplateColumn(T2) class Meta: model = Person fields = ('name','surname','city','grade',) template_name = 'django_tables2/bootstrap4.html' -
Get first and last item in one query
I want to get the first item and the last item in Django. My current code looks like this: first = Article.objects.first() last = Article.objects.last() However, these are two queries. Is there a way to make one query out of it? -
Django: creating a dynamic number of forms
im new to Django so any kind of help would be appreciated. Is there a way to create a dynamic number of forms depending on the elements of a list in Django? For Example I have a list of 15 string elements and I want to create a view which displays the first elements of the list and then at every third element it creates a form for user Input right after the strings. I also dont really know if I have to edit it in my views.py or forms.py to create many forms. -
MultiValueDictKeyError at /files/ in Django file upload
I am facing issue uploading file using Django rest framework. I am testing using postman and adding Content-Type header as multipart/form-data, but I get MultiValueDictKeyError at /files/ error, here is my code. class FileUploadView(APIView): parser_classes = (MultiPartParser,) def put(self,request, format = None): file_obj = request.FILES['file'] file_obj.seek(0) data = file_obj.read() return Response(data,status=204) I am using multipart form data so that I access post data along with uploading files. -
Django filter - filter by Avg of a field in related model
I'm using django-filter to filter through Festival model. There is another model - Review which contains reviews about festivals and related to Festival model by Foreignkey. My goal is to be able to filter festivals by friendly average > 3 (friendly is a one field for example in Review model). Any idea how to do it? Many thanks =] Models.py class Review(models.Model): ... festival = models.ForeignKey( Festival, related_name='Festival_Reviews', on_delete=models.CASCADE, null=True, blank = True, default = '', ) score_choices = ( (1, 'Bad'), (2, 'Okay'), (3, 'Good'), (4, 'Great'), (5, 'Superb'), ) friendly = models.IntegerField( choices=score_choices, default='', null=True, blank = True, ) class Festival(models.Model): ... created_at = models.DateTimeField(auto_now=True) name = models.CharField(max_length=200) Filter.py (this was my idea, I'm pretty new to Django so seem not in the direction..) class FestivalFilter(django_filters.FilterSet): ... Festival_Reviews_friendly = django_filters.BooleanFilter(field_name='Festival_Reviews',method='avg_above3') def avg_above3(self, queryset, name, value): return queryset.aggregate(friendly_avg=Avg('friendly')).filter(friendly_avg__gt=3) Views.py class HomePage(ListFilteredMixin, AjaxListView): template_name = 'index.html' page_template = 'index_page.html' model = models.Festival paginate_by = 12 context_object_name = 'festivals' filter_set = FestivalFilter -
Wagtail admin - playing with urls
I created in wagtail a model called Regbox in model.py and also RegboxModelAdmin in wagtail_hooks.py. Wagtail admin includes item Regbox in wagtail side bar menu. Then I programmatically created a new collection, a new group with permissions add, edit, delete Regbox and this group is assigned to new user after registration. New user can add (edit and delete) new Regbox (model Regbox has forein key User) and this new user can see in wagtail admin only his own regboxes (I used queryset filter so that superuser could see all regboxes in wagtail admin and the current user only his own regboxes). But if this new user plays with urls he can see also other regboxes (not only his own regboxes). Could someone please advice me how can I do it in wagtail admin ? Thanks -
Ember JSONAPI Adapter with Django REST framwork json API
I am using EmberJS with django. For my API do I want to use JSONAPI. For this I installed Django rest framework json api. And in Ember do I use the JSONAPIAdapter. When my Ember app tries to get /appointments/ everything is fine and "type": "Appointment" but when my Ember Store tries to save an appointment it goes to the correct URL but "type": "appointments" after some testing I concluded that the only type that works is "Appointment", not "appointment" and neither "appointments" or "Appointments". I don't know why the Ember JSONAPIAdapter does this, but is there a way to fix this problem? -
Django 2.1.3/SQLite : UNIQUE constraint failed: users_profile.user_id || while trying to access my superuser account
i am working on a website that has a social appeal and i have to create an AbstractUser Model to store extra info about the users; while doing so, i ran into this error while trying to log into django admin page with my superuser account. UNIQUE constraint failed: users_profile.user_id. i have rebuilt the project 3 times and the issue still occurs. here's my models/forms/signals/admin.py files models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings from PIL import Image # Create your models here. class UserModel(AbstractUser): bio = models.TextField(max_length=500, blank=True, null=True) location = models.CharField(max_length=35, blank=True, null=True) birthday = models.DateField(blank=True, null=True) url = models.URLField(blank=True, null=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True) image = models.ImageField(default='default.png', upload_to="profile_pics") def __str__(self): return self.user.username def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) path = self.image.path img = Image.open(path) if img.height > 500 and img.width > 500: output_size = (500, 500) img.thumbnail(output_size) img.save(path) forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import UserModel, Profile class UserModelCreationForm(UserCreationForm): email = forms.EmailField() class Meta: model = UserModel fields = [ 'username', 'password1', 'password2', 'email', ] class UserModelChangeForm(UserChangeForm): email = forms.EmailField() class Meta: model = UserModel fields = [ 'username', 'email', ] class … -
Migration Issue Django, No Migrations To Apply to New DB
I feel like I understand how migrations work, but I am running into what seems to be a strange issue with migrations today. I created a DB in my settings file (and obviously on the server), but when I run the migrations to sync the Models with the DB I am being told there are no migrations to apply. I had 2 DBs on my server: test_universal and test_client. Now I have a new one, which is a 'real' client titled _6_. When I created test_client I ran the same migrations you see below and they worked. I have read that the migration table may be causing this but I am moving to a new DB so that can't be right. What is going on? py manage.py migrate objects_client --database=_6_ Operations to perform: Apply all migrations: objects_client Running migrations: No migrations to apply. py manage.py migrate objects_client 0001_initial.py --database=_6_ CommandError: Cannot find a migration matching '0001_initial.py' from app 'objects_client'. py manage.py showmigrations objects_client objects_client [X] 0001_initial [X] 0002_auto_20181119_2025 # there is nothing in the default db either py manage.py migrate objects_client Operations to perform: Apply all migrations: objects_client Running migrations: No migrations to apply. -
Django Cant change audio currenttime
I'm creating an article app where you can add an audio file. I can play the audio but whenever I try to change currenttime of the song it starts from 0. I added static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py. my template (removed some unnecessary parts): var songs = [ {% for audio in article.audio_set.all %} "{{audio.file.url}}", {% endfor %} ], title =[ {% for audio in article.audio_set.all %} "{{audio.name}}", {% endfor %} ] var songTitle = $("#songTitle"), songSlider = $("#songSlider"), currentTime = $("#currentTime"), duration = $("#duration"), volumeSlider = $("#volumeSlider"), nextSongTitle = $("#nextSong"); var song = new Audio(), currentSong = 0, oldvolume = 0.5; var nextSong; $(document).ready(function(){ loadSong(); }); function loadSong(play=false){ nextSong = currentSong + 1; if (nextSong + 1 > songs.length) {nextSong = 0;} nextSongTitle.html("<b>Nächstes Audio: </b>" + title[nextSong]); songTitle.text(title[currentSong]); song.src = songs[currentSong]; song.currentTime = 0; song.playbackRate = 1; song.volume = volumeSlider.val(); if (play) song.play(); song.addEventListener('loadeddata',() => { showDuration(); }); } setInterval(updateSongSlider, 100); songSlider.on("input", function(){ var newValue = parseFloat(songSlider.val()); song.currentTime = newValue; }); When I navigate to the file (in browser) I can play it too but I can't change currenttime. -
Output python script in django dashboard app
Currently I'm learning to work with the Django framework. I'm trying to make a dashboard that can collect some output of scripts I want to make (in Python). I can't really find a conclusive answer to how to pipe the output of a python script through Django in my app. For instance, I want a script that runs a couple of ARP calls and pings in a network and have the output in a dashboard. Of course python is probably not the only language I'm going to use for scripting, maybe I will use some Bash or Golang also. I hope someone is able to help my in the right direction. Thank you in advance! -
Key-value pairs in SQL table
I am building a Django app and I would like to show some statistics on the main page, like total number of transactions, percentage of successful transactions, daily number of active users etc. I don't want to calculate these values in the view every time a user requests the main page for performance reasons. I thought of 2 possible solutions. (1) Create a number of one-record tables Create a table for each of the statistics, e.g.: from django.db import models class LastSuccessfulTransactionDate(models.Model): date = models.DateTimeField() class TotalTransactionAmount(models.Model): total_amount = models.DecimalField(max_digits=8, decimal_places=2) # ... and make sure that only one record exists in each table. (2) Create a table with key-value data class Statistics(models.Model): key = models.CharField(max_length=100) value = models.TextField() and save the data by doing: from datetime import datetime from decimal import Decimal import pickle statistics = { 'last_successful_transaction_date': datetime(2010, 2, 3), 'total_transaction_amount': Decimal('1234.56'), } for k, v in statistics.items(): try: s = Statistics.objects.get(key=k) except Statistics.DoesNotExist: s = Statistics(key=k) s.value = base64.b64encode(pickle.dumps(v, pickle.HIGHEST_PROTOCOL)).decode() s.save() and retrieve by: for s in Statistics.objects.all(): k = s.key v = pickle.loads(base64.b64decode(s.value.encode())) print(k, v) In both cases the data would be updated every now and then by a cron job (they don't have to be … -
Django: NOT NULL constraint failed: Cart.cart_id
I'm trying to create an Ecommerce site. I need to make a 'Cart' app that will generate a Cart object which will hold the items that the user wants to shop. However, when adding an item to the Cart I get: IntegrityError at /cart/add/3/ NOT NULL constraint failed: Cart.cart_id 1.- Cart object will have an ID, that will be the user's sessions ID. This is the function that will get the session ID: def _card_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart views.py from django.shortcuts import render, redirect from shop.models import Product from .models import Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _card_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id = product_id) try: cart = Cart.objects.get(cart_id = _card_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _card_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product = product, cart = cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity= 1, cart = cart, ) cart_item.save() return redirect('cart:cart_detail') def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(cart_id = _card_id(request)) cart_items = CartItem.objects.filter(cart = cart, active=True) … -
Get next id from the db table and assign suffix django 2
I am working on this issue for last few hrs and landed no where. Here is my problem. I have a model that will track the shipments and I want to create the shipment number automatically when the form is loaded fro a new shipment. The logic is to get the next available Id from the database and add some test and store. My model is class Shipment(models.Model): id = models.AutoField(primary_key=True) shipmentNumber = models.CharField(max_length=50) shipmentDate = models.DateTimeField() dateCreated = models.DateTimeField(default=timezone.now) dateModified = models.DateTimeField(default=timezone.now) def __str__(self): return self.shipmentNumber and the view is def createshipment(request): if request.method == "POST": form = CreateShipmentForm(request.POST) if form.is_valid(): shipment = form.save(commit=False) shipment.shipmentNumber = request.shipmentNumber shipment.shipmentDate = timezone.now() shipment.save() else: form = CreateShipmentForm() form.shipmentNumber = 'get the next id and assign suffix' context ={'form' : form} return render(request,'../templates/mainSection/createshipment.html',context) I tried to retrieve the data by getting all the shipments in the db and count them and go form there. But I ended up with "didn't return an HttpResponse object. It returned None instead." Any thought on how should I create the shipment number? Thanks -
How to configure subdomain to specific port
I have two projects 1: is wordpress running on apache (main website thespatio.com/45.33.10.149) 2: A Django Application running on Nginx using same IP with 81 port. (45.33.10.149:81). I want to configure above two apps so that when some one hit http://thespatio.com it should show main website and if some hit http://or.thespatio.com it should show my django application. I have seen many fix but none work for me. I tried virtual host like proxypass and proxy_reverse but apache stopped working. below are the two virtual hosts conf file Main Website settings (conf) <VirtualHost *:80> ServerAdmin admin@example.com ServerName thespatio.com ServerAlias www.thespatio.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Django App (conf) <VirtualHost *:80> ServerAdmin admin@test.com ServerName or.thespatio.com ServerAlias www.thespatio.com ProxyPass / http://or.thespatio.com:81/ ProxyPassReverse / http://or.thespatio.com:81/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Any help would be appreciated. Thanks in advance -
Error while Installing mysql-python on CentOS 7
While working through a Pluralsight tutorial, https://app.pluralsight.com/library/courses/docker-ansible-continuous-delivery/exercise-files, I'm having an issue getting mysql to work with django. Running pip install mysql-python produces this output: Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: mysql-python Running setup.py bdist_wheel for mysql-python ... error Complete output from command /home/nick/dev/demos/todobackend/venv/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-YYanvu/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-ED_q9B --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_ SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -m64 _mysql.c:44:23: fatal error: my_config.h: No such file or directory #include "my_config.h" ^ compilation terminated. error: command 'gcc' failed … -
How to unit test Django views when base template has arguments in different, unrelated views/hrefs
For example, I have different views that I am trying to test functionality of, but I can't get past the issue where I have different hrefs that have arguments. For example, in my navbar, which is applied to every view through the base template, I have a link to the user's profile. This looks like: url(r'^(?P<username>[\w.@+-]+)/$', user_profile, name='user-profile'). So this relies on getting the username as an argument: <a class="dropdown-item" href="{% url 'user-profile' request.user.username %}>. I have setup my test like: self.client.force_login(user=self.test_user) request = self.client.get(reverse('home')) request.user = self.test_user It fails at the second line, so I assume it never gets the opportunity to see the request.user. Because I am not directly calling the view in the navbar, but linking to it, how could I go about testing for this without getting a Reverse for 'user-profile' with arguments '('',)' not found -
Django 2.1 reset_password()
I am new in django. In Django version 2.1 has been deleted reset_password() function. How i should add on admin page password reset for admin now?