Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid Load Key '8' error while loading pickle
I am building a Machine Learning Model in which i have saved TfidfVectorizer to pickle.i am trying to use pickle dump but it is giving me error.It is working fine in Jupyter Notebook but when i am implement in Django api its give me error. final_tf_idf = TfidfVectorizer(max_features=5000) final_tf_idf.fit(reviews) with open("final_tf_idf.pkl", 'wb') as file: pickle.dump(final_tf_idf, file) with open("final_tf_idf.pkl", 'rb') as file: vectorizer = pickle.load(file) -
AssertionError: Relational field must provide a `queryset` in Django Rest API even though one is provided
I'm trying to send my User -> Group foreign key to rest api to get the Group.name for display but when i use the serializer RelationalField(any of them) i get the following error: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`. even though I provided the queryset argument in my serializer class UserSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField(many=True, slug_field='name', queryset=Group.objects.all()) class Meta: model = User fields = ('pk', 'username', 'created_at', 'is_admin', 'group') I still get the error. Setting read_only='True' displayed the value but after that it wont let me change it. -
Django Rest Framework enforce CSRF
I am trying to enforce CSRF for a Django Rest API which is open to anonymous users. For that matter, I've tried two different approaches: Extending the selected API views from one CSRFAPIView base view, which has an @ensure_csrf_cookie annotation on the dispatch method. Using a custom Authentication class based on SessionAuthentication, which applies enforce_csrf() regardless of whether the user is logged in or not. In both approache the CSRF check seems to work superficially. In case the CSRF token is missing from the cookie or in case the length of the token is incorrect, the endpoint returns a 403 - Forbidden. However, if I edit the value of the CSRF token in the cookie, the request is accepted without issue. So I can use a random value for CSRF, as long as it's the correct length. This behaviour seems to deviate from e.g. the regular Django login view, in which the contents of the CSRF do matter. I am testing in local setup with debug/test_environment flags on. What could be the reason my custom CSRF checks in DRF are not validated in-depth? -
Django model using hashmap
I have a question about how to properly model my data in Django (and later in graphene). I have a model exam which consists of date, subject, participants, results where subject,participants, results are references to other objects. I could of course have two lists of participants and results however it would be practical to have a map of type: pseudocode: results= map(participant,result) To be honest I do not know if this is even possible without introducing a additional model object participant_results Any insight very welcome. Benedict -
React native code is unable to send data to django admin
I am a beginner and I'm using Django in the backend of my react native app. I am unable to add data to the django admin panel from my app using fetch method. I am not getting any errors but my data is not getting posted to the backend.I have used the django api as the url in fetch method. Please let me know if any other code snippet is required to check. Would appreciate some help here. export class LoginScreen extends Component { constructor() { super(); this.state = { email: '', name: '', }; } updateValue(text, field) { if (field == 'email') { this.setState({ email: text, }); } else if (field == 'pwd') { this.setState({ pwd: text, }); } } submit() { let collection = {}; collection.email = this.state.email; collection.pwd = this.state.pwd; console.warn(collection); let url='http://10.0.0.2:8000/admin/mdlApp/mdlapp/add/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(collection), }) .then((response) => response.json()) .then((collection) => { console.log('Success:', collection); }) .catch((error) => { console.error('Error:', error); }); } render() { return ( <ImageBackground source={require('../images/bg4.png')} style={styles.bg}> <SafeAreaView style={styles.container}> <Logo /> <View style={styles.container1}> <TextInput style={styles.inputBox} name="email" placeholder="Enter Your Email" placeholderTextColor="#ffffff" onChangeText={(text) => this.updateValue(text, 'email')} /> <TextInput style={styles.inputBox} name="pwd" placeholder="Enter Your Password" secureTextEntry={true} placeholderTextColor="#ffffff" onChangeText={(text) => this.updateValue(text, … -
Convert vimeo link into an embed link in python
I am using Python and Flask, and I have some vimeo URLs I need to convert to their embed versions. For example, this: https://vimeo.com/76979871 has to be converted into this: https://player.vimeo.com/video/76979871 but Not converted My code is below: _vm = re.compile( r'/(?:https?:\/\/(?:www\.)?)?vimeo.com\/(?:channels\/|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|)(\d+)(?:$|\/|\?)/', re.I) _vm_format = 'https://player.vimeo.com/video/{0}' def replace(match): groups = match.groups() print(_vm_format) return _vm_format.format(groups[5]) return _vm.sub(replace, text) -
Command 'python' not found - after I've assigned it as an alias to python3
I'm in the early stages of learning django with python. Have done none of both before. I'm following a course where the instructor has showed how to start a new project using vagrant, and one of the files in the main directory is called Vagrantfile, no file extension (same for the instructor). These are the contents of the file: # -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://vagrantcloud.com/search. config.vm.box = "ubuntu/bionic64" config.vm.box_version = "~> 20200304.0.0" config.vm.network "forwarded_port", guest: 8000, host: 8000 config.vm.provision "shell", inline: <<-SHELL systemctl disable apt-daily.service systemctl disable apt-daily.timer sudo apt-get update sudo apt-get install -y python3-venv zip touch /home/vagrant/.bash_aliases if ! grep -q PYTHON_ALIAS_ADDED /home/vagrant/.bash_aliases; then echo "# PYTHON_ALIAS_ADDED" >> /home/vagrant/.bash_aliases echo "alias python='python3'" >> /home/vagrant/.bash_aliases fi SHELL … -
git push Heroku main - error: src refspec main does not match any
I am just trying to follow the step from heroku site. but on my console when i git push to heroku main? that doesn't work. Some error showing. like below. C:\Users\TORU\Desktop\Website Again\Python\django_files\hero\hero_con>git push heroku main error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/secure-taiga-84539.git' what i do now?? -
Django with extra trailing slash gives 404 when Debug is False
I'm using Django 2.2 The URL pattern defined is urlpatterns = [ path('data/', views.GetData.as_view()) ] When DEBUG=True the following URL is not giving any error https://example.com/data// Note the two trailing slash at the end. But when the DEBUG=False then it gives 404. How can I add a check when Debug is True? -
How I can filter date from last 3 days to today in Django?
I am trying to filter data in django from last 3 days to today, I can do it easily using 2 input box, but I want to filter data using single input box, I am using jquery for this, Please let me know How i can do it. Because it's easy for me when I use 2 input box, but I am unable to filter data when I am using single input box (I am selecting from to to date range in this single input box)... here is my filters.py file... class MainFilter(django_filters.FilterSet): order_date = django_filters.DateFilter( label= "By Date Range", method= 'order_filter', widget=forms.DateInput( attrs={ 'id': 'daterange', } ) ) class Meta: models = Order fields = ['order_date','daterange', 'start_date', 'end_date'] def order_filter(self, queryset, name, value): start = value.start end = value.stop return queryset.filter(start_date__gte=start, end_date__lte=end) here is my jquery code... <script> $(function() { $('#daterange').daterangepicker({ opens: 'left' }, function(start, end, label) { console.log("A new date selection was made: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD')); }); }); </script> here is my viws.py file... def myview(request): datadis= MainFilter(request.GET, queryset=Order.objects.all()) context = {'datadis':datadis} return render(request, 'mainpage.html', context) here is my mainpage.html file... <form method="get"> <div class="row row-xs"> <div class="col-md-8"> <label for="picker1">Select Status</label> {% … -
localStorage not updating Django
Basically i am trying to show the user an alert message only once, when he subscribed to newsletter. So here I am checking whether the user has subscribed to the newsletter by setting a localStorage item 'subscribed' to yes. So that upon refreshing it will not show alert again and again. But when I refresh (localStorage.getItem("subscribed") == 'no') condition executes which it should not. Tell me if I am missing something also if there is a better method available i would like to hear. localStorage.setItem('subscribed', 'no') {% if email %} if (localStorage.getItem("subscribed") == 'no') { alert("Thank you for subscribing") localStorage.setItem('subscribed', 'yes') } {% endif %} -
You have 1 unapplied migration(s) Your project may not work properly until you apply the migrations for app(s): main. Run 'python manage.py migrate'
I am trying to run my project but get this migrations error. I ran makemigrations then ran migrate but once I run migrate I get this error that I don't know where to begin to debug.error I see when I migrate #THE ERROR I SEE WHEN I MIGRATE ^C(djangoEnv) Isaacs-MacBook-Pro:trip_buddy isaac$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main, sessions Running migrations: Applying main.0002_auto_20200428_1944...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 "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 112, in database_forwards field, File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 327, in add_field self._remake_table(model, create_field=field) File "/Users/isaac/Documents/CodingDojo/python_stack/my_environments/djangoEnv/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 188, … -
Receiving a value error, error at line 0 while attempting to deploy my django site to Heroku
1 {% load static %} 2 <!DOCTYPE html> 3 <html> 4 <head> 5 6 <!-- Required meta tags --> 7 <meta charset="utf-8"> 8 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 9 10 <!-- Bootstrap CSS --> Here is the code from my base.html template. {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a> <a class="nav-item nav-link" href="{% url 'profile' %}">Profile</a> <a class="nav-item nav-link" href="{% url 'logout' %}">Logout</a> {% else %} <a class="nav-item nav-link" href="{% url 'login' %}">Login</a> <a class="nav-item nav-link" href="{% url 'register' %}">Register</a> {% endif … -
How do I connect different user model to a single post using the genericforeignkey?
I've created An Account model in the models.py. models. py class Account(AbstractBaseUser): #some properties And I've created other user models containing different properties inheriting from the Account model. class userA(Account): #some properties class userB(Account): #some properties class userC(Account): #some properties Lastly I created the post class. Note that I've limit the genericforeignkey to only userA, userB and userC. from django.contrib.contenttypes.fields import GenericForiegnKey from django.contrib.contenttypes.models import ContentType class post(models.Model): #post data limit=#limited to userA, userB, userC user_name=models.ForeignKey(ContentType, limit_choices_to=limit) object_id=models.CharField(max_length=500) content_object=GenericForeignKey('user_Name', 'object_id') This is my form. forms.py class post_form(ModelForm): class Meta: model=post fields=["Post"] This is my views. views.py class create_post_view(CreateView): form_class=post_form def get_form_kwargs(self, *args, **kwargs): kwargs=super(create_post_view, self).get_form_kwargs(*args,**kwargs) kwargs["object_id"]=self.request.user.id kwargs["user_name"]=self.request.user.id return kwargs def form_valid(self, form): ss=form.save(commit=False) kwargs["user_Name"] =self.request.user.id kwargs["object_id"]=self.request.user.id ss.save() This codes don't work, I kept seeing this error: ValueError Cannot assign: "post.user_Name" must be a "ContentType" instance. How can I solve this? -
Django "Model.objects.create()" linking two fields/relationship
kindly correct me with the tittle if it is wrong or misleading, thanks. I am very new to Django Python. I am using Django 3.1.1. My question is about the "Model".objects.create(), I use it with ajax to save or create data in my Logger model. Question: How can I link the Logger.userprofile to UserProfile.user using Logger.objects.create() or what is the next thing to do to linked the two fields? My UserProfile model is already linked to the User model via OneToOneField but was saving data using form.save(), and this was successful. below is what I have constructed so far by following numerous tutorials. This is already working and it is creating data in my Model, I just need to add the link between the UserProfile and the Logger for the sake of easy identification of the log created. Log is created in the Logger Model via qrcode scan. Views.py def processQRCode(request): if request.method == 'POST': qrcode_uuid = request.POST['qrcoderes'] logged_in = request.POST['logged_in'] logged_in_location = request.POST['logged_in_location'] Logger.objects.create( qrcode_uuid = qrcode_uuid, logged_in = logged_in, logged_in_location = logged_in_location ) return HttpResponse('Success!') Models.py UserProfile Model class UserProfile(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = models.OneToOneField(User, related_name='userprofile', null=True, on_delete=models.SET_NULL) qrcode_uuid = models.UUIDField(unique=True, default=uuid4) … -
deploying Django on amazon linux 2
Hi I hope sonmeone can help me. I am deploying a django webapp on amazon linux 2 but it always give me this error on the borwser Forbidden You don't have permission to access this resource. Meanwhile on /etc/https/logs/error_log file, I walays get these error ImportError: No module named site [Fri Sep 25 14:18:57.888354 2020] [core:error] [pid 3930] (13)Permission denied: [client xxxx.xxxx.xxxx.xxx] AH00035: access to /test denied (filesystem path '/home/ec2-user/project') because search permissions are missing on a component of the path And also I have concern I am using python3 on the venv but upon checking the error logs i saw this [Fri Sep 25 14:18:50.978008 2020] [:warn] [pid 2306] mod_wsgi: Compiled for Python/2.7.14. [Fri Sep 25 14:18:50.978015 2020] [:warn] [pid 2306] mod_wsgi: Runtime using Python/2.7.18. [Fri Sep 25 14:18:50.979217 2020] [mpm_prefork:notice] [pid 2306] AH00163: Apache/2.4.46 () mod_wsgi/3.4 Python/2.7.18 configured -- resuming normal operations [Fri Sep 25 14:18:50.979252 2020] [core:notice] [pid 2306] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' is this ok? Please someone can provide me links on how to setup django. it is my first time to use this <VirtualHost *:80> ServerName www.testwebsite.co.jp ServerAlias testwebsite.co.jp ServerAdmin emai@email.co.jp DocumentRoot /var/www/html <Directory /home/ec2-user/project/testsite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess … -
Please help me creating such models that are visible to all
enter image description herePlease see the image link at the end for better understanding and thank you for visiting my question So I am making a website using Django framework and I am making a website which has around 8 to 9 applications so the question is that I have made something called news updates and this will be a type of database in which there will be an image as well as a title and description and the image will be clickable URL so that thing is that I have registered the models and the news update feature with the Django admin page and the thing is that a like I have a 2 to 3 users and I have also made a login logout system so whenever I post an update so it is only visible to the user in which the update is created as you can see in the images. so how can I make such items or like such a database models which are visible to all despite of the user is even logged in or not or if it is any user like a update which is compulsary for all users to see enter … -
How to create scenario for multi dimensional object definition in Django model
In my Django app, I have a situation where characteristic values (properties) have to be stored at different levels of the characteristic. Presently I have created three levels to define these characteristics using models as described: Models for characteristic: CharA CharB CharC The characteristic values stored in the models (above) are being used in the model (ObjList) which defines the object as shown below: class ObjList(models.Model): obj_id = models.AutoField(primary_key=True, ...) short_text = models.CharField(max_length=55, ...) extended_text = models.CharField(max_length=255, ...) obj_char_a = models.ForeignKey(CharA, ...) obj_char_b = models.ForeignKey(CharB, ...) obj_char_c = models.ForeignKey(CharC, ...) Down the line I realized that there are situations where I may need further sub-division of the object characteristics, like another dimension to the object definition. However, the same is not true for all object types and hence my dilemma. Do I create another model to store information on the new characteristic? Then again, there may be cases where there might yet be a new dimension to the object and thus requiring me to create yet another model?! I tried to find ways to create new models dynamically as per the situation. However I gather that this is either not feasible in Django or is not advisable as it may … -
"module 'channels' has no attribute 'layers'" error in Django ASGI application
In my app, after any user logged in, send status info to other users with channels, celery and websocket. @shared_task def send_status_info(user,status): channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)( "all_users", { 'type': 'send_status_info', 'message':{"user":user.username,"status":status} } ) for this, I use the following settings as shown official document. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } The application although it is running in development environment, it does not work in production environment. As web server I try only daphne or daphne+gunicorn but I get this error on both: "module 'channels' has no attribute 'layers'". Thanks for help. -
Saving multiple records in django models
I've designed a table to fetch multiple inputs in Django. How can I save all the rows of the table at the same time in models of the app each being a different entity. -
How to implement django SSO using dj-rest-auth and django-rest-framework-simplejwt
Has anyone implemented this experimental feature JWTTokenUserAuthentication backend? So I've been trying to build a Django project that handles authentication centrally on a standalone basis using django-rest-framework-simplejwt. And other Django Rest Framework projects that use this for authentication. All projects will have their own databases. I am not quite sure what goes into the database section in settings.py of both the auth project and other projects. The documentation mentions something about JWTTokenUserAuthentication backend as an experimental feature and is quite inadequate. I have done some research and found I may have to use a remote user login or set up a proxy server. Can someone point me in the right direction? -
django model field for sets of values
I have a django model called Product. I wish to have a set of values. Specifically, each product will have different sizes (say 500 mg, 1 g, bulk order; the specific sizes will be differ for each product), along with it, I should have corresponding cost. For example, 1g - $500; 5g - $1500; bulk order - ask for quote. For another product, this could be: 500mg - $100; 1g -$170; 10g -$1000; Which django model field should I use? How can I implement this feature? Thanks! -
Django - Text Isn't Moving Down?
so I made a class and named it ">My Hero Academy<" I am trying to make it move down But its not moving down I am not sure whats the problem Image I am trying to move it lower then my title then a little left but its not moving at all <body> <div class="sidenav2"> <h5>One Piece</h5> </div> </body> </html> {% endblock %} my full home page code {% extends 'main/base.html' %} {% block title%} home {% endblock %} {% block content %} <html> <head> <style type="text/css"> .sidenav2 a { padding:6px 8px 6px 216px; left:100px; top:100px; text-decoration: none; font-size:35px; color: #818181; display:block; } </style> </head> <body> <div class="sidenav2"> <h5>My Hero Academy</h5> </div> </body> </html> {% endblock %} -
Python: TypeError: can only concatenate str (not "int") to str
This happens when I was trying to retrieve fields from a django model object ---> 52 def __str__(self): 53 return 'cpu: {%d}'.format(self.cpu_index) 54 TypeError: can only concatenate str (not "int") to str Also tried with % where cpu_index is an int and the same case happens with decimal.Decmial -
is it posible to limit objects displayed on the Admin dashboard using permissions in django?
Any way I can add permission for a whole model where only users meeting a certain condition e.g belonging to a certain country can view the objects in the Admin dashboard? I'm using Django gurdian for permissions. To be more specific, I only want the Items here https://github.com/CodeForAfrica/gmmp/blob/master/gmmp/settings.py#L244 to only be visible to users in a certain country