Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'delete' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/delete$']
First time writting to stack. If this problem is so stupid, don't condemn me pls. I need to delete the task from main page. I will be so grateful for the help! Traceback > > Template error: In template > C:\Users\dkaza\Desktop\taskmanager\templates\base.html, error at line > 6 Reverse for 'delete' with arguments '('',)' not found. 1 > pattern(s) tried: ['(?P<pk>[0-9]+)/delete$'] > Exception Type: NoReverseMatch at / Exception Value: Reverse for > 'delete' with arguments '('',)' not found. 1 pattern(s) tried: > ['(?P<pk>[0-9]+)/delete$']` urls.py path('<int:pk>/delete', TaskDelete.as_view(), name='delete'), models.py class Task(models.Model): title = models.CharField(max_length=50) content = models.TextField() created_at = models.DateTimeField(auto_now_add = True) def __str__(self): return self.title class Meta: verbose_name = 'Task' verbose_name_plural = 'Tasks' ordering = ['-id'] views.py class TaskDelete(DeleteView): model = Task template_name = 'task/del_task.html' success_url = reverse_lazy('home') context_object_name = 'task' index.html <a href="{% url 'delete' task.id %}" class="btn btn-primary">Delete</a> del_task.html {% csrf_token %} <form method='post'> <h1>Do you want delete the «{{object.title}}»?</h1> <p><button class="btn btn-danger" type='submit' valeu='Yes'/>Yes</button> <a class="btn btn-light" href='{% url 'home' %}'>Cancel</a></p> -
Confused with Stripe payment_method
I have been using Stripe inside my Django project with no problems so far, everything is working, however I am confused about the payment_method parameter. At the moment I have it set to pm_card_visa because that's what the documentation told me to do, however I believe this is causing me problems as when I put in a dummy Mastercard number that Stripe gives you, it is still defaulting to use the default 4242 4242 4242 card. How can I dynamically set the payment_method variable? -
How to use the value of "userinput" in the Finalresult function. And how to convert userinput tointeger so i can divide the client value by 2
def step2(request): return render(request, 'step2.html') def step3(request): enteredtxt = request.GET.get('userinput', 'default') return render(request, 'step3.html') def step4(request): return render(request, 'step4.html') def Finalresult(request): return render(request, 'Finalresult.html') enter image description here -
Django file upload per user
I'm trying to create a form that will upload file per user, and i need to set the default names of the files id or something. for example, if 2 users will upload a CV with the same name 'sampleCV.pdf' i need them to be in a seperated files, by ID or something, i tried to use self.name in the upload, but it did not work, because self is still not recognized at this point.. Is there a default way to set the file upload name? Model class Candidate(models.Model): name = models.CharField(max_length=200, null=True) ... candidate_cv = models.FileField(upload_to=f'uploads/',null=True) ... Form: class CandidateForm(ModelForm): class Meta: model = Candidate fields = '__all__' view: @login_required(login_url='login') def create_candidate(request): form = CandidateForm() if request.method == 'POST': form = CandidateForm(request.POST,request.FILES) if form.is_valid(): form.save() context = {'form': form} return render(request, 'dashboard/form.html', context) Form HTML: {% block content %} <center> <hr> <form enctype="multipart/form-data" action="" method="POST"> {% csrf_token %} {{form.as_p}} <input class='btn btn-sm btn-danger' type="submit" name="Submit"> </form> <hr> </center> {% endblock %} -
Can't get to boxes to align next to each other when there is a button with a link
I want to align two boxes horizontal to each other, but when i add a button with a link. The are align vertical. .box-element{ box-shadow:hsl(0, 0%, 80%) 0 0 16px; background-color: #fff; border-radius: 4px; padding: 10px; } <div class="col-lg-6"> <div class="box-element"> <hr> <h3>Order Summary</h3> <hr> <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{% static 'images/placeholder.png' %}"></div> <div style="flex:2"><p>Product 1</p></div> <div style="flex:1"><p>$20.00</p></div> <div style="flex:1"><p>x2</p></div> </div> <h5>Items: 2</h5> <h5>Total: $4</h5> </div> </div> result: : https://i.stack.imgur.com/cs67Y.png <div class="col-lg-6"> <div class="box-element"> <a href="{% url 'cart' %}" class="btn btn-outline-dark" >&#x2190; Back to Cart</a> <hr> <h3>Order Summary</h3> <hr> <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{% static 'images/placeholder.png' %}"></div> <div style="flex:2"><p>Product 1</p></div> <div style="flex:1"><p>$20.00</p></div> <div style="flex:1"><p>x2</p></div> </div> <h5>Items: 2</h5> <h5>Total: $4</h5> </div> </div> enter image description here thank you in advanced:) -
How to implement a Django model that has a many-to-many relationship with 'tags' but also counts of how many times it was tagged with something?
So I have three relevant models here: Word, Definition, and Tag. Words have a one to many relationship with Definition; many users can posts definitions for the same word. I want to add a tagging feature so that when users submit their definition they can include Tags. These Tags apply to the Word they are defining, not the definition itself. A Word can have more than one Tag, but the same Tag can also apply to more than one word, so Words should have a many-to-many relationship with Tag. I also want to store how many times a Word has been tagged with something. Every time a user submits definition for word X and includes tag Y, I want to increment that Word's count for how many times its been tagged with Y. What would be the best way to setup such a schema? I'm kind of lost here. The only solution I can think of is to store an extra textfield in Word and store num_{tag}=X for each of the tags associated with it. I could also store the tags as part of the Definitions, but to find the number of times a word has been tagged with something … -
Can html5 integrate django rest api?
Can we use only django rest api for backend; html and css for frontend for a webapp, without using django views, only using djnago rest api... -
IntegrityError: UNIQUE constraint failed: accounts_account.user_id, accounts_account.type_of_account
I have a model called account which has a field called type_of_account, I also have another class called safelocks which is inheriting from the account model (the account model is a foreign key). I'm trying to change the type_of_account of all safelock accounts, and I'm doing something like safelocks = SafeLock.objects.all() for a in safelocks: a.account.type_of_account=1 a.account.save() but when I run this, I get this error Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/agozie/Documents/projects/savest_backend/safelocks/management/commands/deposit_to_direct.py", line 17, in handle a.account.save() File "/home/agozie/Documents/projects/savest_backend/accounts/models.py", line 61, in save super(Account, self).save(*args, **kwargs) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/base.py", line 851, in _save_table forced_update) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/base.py", line 900, in _do_update return filtered._update(values) > 0 File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/query.py", line 760, in _update return query.get_compiler(self.db).execute_sql(CURSOR) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1426, in execute_sql cursor = super().execute_sql(result_type) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1097, in execute_sql cursor.execute(sql, params) File "/home/agozie/miniconda3/envs/savests/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, … -
Django: Need help for solve an issue
I have a Model called PoductPurchase with some model attibutes of Product . In this model I will keep quantity of purchased products. I have 2 others Models called RetailInventory and WholesaleInventory . Suppose I bought a product called XYZ and the quantity of that product is 400 ,now I want to divide the quantity of that product in Retail 300 piece and Wholesale 100 piece.I will just give the value in a input field and click 'give to retail' or 'give to wholesale' button and it will update the quantity . how can I do this? help will be highly appreciated. (N.B check the attachment)enter image description here -
Django row level access control approach for ERP app
I am considering using Django to develop an app revolving around case management and accounting, but I am unsure because of security concerns. What I would ideally need is real row level security at the database level, which I can't get with django (or can I?) Let's say I have a model called 'Authority' which represent a firm (it acts as a 'Groups' table). All users belong to one Authority. All other model tables have a 'authority_id' foreign key. I want to make sure no user will ever be able to retrieve rows linked to an authority different than theirs. No admin has access to all the data, at least not via the django app. Anonymous users only access the login/logged-out pages. Solution A is to write a manager function that takes request.user as a parameter and return a filtered query set. Then, use this function everywhere. This seems to be the right way to go, but this solution seems a bit too high level. In case of a coding mistake somewhere, like calling clients.objects.all() instead of clients.objects.for_user(request.user), someone would be getting access to someone else sensitive information. Solution B involves a middleware hack to get access to request.user from … -
Django handling multiple apps in a same project
Lately I started a Django project, I created an app and started to add my models and views in it, as time passed the project get bigger and bigger, more than 20 models, serializations, and a huge views file containing thousands of code lines was the result, in the other hand some of the models (like user profile) might be useful in other projects as well, so I decided to create some new apps (like userprofile) and move related codes to my new app. the problem is my main app is dependent on userProfile app but I cant import it into my main app, I added my new apps into installed apps of settings.py but it didn't affected -
How can we store previous value of some variable in some other variable in python?
Well I want to access previous value of num1 in other function by storing that in other variable. I have tried many ways but can you guys help me. import random num2 = 3 def token(): global num2 print (num2) #It should print previous value of num1 (it is not giving previous value but giving me the same value with num1 every time ) num1 = random.randint(40,90) print(num1) num2= num1 def vcode(): print(num2) #want to access here the previous value of num1 print(token(),vcode()) -
Django cannot recognize package specified in application's __init__.py if i reorganize my applications to an apps folder
I have a Django3 project, let's say "blog". Typical folder structure for applications is: /blog/ /article/ /users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py I want to let the structure to be clean so I put all applications into a apps folder. So now the structure looks like the following: /blog/ apps/ __init__.py article/ users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py I want to use signal function in article apps/application, so the files in article are /blog/ apps/ __init__.py article/ migrations/ __init__.py admin.py apps.py models.py signals.py tests.py views.py users/ ... blog/ __init__.py asgi.py settings.py urls.py wsgi.py manage.py in apps/article/signal.py file: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.text import slugify from core.utils import generate_random_string from apps.article.models import Article @receiver(pre_save, sender=Article) def add_slug_to_question(sender, instance, *args, **kwargs): if instance and not instance.slug: slug = slugify(instance.content) random_string = generate_random_string() instance.slug = slug + "-" + random_string in apps/article/apps.py file: from django.apps import AppConfig class ArticleConfig(AppConfig): name = 'article' def ready(self): import apps.article.signals in apps/article/init.py file: default_app_config = "apps.article.apps.ArticleConfig" if I restart my server, it shows the error: django.core.exceptions.ImproperlyConfigured: Cannot import 'article'. Check that 'apps.article.apps.ArticleConfig.name' is correct. I also tried several settings in apps/article/init.py file like: default_app_config = "article.apps.ArticleConfig" … -
Class diagram of deep learning model deployed in django
i m working on project that is stock market price prediction using deep learning.The Model is then deployed into django framework where the actual and predicted price is shown in graphical form. Anyone can help me in making the uml class diagram of whole project.Thanks -
How to set order_by only on ManytoManyfield in detailview (Django)?
I have 2 models Class and Student. One field within the Class mdel has a ManytoManyField relationship with Student. I want to order the manytomanyfield with first_name in the template. How can I do it? models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=100) class Class(models.Model): student = models.ManyToManyField(Student) subject = models.CharField(max_length=150, unique=True) # many other fields views.py class Class_detailView(LoginRequiredMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html template <div class="row ml-auto mr-auto"> <h6>{{ object.subject }}</h6> {% for student in object.student.all %} <h6 id="class-detail-text" class="mt-2"> {{student.first_name}} <-- want to order here </h6> {% endfor %} </div> right now the names render like this: Freaky Albon Bucky I want it to order like this: Albon Bucky Freaky -
Django ORM join on foreign keys that don't point at each other
tl;dr I'm trying to skip a superfluous join while using Django's ORM Let's say I have models like: # Recipe model not shown, not necessary. class RecipeIngredient(IngredientMixin, models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, related_name='recipeingredients') ingredient = models.ForeignKey( Ingredient, on_delete=models.CASCADE, related_name='recipeingredients') class Ingredient(models.Model): # ...other fields... # M2M field that stores a hierarchy of ingredients. Ingredients can # have multiple parents. parents = models.ManyToManyField( 'self', blank=True, through='IngredientParent', symmetrical=False, ) class IngredientParent(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name='+') parent = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name='+') And I'm trying to figure out which Recipes contain a certain ingredient, but also include Recipes if the parent of an ingredient is our chosen ingredient. For example, "cheese" might be a parent of "cheddar" and if someone selects "cheese", I want to show them all recipes with cheese, but also with cheddar, etc. ANYWAY, I do this: i = Ingredient.objects.get(name='cheese') recipes = Recipe.objects.filter( Q(recipeingredients__ingredient=i) | Q(recipeingredients__ingredient__parents=i) ) print(recipes.query) which gives me the SQL: SELECT -- all Recipe fields FROM "core_recipe" INNER JOIN "core_recipeingredient" ON ("core_recipe"."id" = "core_recipeingredient"."recipe_id") INNER JOIN "core_ingredient" ON ("core_recipeingredient"."ingredient_id" = "core_ingredient"."id") LEFT OUTER JOIN "core_ingredientparent" ON ("core_ingredient"."id" = "core_ingredientparent"."ingredient_id") WHERE ("core_recipeingredient"."ingredient_id" = <ingredient_id> OR "core_ingredientparent"."parent_id" = <ingredient_id>) Looks good. But actually, that INNER JOIN to core_ingredient … -
Django 3.1 TemplateNotFound Exception when Template is Present
I am trying to work towards deploying my application and have done most of my work on Windows. However now that I have moved it over to AWS it does not work anymore. Before anyone links other articles here is a list of all the things I have tried: Adding os.path.join(BASE_DIR,'templates') to TEMPLATE_DIR Changing the permissions of my template My app is in my INSTALLED_APPS variable I have checked that all my render methods are formatted correctly Re-downloaded my project completely Like I said earlier, it works on my Windows machine, just not on AWS or my Mac. Even more strange is that the error says Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/admin/templates/uploads/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /opt/bitnami/python/lib/python3.8/site-packages/django/contrib/auth/templates/uploads/base.html (Source does not exist) And /opt/bitnami/apps/django/django_projects/goFiles/uploads/templates/uploads/base.html is the correct absolute path to the template I am looking for. If I try to cat that file, using that absolute path, it prints to stdout. All this being said I will include some of my code for critical review. views.py def get(self, request, *args, **kwargs): paste = None return render(request, 'uploads/index.html', … -
How to set checkbox state in a table cell based on another cell's value Django templates
I am trying to set a checkbox inside a cell in each row of a table depending on another cell's value in the row. I am accessing the cell with the value, comparing with a pre-determined value (say "L") and if found, marking the checkbox true. So far I have tried the following: HTML <table id="listTable"> <thead> <tr> <th>Doc Num</th> <th>Short Text</th> <th>Locked</th> <th>Lock Type</th> <th>Frequency</a></th> </tr> </thead> <tbody id="filterTableBody"> {% for data in prod_sch %} <tr> <td><a href="{% url 'prod_schdle' data.pk %}">{{ data.doc_num }}</a></td> <td>{{ data.desc }}</td> <td><input type='checkbox' class='chk_locked' id='id_chkbox_locked' disabled='true'></td> <td>{{ data.lock_type }}</td> <td>{{ data.freq }}</td> </tr> {% endfor %} </tbody> </table> jQuery $(function() { $('#listTable tr').each(function() { var val_status_lock = $(this).find('td').eq(3).html(); if ( val_status_lock === 'L' ) { $('.chk_locked').prop('checked', true); } }); }); Currently, checkboxes of all the rows are getting checked true, even for the rows with a different cell value. How to mark checkboxes of only those rows where the cell value is L? -
Does Sentry work for 2 server instances running the same application pointing to 1 project?
I'm new to Sentry and I'm just curious if it's possible to create 1 project in Sentry and make 2 server instances (2 EC2 instances with load balancer) running the same application and both applications (Django) pointing to the same DSN or 1 project in Sentry? -
How to subtract 2 timezone aware dates in python
I have the following function to find the difference in minutes between 2 dates: def time_diff(self): now = pytz.timezone(self.facility.time_zone).localize(datetime.now()) print(later_time) print(earlier_time) second_diff = (now - self.created_at).total_seconds() return second_diff This prints: > 2020-09-12 20:58:26.006197-07:00 > 2020-09-13 01:57:51+00:00 The created_at is an auto generated field created like: created_at = models.DateTimeField(auto_now_add = True) Time zone is stored with: self.facility.time_zone = 'America/Los_Angeles' Why are the times 2 hours off? -
How To Connect Django With Mqtt
i know how to use mqtt with python but i can't connect django app to mqtt background research <http://www.steves-internet-guide.com/mqtt-basics-course/> <https://pypi.org/project/paho-mqtt/#installation> -
Angular + Django Rest Framework rearranging array on SPA, separate severs works okay
I have a random issue happening. When I run Angular and Django one separate instances (ng serve --poll 2000 & python manage.py runserver) my data is transferred as expected and works okay. When I build my angular project and run via apache2 using django as the entry point for the application I have an array which becomes reordered every time. node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --aot --output-path ../backend/static/ang --output-hashing none The array is loaded with the same contents on different pages and can be in any order. There are 4 primary categories and its these which are reordered. The ITEM1, ITEM2, ITEM3 and ITEM4 below. I have no idea why. The code which makes the nodes is below: def get(self, request): response = {} subjects = ['ITEM1', 'ITEM2', 'ITEM3', 'ITEM4'] for subject in subjects: try: alltitles = TitlePageTitles.objects.filter(title__contains=str(subject)) response.update({subject : []}) titleslist = [] returnedJson = {} returnedList = [] returnedJsonString = "" for title in alltitles: titleslist = list(TitlePageItems.objects.filter(ks_key=title.title).order_by('id').values()) newJsonItem = { "id": 0, "ks_key": title.title, "item_text_display": title.title.replace("_"," "), "item_text_link": title.title.replace("_"," "), "order": -1, "page_id": 0, "children": ArrayToNested(titleslist) } returnedList.append(newJsonItem) response.update({subject : returnedList}) except Exception as inst: print(inst) returnedList2 = [] for key, value in response.items(): #logger.error(key) newJsonItem = … -
How can I create a ForeignKey leaving chances for different models for the TO field?
I have multiple product models like below class ProductBase(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True def __str__(self): return self.name class ProductOne(ProductBase): color = models.CharField(max_length=50) class ProductTwo(ProductBase): type = models.CharField(max_length=50) class ProductThree(ProductBase): breed = models.CharField(max_length=50) Each of these products is expected to have an image_set, so I created the model below for product's images class Image(models.Model): product = models.ForeignKey(to=[HERE IS THE PROBLEM], on_delete=models.CASCADE) image = models.ImageField(upload_to='upload-path') How can I get the product field in my Image class to point to any of the products defined above as desired. -
(Django) Signal isn't working but it works in the shell
I have a signal that runs post_save when a new Student is created that goes through their currently enrolled courses and assigns them an instance of the courses' assignments (for scoring). In users/signals.py: @receiver(post_save, sender=Student) def save_student_assignments(sender, instance, created, **kwargs): if created: all_courses = instance.enrolled_courses.all() assignments = Assignment.objects.filter(session_link__in=all_courses) for assignment in assignments: StudentAssignment.objects.create(student=instance, assignment=assignment) I have already been in users/apps.py to import the signal. If I run this exact code in the shell, it will create the StudentAssignment objects and they'll show up for the user. What am I missing here that's not making the signal fire like it should? -
ImproperlyConfigured at /accounts/verification/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Well I am actually trying to add some very simple logic here. All I want to do is that if the vcode or verification code is equal to 5577 than redirect me to the login page. Otherwise if the user enter wrong number than just show an alert message with text that the code is incorrect or invalid and ask him code to enter again. Right now its showing me an error( given in the Title of this question) when I hit the verify button. If more detail or code is required for help than tell me. I will update my question with that information. I shall me very thankful to you. If you guys spend some of your precious time to answering me with a wonderful and helpful information! class CodeCreateView(CreateView,SuccessMessageMixin): form_class = CodeForm def form_valid(self,form): vcode = form.cleaned_data.get('code') if vcode == 5577: user = form.save(commit=False) user.is_active = True success_message = "Verified successfully" success_url = reverse_lazy('login') else : success_message = "Verifification unsuccessful" return super().form_valid(form) # success_url = reverse_lazy('accounts:code_verification') template_name = "accounts/code_verification.html"