Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: how to get object after click
as above I'm wondering how can we get specific object after clicking button. Let's say that in our page we have table which contains data from db and each row has button. How can we recognize in Django which object was clicked? -
Can't update model because already exist when editing
I'm building a database in Django with bootstrap and I have my form for edit, when I try to modify the values of my form in my edit form I can't because ''the model already exist'' I tryed to modify my form but is not working. views.py class encuesta_edit(UpdateView): model = Encuesta form_class = tfg_EncuestaForm template_name = 'encuesta.html' success_url = reverse_lazy('mostrar_encuestas') forms.py class tfg_EncuestaForm(forms.ModelForm): class Meta: model = Encuesta fields = ['id', 'Nota', 'Profesor', 'Curso_alumno'] labels = { 'id': 'id', 'Nota': 'Nota', 'Profesor': 'Profesor', 'Curso_alumno': 'Curso_alumno', } widgets = { 'id': forms.NumberInput(attrs={'class': 'form-control'}), 'Nota': forms.NumberInput(attrs={'class': 'form-control'}), 'Profesor': forms.Select(attrs={'class': 'form-control'}), 'Curso_alumno': forms.Select(attrs={'class': 'form-control'}), } I want to be able to modify mi field 'Nota' with no errors. -
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)
Django project which examines the frequency of occurrence of words on the blog. the project is not finished yet but the scraper did not give any errors before. The error appeared after switching to another komupter, but I'm not sure if it matters when I try to run my scraping script I get this error: ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852) I tried to use the time function but it didn't help import time time.sleep(5) -
Django forms not recognizing a FloatField as changed if initial value is blanked out by user
I am using a formset with initial data. The formset displays correctly in the template. If a user enters new data or edits the data all works fine. If the user blanks initial data, the forms.changed_data does not contain the field that was blanked out. def post(self, request, *args, **kwargs): MemberDataInputFormSet = formset_factory(MemberDataInputForm, extra=0) fs = MemberDataInputFormSet(self.request.POST) if fs.is_valid(): for frm in fs: # changed will not contain a field if user blanks out the value. changed = frm.changed_data I need to know if the result was changed to blank so I can mark the existing result as deleted. I do not want to put a 'DELETE' checkbox on the formset (can_delete) because we audit all edits and deletions. Thanks in advance for any suggestions. -
How to implement dependant drop down in a Django model formset
I am trying to figure out how to create a dependant drop down for a model formset, but all I can find is info on drop downs for forms. My models are: Office, Staff, and Calls Staff has a foreign key linking it to an Office, and Call has a foreign key linking it to Staff. Calls are created via csv upload, after which a user will manually select the correct staff from a drop down. However, I need this drop down to show only Staff linked to the correct Office. I've looked at a the formset docs and a number of tutorials but am coming up short on info specific to this problem; any advice on how to approach this? Would like to avoid any JS if possible. -
How to use html save in media_root in template module using include tag?
I wonder if you could help me on that situation. Basically I`m working in a project which will store dynamic files (css, js, thumbnails and also HTML) by FileField upload. These files will be used posteriorly to build dinamic graphs using D3 JS. The point here is that I`m not achieving the goal by use the HTML file inside to MEDIA_ROOT, once Django always says that it is not part of template. That is the structure of my project documents html js json thumbnails -
Python Cursor - query with positional and named parameters
In my Django application, I would like to use cursor, run a query which contains combination of named and positional parameters. Query with only positional parameters: from django.db import connection cur.execute("SELECT %s AS foo, %s AS bar", (1, 2)) # Results to [(1, 2)] Query with only named parameters: from django.db import connection cur.execute("SELECT %(num)s AS foo, %(num)s AS bar", {'num': 1}) # Results to [(1, 1)] However I have no idea how to correctly parametrize query below: "SELECT %(num)s AS foo, %(num)s AS bar, %s AS baz, %s AS bat" Any ideas and insights are welcome. I also read official docs, but they are not helpful in any way. -
Install Psycopg2 failed. error: invalid command 'bdist_wheel'
I can't install Psychopg2 in my django project after changing the computer. -
python eval speed and perfomance
i have a dictionary let say prices={ "set1": { "price1": 200, "price2": 300 .... }, "set2": { "price1": 200, "price2": 300, .... } } i have a set of rules let say rules={ "set1": { "a>0 and b<10 and price1>300": 1.5, "a+b=10 or c>20": 2.5 .... }, "set2": { "a=c and b!=d or price2<100": 3.5, "a=b": 4, .... } } here a,b,c,d.. are variables defined with some values if any of rules in corresponding set satisfies it will add to prices in prices right now i am using if eval(rule) in for loops but total around near 20000 loops are there so taking atleast 5minutes to execute is there any option to make it faster? i am using django framework for this api -
'NoneType' object has no attribute 'username' on a project which has been working fine for some time
I am working on a project and the models seemed to work fine until I added a feedback field in models. The data in the UserProfile table cannot be accessed and returns the above error. models.py Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') feedback = models.TextField(default=None, null=True) def __str__(self): return self.user.username view for feedback: @login_required def feedback(request): form = FeedbackForm() if request.method =='POST': form = FeedbackForm(request.POST) if form.is_valid(): form = FeedbackForm.save() return render(request, 'NewApp/feedback.html',{'form':form}) forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('first_name','last_name','username','email','password') def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('role',) class FeedbackForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('feedback',) -
Django: get data from fields and insert to 2 tables related to user
I have basic html form with 2 fields (email and phone). I have 3 models: models.py class Person(models.Model): name = models.CharField() surname = models.Charfield() class Email(models.Model): person = models.ForeignKey(Person,editable=False,on_delete=models.CASCADE) email = model.EmailField() class Phone(models.Model): person = models.ForeignKey(Person,editable=False,on_delete=models.CASCADE) phone = models.CharField() in my views.py /imports/ def home(request): context = {'users': Person.object.all()} return render(request,'app/home.html',context) and my home.html {% block content %} {% for user in users %} Displaying user's attributes {% for email in user.email_set.all %} {{ email }} {% endfor %} <form method="POST"> <input type="email"> <input type="label"> <button type="submit">Add data</button> </form> {% endfor %} {% endblock content %} So after clicking button I want to get data from field and add them to 2 tables in my database and this data must be related to clicked user. I know I should use forms.py but I try to do this without it. Is there a easy way to solve this? -
PermissionError: [Errno 13] Permission denied when uploading a file to a Django-Pythonanywhere Website (GNUPG)
I am attempting to implement the Mayan EDMS application into my PythonAnywhere-driven website which uses the Django web framework (1.10). As well, GNUPG is installed and uses GPG files for key ecription, but I am not an expert regarding this. I have successfully loaded in the static files and the EDMS dashboard is operational; however, I am having trouble uploading documents to any file destination I indicate. Django is giving me a permissions error which revolves around my GPG class in the gnupg.py file. I anticipate this error is due to the nature of PythonAnywhere (i.e., I'm deliberately not allowed to perform this). Is there a way I can give myself access to access this file location? Do I have to reference a certain file location? Relevant errors/files that I am editing are: Traceback 2019-06-10 12:54:27,998: Error executing document upload task; Unable to run gpg - it may not be available., <class 'OSError'> Traceback (most recent call last): File "/home/mywebsite/.virtualenvs/env/lib/python3.7/site-packages/gnupg.py", line 751, in __init__ p = self._open_subprocess(["--version"]) File "/home/mywebsite/.virtualenvs/env/lib/python3.7/site-packages/gnupg.py", line 808, in _open_subprocess startupinfo=si) File "/usr/lib/python3.7/subprocess.py", line 756, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.7/subprocess.py", line 1499, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) PermissionError: [Errno 13] Permission denied: '/home/mywebsite/.virtualenvs/env/bin/gpg1' **NO MATCH** … -
Reset email send me example.com url
When I try to use the password password/reset send me a mail with this this url http://example.com/password-reset/confirm/MjM/572-52a21bbd1b80e9377f98/ Any ideas?? -
get_field_display not working in __str__ method (RecursionError)
I have a Repo model with this: TYPE_REPO = 'r' _TYPE_CHOICES = ( (TYPE_REPO, 'Repository Collection'), ) _type = models.CharField(max_length=1, choices=_TYPE_CHOICES) but in the Rest framework, not display 'Repository Collection' when i do this: def __str__(self): return f"{self.title} - type: {self.get__type_display}" and this raise: RecursionError at /api/repos/ maximum recursion depth exceeded while calling a Python object -
Suggest a way to populate database on button click
I am a novice Django programmer, trying to build a basic e-commerce website. I want to add selected items by pressing 'add to cart' button to the database and load the same home page. When clicking this button is am getting error: MultiValueDictKeyError at / 'add_cart' Please suggest any other good method to the same if required My template for the button is : <form action="get"> <button type="submit" class="button1" value="{{ product.id }}" name="add_cart">Add to Cart </button> </form> views.py: def home(request): products = Products.objects if request.method == "GET": product_id = request.GET['add_cart'] if product_id: product = Products.objects.get(id=int(product_id)) if product: product.c_title =product.title product.c_description = product.description product.c_price = product.price product.customer = request.user product.save() models.py Here I have used 'c_' prefix in items for storing cart items for that user class Products(models.Model): title = models.CharField(max_length = 100) body = models.TextField() description = models.TextField() price = models.IntegerField() image = models.ImageField(upload_to = 'images/') customer = models.ForeignKey(User, on_delete = models.CASCADE) total_items = models.IntegerField(default = 1) icon = models.ImageField(upload_to = 'images/') c_title = models.CharField(max_length = 100) c_description = models.TextField() c_price = models.IntegerField() c_total_items = models.IntegerField(default = 1) -
VSCode pylint not displaying relative import failures
I am running a Django application in VSCode, using pylint, and the relative imports errors are not displaying. They were before I installed a newer version of VSCode. I have tried changing user settings and also workspace settings, but still can't get the errors to show. User Settings { "window.zoomLevel": 1, "explorer.confirmDelete": false, "workbench.startupEditor": "newUntitledFile", "window.menuBarVisibility": "default", "explorer.confirmDragAndDrop": false, "workbench.colorTheme": "Visual Studio Dark", "update.enableWindowsBackgroundUpdates": false, "update.channel": "none", "php.validate.run": "onSave", } Workspace settings { "python.linting.enabled": true, "python.linting.pep8Enabled": false, "python.linting.pylintArgs": ["--load-plugins", "pylint_django"], "python.linting.pylintEnabled": true, "python.pythonPath": "/home/justin/anaconda3/bin/python", "python.linting.pylintPath": "/home/justin/anaconda3/bin/pylint" } At the top of one of my functions, a couple of different relative imports. Which one is right or wrong, VSCode should show me. Both imports are in the same project directory in Django, therefore import should be a single '.' I believe. from .performance import get_perf_dates, get_perf_data from ..models import DistributionList, Legend -
maximum recursion depth exceeded while calling a Python object, for counting views
I simply want to count the post pages being opened. so there's views field and update. but I get the following error. And I think it's better to put this logic in models.py not in views.py models.py class Post(models.Model): withOutSub = 'WO' withSub = 'WS' WITH_OR_WITHOUT_SUB_CHOICES = [ (withOutSub, 'withoutsub'), (withSub, 'withsub'),] with_or_without_sub = models.CharField( max_length=2, choices=WITH_OR_WITHOUT_SUB_CHOICES, default=withOutSub, ) title = models.CharField(max_length=100) content = models.TextField(blank=True, null=True) embedded_content = models.TextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) url = models.URLField(max_length=250, blank=True, null=True) views = models.PositiveIntegerField(default=1) likes = models.IntegerField(default=0) rank_score = models.FloatField(default=0.0) with_votes = PostVoteCountManager() objects = models.Manager() image = models.ImageField(upload_to='get_image_path_community', blank=True, null=True) def update_view(self): return self.views +1 self.save() views = property(update_view) -
Django: Module not found
I use Ubuntu 18.04 and have Django with Apache in use. There I would like to include a Selenium script. The bash command works correctly. sudo scrapy runspider -s LOG_ENABLED=False -a category=electronics -a domain=system /home/chef/Desktop/synology/selenium/ginger.py > /home/chef/Desktop/synology/selenium/output.txt 2>> /home/chef/Desktop/synology/selenium/output.txt The integration via Django (via another directory) provides: ModuleNotFoundError at / No module named 'selenium' Request Method: GET Request URL: http://192.168.111.174/ Django Version: 2.1.2 Exception Type: ModuleNotFoundError Exception Value: No module named 'selenium' Exception Location: /home/chef/Desktop/Immo/Immo/Immo/ginger.py in <module>, line 1 Python Executable: /usr/bin/python3 Python Version: 3.6.7 Python Path: ['/usr/bin/python3', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/home/chef/Desktop/Immo/Immo'] What do I have to change? -
Django - perform_create() always creates 2 instances
I have the following model.py file: class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) job = models.CharField(max_length=100, blank=True) photo = models.FileField(upload_to='Images/', default='Images/None/No-img.jpg') def __str__(self): return "%s%s" % (self.first_name, self.last_name) class Meta: ordering = ('created', ) class Clique(models.Model): # holds when the clique was created created = models.DateTimeField(auto_now_add=True) # holds the name of the clique name = models.CharField(max_length=100, blank=False) # holds the members of the clique members = models.ManyToManyField(CustomUser, blank=True) def __str__(self): return self.name class Meta: ordering = ('created', ) Basically, I have a model for the users and a model for cliques. A user can be in multiple cliques and a clique can have multiple users. What I want is that when a user creates a clique, then he should be automatically added to the clique as member. So, in my views.py file, I override the perform_create() method like this: class CreateClique(generics.CreateAPIView): ''' This class creates a Clique for the user who made the request. ''' # define the serializer class serializer_class = CliqueSerializer # we use token authentication authentication_classes = (TokenAuthentication,) # user must be authenticated permission_classes = (permissions.IsAuthenticated,) def perform_create(self, serializer): user = self.request.user # get the user data = self.request.data # get the data the user has sent # first … -
How to connect an interactive webpage to a local csv file?
I have a CSV file which contains Employee data which follows this structure - Name Age Pay Role Duration Jack 34 9000 Manager 5 John 45 12000 HR 10 Jim 56 20000 Admin 12 Kelly 26 10000 Sales 4 Will 40 11000 IT 8 I want to create a dynamic webpage where the user can select a name from a drop-down list of names and is then displayed the age, pay, role etc information of that particular employee. Essentially what I wish to know is if there's a way to link a local csv file to an interactive webpage using Python. I have just started using Django for web-development. I realise that this question might be too broad but I have no clue where to start as Googling threw up no satisfactory ideas (probably because I wasn't even sure what to Google). Any help would be appreciated. -
How to write django model for nested category?
I am making a Class note sharing django(2.1) website for college where categories and sub-categories will be nested: |- Electronic |- Mechanical | |- Automobile | |- Car Design |- Chemistry These categories and sub-categories will be created by admin-user and always can reorder them by changing its parent_id, category tables stacked nestedly as follows, id parent_id category --------------------------------- 1 NULL Electronic 2 NULL Mechanical 3 2 Automobile 4 3 Car Design 5 NULL Chemistry So, What I need to make write a model for this. I already made a blog with django(2.1), but I cant find out solution for this. Please help -
How to change `title, body, and icon` django-push-notification`?
I know lacking of document is known issue. However, the authors of the library seems very busy then I hope someone here might shed the light on me and teammates Softwares: Python 3.7.3 django-push-notifications: master django: 2.2.1 Background: I need to customize web push notification. My targets are title, body, and icon respectively. Attempt: I tried to mimic the APNS and FCM APIs but does not work. In [22]: wps.send_message("Hello World!", title='test', extra={'title': 111}) Out[22]: [{'results': [{}], 'success': 1}] Use dict in the positional argument raises TypeError In [24]: wps.send_message({'title': 'test'}) TypeError: unhashable type: 'slice' Question: How to customized title, body, and message? -
Css file is not loading
I am not able to load the CSS file can someone tell me what is going on ? is path I am using is wrong or something else? is my path mentioned in base file is okie ? [here is base.html][1] [1]: https://i.stack.imgur.com/1QGEE.png [here is settings.py file][2] [2]: https://i.stack.imgur.com/AqXAQ.png -
Django Rest Api - display the username for every user
So I have a model called 'Task' and the task has 'UserProfile's working on them. These 'UserProfile' models are just normal Users but inside the App of the 'Task'. This is the API I have right now: "tasks": [ { "id": 1, "name": "Läs På Internet", "description": "asdasdasdasa", "created": "2019-06-08", "deadline": "2019-06-19", "state": "new", "stickers": [ { "id": 1, "name": "Detta är en sticker", "content": "Sillicon Valley", "created": "2019-06-08", "creator": { "id": 1, "user": 1 } } ], "checkmarks": [ { "id": 1, "name": "Googla", "checked": false } ], "workers": [ { "id": 1, "user": 1 } ] }, { "id": 2, "name": "Läs i böcker", "description": "aaa", "created": "2019-06-10", "deadline": "2019-06-25", "state": "done", "stickers": [], "checkmarks": [], "workers": [ { "id": 1, "user": 1 } ] } ], As you can see every user now just has 'id' and 'user', which are both the ID. How do I get the username for every user and display them in the rest api? # Users class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) #Tasks class Task(models.Model): name … -
How to record and preserve a user-editable Django model instance at a given time
I am working on a Django app where I need to record and preserve a user's details when they complete an action. To use an analogy, say I have an Address model something like: class Address(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) street = models.CharField(max_length=100) town = models.CharField(max_length=50) ... And so on. The user can edit their address at any time. When they complete an action, I need to create a receipt detailing their address at the time. If I created a Receipt model with an address field as a ForeignKey like so: class Receipt(models.Model): ref_num = models.UUIDField(default=uuid.uuid4, editable=False) date = models.models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.ForeignKey(Address, on_delete=models.CASCADE) The receipt would be correct at the time of creation, but if the user then changed their address, it would be incorrect. Is the solution to create a Receipt model duplicating all of the fields in the Address model, so that they can be preserved? class Receipt(models.Model): ref_num = models.UUIDField(default=uuid.uuid4, editable=False) date = models.models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) street = models.CharField(max_length=100) town = models.CharField(max_length=50) ... I am assuming there's a less verbose and more elegant way of achieving this. I need to create a snapshot of the user's address at a given …