Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to show my post only to my friends in django
I want to show my post only to my friends, How can I filter my post only to my friends? I have tried to filter in html code but as my friends get more, it repeats my post more (I mean repeat one post few times ) My models.py class PostUser(models.Model): posttype = models.CharField(max_length=3000, default='postuser') content = models.TextField(null = True, blank= True) media_image = models.FileField(null = True, blank= True) media_video = models.FileField(null = True, blank= True) per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) datetime = models.DateTimeField(auto_now_add=True) like = models.IntegerField(null=True, blank=True) comment = models.IntegerField(null=True, blank=True) share = models.IntegerField(null=True, blank=True) user_pk = models.IntegerField() class Friends(models.Model): # Sender friend_one = models.IntegerField() # Reciver friend_two = models.IntegerField() per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone') status = models.CharField(max_length=3000, default='active') datetime = models.DateTimeField(auto_now_add=True) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) and this is my views.py allmyfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk)) -
How to auto-update the slug field in Django admin site?
I know how to auto-populate the slug field of my Blog application from post's title, and it works fine. But if I edit the title the slug field is not changing. Is there any way to have it updated automatically? I use Django's admin site. Thanks. -
Django define update_fields when creating objects in model
I am using a SQL Server table with period columns, and my model in Django is defined as class Client(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=40) sys_start_time = models.DateTimeField(db_column="SysStartTime") sys_end_time = models.DateTimeField(db_column="SysEndTime") class Meta: managed = False db_table = "client" where sys_start_time and sys_end_time are period columns. Due to sql server rules, any query defining values for these columns are invalid, which means that the sql query django generated when creating or updating this model won't work. I managed to exclude them in update_fields when performing update so that django will generate queries without period columns, but I can't use the same update_fields parameter when creating an object, otherwise I get an error saying Cannot force both insert and updating in model saving. Is there a way to let django ignore certain fields when creating an object? OR Is there a way to tell Django to send DEFAULT (sql server keyword, not string) as the value for these period columns? -
How to submit two forms in one Update View
I'm searching how to submit two forms with two different submit buttons in one view class EditAvatarForm(forms.ModelForm): class Meta: model = Person fields = ('avatar',) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user_created = None avatar = forms.ImageField(required=True, ) self.fields = OrderedDict( [ ("avatar", avatar), ] ) def clean_avatar(self): image = self.files.get('avatar') if image: try: creator = None if self.instance: creator = self.instance # ?That simple? Yes!: return ImageFile.objects.create( image_file=image, creator=creator ) except IOError: self.add_error('avatar', _("Unknown image type")) return None def clean(self): return super().clean() class EditProfileForm(forms.ModelForm): class Meta: model = User fields = ("username", "first_name", "last_name", "email",) this is the forms.py I would like to be able to change the avatar and the user informations in a single view. Person is a model related to User with user = models.OneToOneField( User, blank=True, null=True, on_delete=models.CASCADE ) and related to imageFile with avatar = models.ForeignKey( ImageFile, default=None, blank=True, null=True, related_name="persons", on_delete=models.SET_NULL, ) -
Two model fields and one form field
I have two fields in Model and one form field. The widget AutocompleteInput is attached to form input. If the user selects an element from the autocompleteinput list in the widget, I want the data to be save to one field model. If the user enters their own string, I want the data to save to another field in the model. So i need to clean the user input, check if the inputs matches any autocomplete option, if so, need to save to the first model, otherwise save to other, but i dont know how to save custom string to db. models.py class Something(models.Model): name = models.CharField("name", max_length=50, default='', blank=True) title = models.CharField("title", max_length=50, default='', blank=True) forms.py class SomethingtForm(DisableModelForm): name = forms.CharField(label='Name', widget=AutocompleteInput( id_key='name', display='name', field_name='something_name', url='/api/something?search=', ), required=False) title = forms.CharField(required=False, max_length=32) def __init__(self, *args, **kwargs): if kwargs.get('instance', None): instance = kwargs['instance'] kwargs['initial'].update({ 'name': instance.name, 'title': instance.title, }) def clean_name(self): if self.instance and hasattr(self.instance, 'blabla'): return self.initial['name'] return self.cleaned_data['name'] def clean_title(self): if self.instance and hasattr(self.instance, 'blabla'): return self.initial['title'] return self.cleaned_data['title'] def clean(self): cleaned_data = super().clean() name = cleaned_data.get('name') title = cleaned_data.get('title') if title not in Blabla.queryset.all(): #autocomplete options ........... # if input doesnt match autocomplete options i want to … -
SMTPServerDisconnected at /password-reset/
Connection unexpectedly closed: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') Less secure app access are allowed on my gmail account -
TypeError: connect() argument 4 must be str, not WindowsPath . /*The Error that i m getting in my simple login django project*/
System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. February 17, 2021 - 19:52:27 Django version 3.1.6, using settings 'felix.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. C:\Users\FELIX\OneDrive\Desktop\Projects\django login2\felix\felix\settings.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 459, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migrations if self.has_table(): File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 259, in cursor return self._cursor() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 235, in cursor self.ensure_connection() File "C:\Users\FELIX\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
How do you implement CSRF tokens in django rest framework?
I have noticed that when using django and you make a post request, using a form for example, django asks you to add the csrf token, but when I was fetching data from an api created with django rest framework with react I realized that when I didn't send the csrf token there wasn't any error with the application. In this app I am using token authentication with knox and I have seen some posts about how to use csrf token with session authentication. My question is if token authentication does not need the csrf tokens or are they passed automaticaly by react? Thanks in advance. -
JavaScript cloning an element with a loop inside
I'm new to coding/web development, I'm using JavaScript function to clone an Element which has a loop inside it. But the function is not working. Following is my HTML code: <table> <tr> <td id="add"> <Select class="selectpicker form-control" name="audience"> <option value="all">All</option> <option value="teachers">Teachers</option> <option value="parents">Parents</option> <option value="students">Students</option> {% for i in range(1,14) %} <option>{{i}}</option> {% endfor %} </Select> </td> <td><button type=button onclick="newfield()" class="btn btn-outline-success"> + </button> <button type=button onclick="remove()" class="btn btn-outline-danger"> - </button> </td> </tr> </table> And following is my JavaScript function: function newfield(){ var newselection =document.getElementById("add").firstChild; var newfield = newselection.cloneNode(true); var x = document.getElementById("add") x.insertBefore(newfield, x.firstChild); } function remove(){ var x = document.getElementById("add"); x.removeChild(x.lastChild); } but when I manually insert the numbers from 1 to 13 in attribute. the function works perfectly. As I'm new to coding space I'd like to know whether there's a way to overcome this problem. Thank you. -
Python requests in CRON job getting called twice
I'm not really sure why but each request I make with the Python requests library is getting called twice. I am sure that the CRON job is not called twice as I'm logging a message to a logfile every time it runs. What might be the possible issue for this? Here is a screenshot of the calls: If you take a look at their times, they're very close to each other. -
Newer version of Django URL is not working , "throws not found error " while passing string arguments
The newer version Django URL throws not found error while earlier version works as expected url(r"^delete_comments/(?P<id>\w+)/$",DeleteComments.as_view(),name="del_comments"), url('delete_comments/<str:id>/',DeleteComments.as_view(),name="del_comments"), I am just passing a string a parameter in the URL,the django literally throws there is no such URL in the system -
django and wsgi outputs blank page with no error
When I run my django server with uwsgi (probably) my static files are not loading correctly. My connection is fine since I get 200 OK, but the page is blank. Response seems to be fine: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Label It</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </head> <body style="margin: 0"> <div id="main"> <div id="app"> </div> </div> <scipt type="application/javascript" src="/vol/web/static/frontend/main.js"></scipt> </body> </html> my config for UWSGI: uwsgi --http 0.0.0.0:8000 \ --master \ --module label_it.wsgi \ --processes 2 \ --static-map /static=/vol/web/static/frontend My application runs in docker container, and I tell django to put static files to /vol/web/static, and I can confirm- those files are there (main.js is there). Django app setting.py : STATIC_URL = '/static/' MEDIA_URL = '/static/media/' STATIC_ROOT = '/vol/web/static' MEDIA_ROOT = '/vol/web/media' On development, everything is fine. UWSGI output on console when connecting: [pid: 34|app: 0|req: 2/3] 172.18.0.1 () {38 vars in 721 bytes} [Wed Feb 17 16:03:00 2021] GET / => generated 680 bytes in 0 msecs (HTTP/1.1 200) 6 headers in 180 bytes (1 switches on core 0) -
django.db.utils.ProgrammingError: column does not exist LINE 1
I've created a boolean column in an existing Model and Migrated. I can see the column in the table with default values. but while running ./manage.py test, I'm getting the below errors. psycopg2.errors.UndefinedColumn: column xxxx does not exist LINE 1: django.db.utils.ProgrammingError: column xxxx does not exist LINE 1: -
How to filter query value in one if there is few of same value in Django
My views.py, I want to show only one value of the same value filtermyfriends = [] myfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk)) for checkf in myfriends: if Friends.objects.filter(Q(friend_one = checkf.friend_one) | Q(friend_two = checkf.friend_two)) not in filtermyfriends: filtermyfriends.append(checkf) -
Rendering Django Model to HTML
I made a Django app to fill my single html pages. This is my model.py class Flatpage(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=40) short_description_text = models.TextField(blank=True) content = RichTextField(blank=True, null=True) published_date = models.DateTimeField('Published_Date') meta_keyword = models.CharField(max_length=30) meta_description = models.TextField(blank=True) How should views.py look like to print the output of my model on the relevant pages? How can I print my model output according to slug to single page htmls (About us, FAQ, etc.) -
Django-rest-auth multiple Google Apps
I am writing a Django REST Application that uses Django-all-auth plugin. I want the user to be able to login both via their Mac or Website. So in my Google Console, I have created 2 OAuth2.0 Apps. One for Mac and one for Website, the difference being that the website one has the redirect URI of my website and the Mac one to have redirect URI of https://google.com Under my Social Applications in admin, I have added both Apps with their Client IDs and Secrets. Now, after logging the user in with Google account, I POST the "access_token" returned to Django-all-auth google login url at my REST server. Before I only had the Website app and it used to work fine but now I am getting this error: Does it not allow you to have 2 Google Apps attached at the same time? Is there a setting I am unaware of to allow 2 Google OAuth2.0 apps? I couldn't find anything in the docs for this: https://django-allauth.readthedocs.io/en/latest/overview.html Any suggestions will be highly appreciated. -
Django Ajax Get method giving 405 (Method Not Allowed) error
$(document).on("click", "#btn_create_card", function () { url1 = $(this).attr("data-url"); $.ajax({ url: url1, type: "GET", data: { description: "test", }, success: function () { console.log("sucess"); Get_CardView(); }, }); }); Below is my Class-based view for the call class CreateCard(View): def get(self, request): description1 = request.GET.get('description', None) print(description1) return redirect('/') but I am getting below error message GET http://127.0.0.1:8000/create_card?description=test 405 (Method Not Allowed) below is my url path('create_card', views.CreateCard.as_view(), name='create_card'), -
pylint django with django-configurations
How to make pylint-django work together with django-configurations ? I've setup a Django project in VS code with pylint and django-pylint as linter. I have a conflict with django-configurations, a package that I use to have different config file depending on environment. I specify django-settings-module in order for django-pylint to understand django project. Settings.json in vscode looks like this : { // ... "python.linting.pylintArgs": [ "--load-plugins", "pylint_django", // Works fine // "--django-settings-module", "project.settings" // Do not work anymore when adding this ], ], // ... } Also I've tried the same config file with another django project that does not use django-configurations and pylint django works well with second line on. -
How to repeat a many-to-many relationship in Django?
I have these models in my Django app from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Animal(models.Model): name = models.CharField(max_length=100, unique=True) class AnimalList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) list = models.ManyToManyField(Amimal) I want to add the same pokemon to the same list twice: >>> animal = Animal.objects.create(name='milla') >>> user = User.objects.create(username='user') >>> list = AnimalList.objects.create(user=user) >>> list.list.add(animal) >>> list.list.add(animal) >>> animal.save() The animal is added only once, though: >>> list.list.all() <QuerySet [<Animal: Animal object (3)>]> I expected that, the documentation is explicit that Adding a second time is OK, it will not duplicate the relation: Yet, I do want to repeat the animals. How could I do that? Is it possible by using ManyToManyField? -
Store multiple inputs values of form in single json to store in model field. - Django
I am working on a project which is online printing ordering service. Here on the order page I am getting different attributes of product in radio button list in the form, and all the attributes I want to store in a single json in database. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) # this is the order table , there is a "attribute_field" I wantto store the attributes in this field # as JSON. class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.ImageField('Product Quantity', max_length=10, default=500) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) order_date = models.DateField("Order Date", auto_now_add=True, null=False) order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False) order_desc = models.CharField("Details for Product", max_length=1000, null=False) product_img = models.ImageField("Template Image", null=False) address = models.CharField("Customer Address ", max_length=100, null=False) state = models.CharField("Customer State", max_length=30, null=False) city = models.CharField("Customer City", max_length=30, null=False) postal_code = models.IntegerField("Area Pin Code", null=False) order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size … -
Django raising 'django.urls.exceptions.NoReverseMatch: Reverse for '/' not found. '/' is not a valid view function or pattern name.' in base.html
I am making a website using Django and DTL. I wanted to comment the embedded javascript in my code, but it happens that Django Template Language does not comment the same way as plain HTML. Traceback when I go to ***any ***page: NoReverseMatch at / Reverse for '/' not found. '/' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for '/' not found. '/' is not a valid view function or pattern name. Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /usr/local/bin/python3 Python Version: 3.9.0 Python Path: ['/Users/william/Documents/coding/WDTP/almostanything/django/almostanything', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Users/william/Library/Python/3.9/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'] Server time: Wed, 17 Feb 2021 09:43:34 -0500 Error during template rendering In template /Users/william/Documents/coding/WDTP/almostanything/django/almostanything/templates/base.html, error at line 20 Reverse for '/' not found. '/' is not a valid view function or pattern name. 10 display: none; 11 } 12 /* tr's 13 .tr1{top:4px;right:4px;}.tr2{top:4px;right:39px;}.tr3{top:4px;right:79px;} 14 .shadowed{box-shadow:3px 3px 1px 0px blue;} */ 15 </style>{% endblock %} 16 </head> 17 <body> 18 {% block script %} 19 <script> 20 # var st = document.getElementById('shadowtopbar'); 21 # function load(); 22 # st.style.display = "block"; 23 # setTimeout(500, load()); 24 </script> 25 {% endblock … -
Changing img tag src value with javascript with the Django framework
I am trying to load a random image from a dictionary on page load using Javascript. This is the HTML <div class="img-container"> {% load static %} <img id="qimage" src="{% static '' %}"></img> </div> So basically I want to change the src to a random generated image src from dictionary on page load: this is the Javascript: window.onload = function(){ var image = document.getElementById("qimage"); let src = getRandomImage(); image.setAttribute("src",src); } And this is the generate random image function: function getRandomImage(){ var keys = Object.keys(dict); var index = getRandomInt(0,keys.length); var selection = keys[index]; var image = dict[selection][0]; return image; } and lastly this is the dictionary: var dict = { "barrackStreet":["{% static 'images/hard/bstreet.jpg' %}",{"lat":51.893897,"lng":-8.477632}], "GrandParade":["{% static 'images/hard/gparade.jpg' %}",{"lat":51.893897,"lng":-8.477632}], "PatricksHill":["{% static 'images/hard/phill.jpg' %}",{"lat":51.893897,"lng":-8.477632}], }; -
how can i extract from my django model into a javascript variable (Django)
How can I extract data from my django model and put it into a javascript variable. I have a music player that uses javascript, within the JS code there is a variable 'trackUrl' which is a list of the track paths. How can i use my music model to extract the track and place into this JS code ? I've been trying to find a solution but was only advised to use Django REST framework, is there another method I could use. Could you please explain in detail as I'm still learning Django. Thanks This is the music player : https://codepen.io/himalayasingh/pen/QZKqOX models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio') title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', blank=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py @login_required def music_upload(request): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): user = request.user song = form.save(commit=False) song.artist = user song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile') else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) -
Caller Device Detection of a Django-Python Rest API
We are developing a REST API using Python-Django. API is consumed by IOS and Andriod native apps and a browser-based web application. With each user login, we need to detect and store the device users are connecting. Right now I have tried to achieve this using django_user_agents. It detects the device correctly when calls are coming from browsers. But it can't detect the devices of calls from native apps. So I'm just guessing django_user_agents works only for browser-originated calls. I'm kinda new to python and Django world. Any help on how to detect calling devices universally would be really appreciated. Thanks, -
Plesk Django Server Error 403 Forbidden You do not have permission to access this document
Error log: [Wed Feb 17 14:39:51.592472 2021] [autoindex:error] [pid 147736:tid 140504350598912] [client 203.78.146.30:0] AH01276: Cannot serve directory /var/www/vhosts/allfamousbd.com/django-app/django-public/allfamousbd/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm,index.shtml) found, and server-generated directory index forbidden by Options directive