Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot change django auth urls namespace
I'm including all Django auth urls in one go, like this: app_name = "main" urlpatterns = [ ... path("accounts/", include("django.contrib.auth.urls")), ... ] However, if I go to /accounts/password_reset/ and add my email, the email gets sent but it can't resolve the "reset done" url. Error: NoReverseMatch at /accounts/password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. I assume the reason is that it is resolvable at "main:password_reset_done". Then I add a namespace in my url include like this: app_name = "main" urlpatterns = [ ... path("accounts/", include("django.contrib.auth.urls", namespace="main")), ... ] But then I get another error: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Which doesn't make sense, as I already have app_name set. -
Django makemigrations tool fails if i change the foreign key / other relationships at models
I have a problem with Djang makemigrations / migrate tool I have a Withdraw model with foreignkey to an Employee table. Everything is working fine models.py from django.contrib.auth.models import User class Withdraw(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) amount = models.IntegerField(default=0) withdraw_date = models.DateTimeField(default=timezone.now) is_confirmed_by_employer = models.BooleanField(default=False) I want to change it and have user as a foreignkey to user: user = models.ForeignKey(User, on_delete=models.CASCADE) I run makemigrations and I have this errormessage: You are trying to add a non-nullable field 'user' to withdraw without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py If I press 1, then I have the following message, what I dont really get, why shall I put datetime or timezone.now to user?? Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt I tried to delete migrates folder and recreate migration files as was … -
PasswordChangeForm from Django doesnt show on template
I'm tying to make a ChangePasswordForm but it isn't showing on template. The section only prints the description but it doesnt show the form. By the way, Ive been reading about that specific form, and most websites claim it to be implemented by Django, thats why i hadn't put it on forms. I think that might be the mistake. views.py def change_password_view(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Contraseña cambiada con éxito') return redirect('profileedit') else: messages.error(request, 'Ha ocurrido un error.') else: form = PasswordChangeForm(request.user) context = { 'form2': form } return render(request, 'profileedit.html', context) template (in case of) <form method="POST" action="#" id="contraForm" name="form2"> {% csrf_token %} <p>Por favor, llena los siguientes campos para cambiar tu contraseña. {{ form2.as_ul }} <button class="btn btn-primary py-1 px-2" type="submit" > Save </button> </p> </form> -
Base64ImageField for Django Nested Serializer
I have a model that looks like this: class ChoiceImage(models.Model): choice = models.OneToOneField(Choice, on_delete=models.CASCADE, null=True) img = models.ImageField(upload_to='some-path/') That points to: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) When a user submits a Question, it goes through this serializer: class CreateQuestionSerializer(serializers.ModelSerializer): choice_set = CreateChoiceSerializer(many=True) class Meta: model = Question fields = ('user', 'choice_set') def create(self, validated_data): choices_validated_data = validated_data.pop('choice_set') question = Question.objects.create(**validated_data) choices_serializer = self.fields['choice_set'] for choice in choices_validated_data: choice['question'] = question choices_serializer.create(choices_validated_data) return question Then this: class CreateChoiceSerializer(serializers.ModelSerializer): choiceimage = ChoiceImageSerializer(many=False, required=False) class Meta: model = Choice fields = ('choice', 'choiceimage') def create(self, validated_data): image_uploaded = validated_data.get("choiceimage") image_validated_data = validated_data.pop('choiceimage') choice = Choice.objects.create(**validated_data) image_serializer = self.fields['choiceimage'] image_validated_data['choice'] = choice image_serializer.create(image_validated_data) class ChoiceImageSerializer(serializers.ModelSerializer): img = Base64ImageField() class Meta: model = ChoiceImage fields = ('img',) Notice how I have Base64ImageField() as my img. Whenever I submit data in my form, it complains saying no file was submitted. However, I'm submitting a Base64Image I'm not sure why it's complaining about a file when I'm specifying that it'll be a Base64ImageField What am I doing wrong? -
Проблема с файлом wsgi.py (Problem with wsgi.py file)
/ Hi all! Помогите, пожалуйста, настроить файлы wsgi.py для сайта pythonanywhere.com. (Please help set up wsgi.py files for pythonanywhere.com) Лог ошибки, который выводит pythonanywhere. (The error log that pythonanywhere prints) !2020-03-29 21:29:25,095: Error running WSGI application 2020-03-29 21:29:25,095: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. 2020-03-29 21:29:25,095: File "/var/www/relizerel_pythonanywhere_com_wsgi.py", line 22, in 2020-03-29 21:29:25,095: application = get_wsgi_application() !2020-03-29 21:29:25,095: File "/usr/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-29 21:29:25,095: django.setup(set_prefix=False) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/init.py", line 19, in setup 2020-03-29 21:29:25,096: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 79, in getattr 2020-03-29 21:29:25,096: self._setup(name) !2020-03-29 21:29:25,096: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 66, in _setup 2020-03-29 21:29:25,096: self._wrapped = Settings(settings_module) !2020-03-29 21:29:25,097: File "/usr/lib/python3.8/site-packages/django/conf/init.py", line 176, in init 2020-03-29 21:29:25,097: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") Я думаю, что проблема в SECRET_KEY, но во всех файлах он указан. (I think the problem is in SECRET KEY, but in all files it is indicated.) Какие еще данные необходимы, что бы Вам было проще дать ответ? (What other data is needed to make it easier for you to give an answer?) Please, excuse me for using google translator :) -
Is it possible to upload an image directly from django forms?
I wanted to run my Dog vs Cat classifier in my website (in a heroku server) I don't want to consume space in the cloud at the same time don't want to save the uploaded image in the database. This is my code in the views.py file def test_model(request): if request.method == 'POST': form = modelForm(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['label_name'] form.save() inp_img = str(form['test_img'].value()) path = "./media/img/{}".format(inp_img) dest = "./media/img/" resz(path,dest,inp_img) inp = pred_dog_cat().prepare(path) pred,label = pred_dog_cat().prediction(inp) pred = round(pred *100,2) params = {'inpImg':inp_img,'pred':pred,'label':label} return render(request,'dcapp/output.html',params) the modelForm class is in the forms.py from django import forms from .models import * class modelForm(forms.ModelForm): class Meta: model = Test_model fields = ['test_img','label_name'] The models.py file is: class Test_model(models.Model): model_id = models.AutoField(primary_key=True) label_name = models.CharField(max_length=50,default="None") test_img = models.ImageField(upload_to='img/',default="None Selected") output = models.CharField(max_length=50,default="None") def __str__(self): self.str_img = str(self.test_img) return self.str_img I need some guidance about how to upload images from the forms without saving it in the database? And Is it possible to upload it without saving it locally? (as I don't want to consume space in the server) -
How do I create a Django migration to set charset and collation for all existing tables and all future ones?
I'm using Django, Python 3.7 and MySql 5.7. I want to set the default charset and collation for all existing and all future tables to DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci I have already created some migrations, (venv) localhost:maps davea$ ls web/maps/migrations/ 0001_initial.py __init__.py __pycache__ Is there any way I can create such a migration? I'm happy to blow away from database and start from scratch if that's what it takes. -
Unable to save data with custom create serializer django rest_framework
Got AttributeError when attempting to get a value for field note on serializer ProcessStepSerializer2.\nThe serializer field might be named incorrectly and not match any attribute or key on the ProcessStep instance.\nOriginal exception text was: 'ProcessStep' object has no attribute 'note'. My code : model file class ProcessStep(BaseModel): process = models.ForeignKey('Process', on_delete=models.PROTECT) order = models.ForeignKey('Order', on_delete=models.PROTECT) priority = models.FloatField(default=0.0) notes = ArrayField(models.TextField(blank=True), default=list) end_date = models.DateTimeField(default=datetime.now) status = models.CharField(max_length=128, null=True, choices=(('inprogress', 'In Progress'), ('delayed', 'Delayed'), ('completed', 'Completed')) ) in views note = request.data['note'] status = request.data['status'] process = ProcessStep.objects.get(id=slugid) serializer = ProcessStepSerializer2(process, data=request.data, context={'request': request}, partial=True ) // serializer file class NoteSerializer(serializers.Serializer): status=serializers.CharField() type=serializers.CharField() text=serializers.CharField() class ProcessStepSerializer2(serializers.Serializer): note= NoteSerializer() status=serializers.CharField(required=True) user=serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) def update(self, instance, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user current_time = datetime.datetime.now(tz=datetime.timezone.utc) note = validated_data['note'] note['time'] = current_time.replace(tzinfo=datetime.timezone.utc).timestamp() * 1000 note['user'] = UserSerializer(request.user).data validated_data['jsondumpednote'] = json.dumps(note) instance.notes.append(validated_data.get('jsondumpednote', instance.notes )) instance.status = validated_data.get('status', instance.status) instance.save() return instance So, it is returning the above error. My doubts: 1. when calling save on serializer in views, if am not passing previous instance than it should create, right? 2. similarly when updating, when object instance is passed, than it should update, right? 3. Does … -
how to take foreign key fields in actual form validation, DJANGO
Thanks for your time: i want to set Validation Error with data that is already written in other modelclass. Models.py class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) class Pets(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) nome = models.CharField(max_length=150) custo = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.SmallIntegerField() def __str__(self): return '%s - %s' % (self.pessoa, self.nome) Forms.py: class PetForm3(forms.ModelForm): #SELECIONAR FORM PELO FORMS.PY field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'ANDORINHA') ] nome = forms.CharField(max_length=100) custo = forms.DecimalField(max_digits=7, decimal_places=2) tipo = forms.ChoiceField(choices=field_choices) class Meta: prefix = 'pet' model = Pets fields = ['nome', 'custo', 'tipo'] def clean_tipo(self): data = self.cleaned_data.get("tipo") data_pessoa = self.cleaned_data.get("pessoa") slug = slugify(data_pessoa) if slug.startswith('a'): data == 2 raise forms.ValidationError('nomes com A nao podem ter gatos') return data i got these two models and the Pets is a ManytoOne to People i'd like to take attributes of People like birthday and cpf in the clean_method of PetForm3. and like to get the ''pessoa'', whithout having to display, field from Pets on the clean method either. i'm able to achieve something like that with request.user in views.py but i'd like to get it in clean_method at forms.py -
Traverse multiple foreign keys in Django DetailView
I'm working on a project to record all scores shot at a bunch of archery events. They are shot by many people at many events and many different archery rounds. (A "round" in archery is a particular type of competition. For the sake of simplicity let's say there are two: indoor and outdoor.) Here's a basic ER diagram of the relevant part of my database model: ┌───────────┐ ┌───────────┐ ┌────────────────┐ ┌───────────┐ │ │ ╱│ │╲ │ │╲ │ │ │ Person │──────┼──│ Score │──┼────│ EventRound │──┼─────│ Event │ │ │ ╲│ │╱ │ │╱ │ │ └───────────┘ └───────────┘ └────────────────┘ └───────────┘ ╲│╱ ┼ │ ┌───────────┐ │ │ │ Round │ │ │ └───────────┘ You can see that there are two ManyToMany relationships at work here resolved with two junction tables (EventRound and Score). I'm creating these junction tables manually by specifying the "through" table and "through_fields" in models.py. I've created a PersonDetailView that allows me to access and iterate through all of the scores in the Score table for a specific person. (Thanks to Jaberwocky and his solution at Detailview Object Relations) # views.py class PersonDetailView(DetailView): model = Person queryset = Person.objects.all() template_name = 'person_detail.html' def get_context_data(self, **kwargs): context = super(PersonDetailView, self).get_context_data(**kwargs) … -
How to upload multiple images and sort them? - Django
I am building an application with Django and I am struggling with uploading multiple images to each post. I want the users to be able to easily upload images (up to 7) to each post and also be able to sort them around, in other words, to be able to choose in which order the images will be displayed. If anyone knows how to do this or knows of any good guides/tutorials out there that shows how to do this, please let me know. I would really apprecciate it! Thanks -
django models - how can i create abstract methods
In django abstract classes seem to be posibble by using: class Meta: abstract = True However I do not see how to declare abstract methods/functions within these classes that do not contain any logic like e.g. class AbstractClass(models.Model): def abstractFunction(): class Meta: abstract = True The library abc repectively the notation @abstractmethod doesnt seem to applicable here, or am I wrong? -
Django views.py is not rendering html file?
i am sending an object to backend (django) via ajax "POST" method. in the views.py the code runs but the render statement is not executing. ajax $.ajax({ url: '{% url "chout" %}', data: { 'object': object1, 'csrfmiddlewaretoken':csrf }, method: "POST", dataType: 'json', success: function (data) { alert("success"); } }); views.py return render(request, "mart/checkout.html", {"total": total_price, "final_bill": final_dict}) Everything above return statement runs smoothly but somehow the return line dont run. it is not showing any error or warning either. -
Django Ajax form submitted twice
I am trying to submit a post creation form, however, after I click on my submit button the view is called twice and the post object is created twice upon my Ajax request, I was wondering what Is causing this issue? This is my post_create view: @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) This is my post.js for handling Ajax: $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); return false; }; var SaveForm = function(e){ e.preventDefault(); var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; } //create $('.create-post-btn').click(ShowForm); $('#modal-post').on("submit",".post-create-form",SaveForm) //update $('#post-list').on("click",".show-form-update",ShowForm); $('#modal-post').on("submit",".update-form",SaveForm) //delete $('#post-list').on("click",".show-form-delete",ShowForm); $('#modal-post').on("submit",".delete-form",SaveForm) }); And this is my post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) last_edited= … -
No module named 'registration' in django 2.2.5
I am using django 2.2.5 with python 3.6 i have installed django-registration by adding it to my project's installed apps and then doing a pip install django-registration. All this worked fine but now when i am trying to perform a python mange.py makemigrations am getting this error. I read a lot of solutions online and they don't seem to work, i tried downgrading the django-registration version to 2.4 but then it uninstall django 2.2.5 because it works with django 1, which will cause some other serious problems. here is my installed app section: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'wewriteapp', 'crispy_forms', ] Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Ahmed\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\Ahmed\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'registration' -
Django request.user modification not happening in test
I have a view that is changing a field of request.user: def test(request): request.user.is_provider = False request.user.save() print(request.user.is_provider) return HttpResponse(status=200) Now I am testing the function and I have the following test: class RoleSwitchTests(TestCase): def test_switch_to_customer(self): User = get_user_model() user = User.objects.create_user( username='test', email='test', password='test', first_name='test', last_name='test', is_provider=True, is_admin=False, ) self.client.login(username='test', password='test') response = self.client.post('/test/', follow=True) print(user.is_provider) self.assertEqual(response.status_code, 200) self.assertFalse(user.is_provider) self.assertFalse(user.is_provider) fails here. For some reason, request.user.is_provider is False in test, but in test_switch_to_customer, user.is_provider is True. I know these refer to the same user because they have the same id, so why is the modification not being preserved here? -
Django execute order by before filter
i'm using django 2.0.7 so, i want to order a queryset and then select distinct entries, after that, i'm gonna perform some filtering as you can see here i'm doing the order and select distinct stuff forms = Form.objects.order_by('user','-created_at').distinct('user') and here i'm filtering some attributes filterd_qs = forms.filter(**query) the problem is that the order_by query is executed after the filter query which causes unexpected results (it's applying the filter on the whole queryset), the sql query resulted from the last filter : SELECT DISTINCT ON ("table"."user_id") fields FROM "appname_form" WHERE where_clause ORDER BY "appname_form"."user_id" ASC, "appname_form"."created_at" DESC; so how do i force django orm to wrappe the orderby query by the filter query !! any suggestion will do -
Serialize view class django
i need to send the same info via json this is my view class class ContatoreDetailView(LoginRequiredMixin, DetailView): model = Contatore def get_context_data(self, object: Contatore=None, **kwargs): context = super().get_context_data(**kwargs) context['Letture'] = Letture.objects.all().filter(srf=object.srf) return context I need to have a json version of this view, is there any way? -
mozilla-django-oidc issue with Azure AD B2C
I am trying to configure the "mozilla-django-oidc" package in Django. To authenticate I use Azure Active Directory B2C policy, so this is my federation server. When I click in the login button I got this URL which looks wrong to me, I will split it, just for convenience: https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize?p=b2c_1_TENANTID_signin?response_type=code&scope=openid+email&client_id=XXXXXXXXXXXXXXX&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foidc%2Fcallback%2F&state=pt8aYXicnYRSQkkB8kwHSv4hQwt9Xzre&nonce=UfLfk6QovA2inpfo9W7zS2MZHLpO1tkJ and the URL I need has this format: https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize?p=B2C_1_TENANTID_SIGNIN&client_id=XXXXXXXXXXXXX&nonce=defaultNonce&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Foidc%2Fcallback%2F&scope=openid&response_type=id_token&prompt=login In the home page I have this code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home page</title> </head> <body> <h3> Welcome to home page </h3> {% if user.is_authenticated %} <p>Current user: {{ user.email }}</p> <form action="{% url 'oidc_logout' %}" method="post"> <input type="submit" value="logout"> </form> {% else %} <a href="{% url 'oidc_authentication_init' %}">Login</a> {% endif %} </body> my code in the settings.py OIDC_RP_SIGN_ALGO = "RS256" OIDC_RP_CLIENT_ID = "xxxxxxxxxxxxxx" #fake client id just for this post # OIDC_RP_CLIENT_SECRET = os.environ['OIDC_RP_CLIENT_SECRET'] OIDC_OP_AUTHORIZATION_ENDPOINT = "https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/authorize? p=b2c_1_TENANTID_signin" OIDC_OP_TOKEN_ENDPOINT = "https://TENANTID.b2clogin.com/TENANTID.onmicrosoft.com/oauth2/v2.0/token? p=b2c_1_TENANTID_signin" # OIDC_OP_USER_ENDPOINT = "<URL of the OIDC OP userinfo endpoint>" LOGIN_REDIRECT_URL = "http://localhost:8000/oidc/callback/" LOGOUT_REDIRECT_URL = "http://localhost:8000/welcome/ Note: I don't know what to put in this variable "OIDC_RP_CLIENT_SECRET" and also "OIDC_OP_USER_ENDPOINT" Any help please to get the right URL in this configuration? Thanks -
QuerySet to get top x of something - Django
first time here, so please be nice (? I want to be able to show a Top X of "alojamientos" in my website. #models.py class post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) text = models.TextField() class comment(models.Model): post = models.ForeignKey("appname.author", on_delete=models.CASCADE) author = models.ForeignKey("auth.User", on_delete=models.CASCADE) text = models.TextField() #views.py def index(request): top_comm = #I know it has to be Django aggregation, but I can't make it. return render(request, 'home/index.html', {"top_comm" : top_comm}) #index.html {% for row in top_comm %} {{row.author|linebreaksbr}} {{row.text|linebreaksbr}} {% endfor %} -
Add all the rows in a column and display it at the end of the file
I am trying to add all the rows in the column and display the output in a single row. Here is my source code: csvio = StringIO() header = ['Name','Unit1','Unit2','Marks'] writer = csv.writer(csvio) writer.writerow(header) for ut in uts: data = marks_helper() tot = 0 row = [] if data['a'] > 0.01 or data['b'] > .01 or data['a'] > .01: row.append(ut.name) row.append(round(data['a'],1)) row.append(round(data['abd'], 1)) tot = Decimal(data['abd']) - Decimal(data['a']) row.append("{}".format('%.2f' % tot)) if len(row) >= 1: writer.writerow(row) local = open( 'filename' , 'w') local.write(csvio.getvalue()) local.close() csvio.seek(0) breakdown = csvio.getvalue() I am trying to get the sum of all the rows in Marks column and display that in a new row. I have tried this: for x in tot: x += int(row[3]) row.append(x) but I get this error: 'Decimal' object is not iterable -
In Django, Save new record and updated existing in two separate models when user clicks one of two cards
TL;DR Question: How do I have a user's button click create a new record in one model and update an existing record in a second model? Disclaimer: no idea what I'm doing, limited knowledge of Python/Django/web development in general. I'm just messing around trying to learn something new during quarantine. I know Django is a weird place to start but I like a challenge. Any suggestions on tutorials/examples would be helpful too. This post is long enough, but if I forgot anything, this is just for fun so I have no problem sharing more. Objective: I'm trying to create a page where the user can choose between two "ideas". I then track these choices with the goal of ranking them based on the aggregation of these "pairwise" choices. The page needs to record the choice, then calculate a new "score", then update the "ideas" table with the current score. Current status: I was doing pretty well following some tutorials and googling. I have two models built, one to just hold the ideas and one that's basically just a log of the results (with some other logic that I'm not sure is working yet). I have the page populating two ideas … -
Is this possible? Using signals to set a global variable
I have made this function that runs every time a user logs in. I want to get the branch from 'user' but every time the session is set it's only available to the function even after setting it to BRANCH_ID in the settings file. any help? plus I don't want to do anything in view function with the request as it's not accessible from models def perform_some_action_on_login(sender, request, user, **kwargs): """ A signal receiver which performs some actions for the user logging in. """ request.session[settings.BRANCH_ID] = user.profile.branch_id branch = request.session.get(settings.BRANCH_ID) print(branch) user_logged_in.connect(perform_some_action_on_login) -
Django2.2 SQL Server How to store Checkbox input to Database
I have 2 checkboxes and I can check them in HTML but apparently I can't send them to my database, only the id increases but not one checked checkbox information is send to database. My model: class Qskontrolle(models.Model): qsid = models.AutoField(db_column='QsID', primary_key=True) mhd = models.BooleanField(db_column='MHD', blank=True, null=True) etiketten = models.BooleanField(db_column='Etiketten', blank=True, null=True) verpackungseinheiten = models.BooleanField(db_column='Verpackungseinheiten', blank=True, null=True) class Meta: managed = False db_table = 'qskontrolle' My view: def qskontrolle_view(request): qskontrolle = QskontrolleForm() if request.method == 'POST': qskontrolle = QskontrolleForm(request.POST) if qskontrolle.is_valid(): qskontrolle.save() context = { 'object': qskontrolle } return render(request, "pages/qswareneingang.html", context) My form: class QskontrolleForm(ModelForm): class Meta: model = Qskontrolle fields = '__all__' My HTML: <form action="" method="post"> {% csrf_token %} <div class="card-group"> <div class="col-md-4"> <div class="card"> <div class="card-header"> <h5 class="card-category">Wareneingangn QS-Prüfung</h5> <h4 class="card-title"> Kontroll-Check</h4> </div> <div class="card-body"> <div class="table-full-width"> <table class="table"> <tr> <td> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" name="mhd"> <span class="form-check-sign"></span> </label> </div> </td> <td class="text-left">MHD </td> <td class="td-actions text-right"> </td> </tr> <tr> <td> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" name="etiketten"> <span class="form-check-sign"></span> </label> </div> </td> <td class="text-left">Etiketten </td> <td class="td-actions text-right"> </td> </tr> </form> What can I do to successfully transmit the checked or unchecked checkboxes to my database, after the user clicked on … -
Django database not working properly when deployed to Heroku
I've been having issues when creating a new Django website and deploying to Heroku. I have followed the tutorials almost exactly for how to create a portfolio website using Sql databases on realpython.com, and followed the Heroku Deployment tutorial on the mozilla developer website. The trouble seems to be with the migration of the database for my blog entries and projects from SQLLite to the Heroku compatible Postgres database. I have verified that the Heroku database exists using the Heroku Postgres add-on, my database exists in data.heroku.com, and my DATABASE_URL environmental variable is setup in Heroku. I am quite baffled as the Heroku logs do not seem to have any error messages or anything, the database entries just appear blank. When I runserver locally the website appears as I'd expect. Django Website Tutorial: https://realpython.com/get-started-with-django-1/ Heroku Deployment: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment Website Code is in GitHub: https://github.com/kevinjweiss/website The sample website is also at kevinjweiss.com Any ideas would be appreciated. I got this far and am about to give up - have spent multiple days trying to sort out this issue and have running into a brick wall.