Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Migrating Django project from production to local SQL server
I have Django project which is working fine in production(using Mysql as Database). I am running Mysql server locally in my PC(using XAMPP) , i have a done appropriate changes in setting.py as shown below. BUT when i try to run "python manage.py migrate MYAPP" i am getting an error as shown below. Also tried different command (same error) --> python manage.py syncdb --> python manage.py makemigrations MYAPP --> python manage.py runserver ..etc., It is not creating any table in SQL backend , any suggestion ? Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'MYAPP', 'USER': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } ERROR _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1146, "Table 'MYAPP.role' doesn't exist") -
How to trigger empty value validation in Django functional test?
I am new to Django and I am now reading the "Test-Driven Development with Python' book for learning. However, when I want to test the empty-value validation, the unit test is ok, but the functional test is failed. I am now using Django 2.1, Python 3. I have tried my best to check the reason of the problem but still failed to pass the functional test models.py ... class Item(models.Model): text = models.TextField(default='') list = models.ForeignKey(List, default=None, on_delete=models.CASCADE) views.py ... def new_list(request): list_ = List.objects.create() item = Item.objects.create(text=request.POST['item_text'],list=list_) try: item.full_clean() item.save() except ValidationError: list_.delete() error = "You can't have an empty list item" return render(request, 'home.html', {"error": error}) return redirect(list_) test_views.py (Unit Test-Successful) ... def test_validation_errors_are_sent_back_to_home_page_template(self): response = self.client.post('/lists/new', data={'item_text':''}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') expected_error = escape("You can't have an empty list item") self.assertContains(response, expected_error) test_list_item_validation.py (Functional Test-Failed) ... def test_cannot_add_empty_list_items(self): self.browser.get(self.live_server_url) self.browser.find_element_by_id('id_new_item').send_keys(Keys.ENTER) error = self.browser.find_element_by_css_selector('.has-error') self.assertEqual(error.text, "You can't have an empty list item") base.html (All html files extend from this) ... {% if error %} <div class="form-group has-error"> <span class="help-block">{{ error }}</span> </div> {% endif %} I expect that both the unit test and functional test are correct, but the actual result is the unit test is passed but … -
How can I convert the DateTimeField in Django from UTC to enduser's timezone (usually PST) when querying a Django model?
I'm querying a Django model connected to a table in my Postgres database that contains a datetime stored in UTC. My query code looks something like this: query_set = table_object.objects.values() One of the columns in the query set is the datetime value in UTC. The model looks like this: class ops_inbox_view(models.Model): requested_date = models.DateTimeField() other_item = models.CharField(max_length=20) other_item2 = models.CharField(max_length=40) other_item3 = models.CharField(primary_key=True, max_length=10) other_item4 = models.CharField(max_length=50) other_item5 = models.CharField(max_length=50) other_item6 = models.CharField(max_length=50) I want to convert this into PST or robustly in the enduser's local time zone. My current solution is to use pandas with dt.tz_localize and dt.tz_convert after loading the query set into a dataframe but I'm trying to find a solution that is easily manageable in one location of the project file structure of the app. In my settings.py, I have TIME_ZONE set to 'US/Pacific' but because I'm using Pandas, the conversion to PST is not automatically done and will have to change many lines of code in my views.py to make the conversion with pandas. Is there a way to not use Pandas and instead either make the field timezone aware or make the explicit conversion in the query code? Also looking for any other best … -
What type of options apply to the SlugField?
If we see the documentation of Django, we see this; SlugField class SlugField(max_length=50, **options) **options : is a kwargs but Django doesn't show me anything about of what other parameter I can use it. I appreciate if somebody help me. https://docs.djangoproject.com/en/2.1/ref/models/fields/#slugfield -
Wget, Urlib and Requests failing
I'm running a Django server with Nginx that is trying to download an image from a wordpress site. Wget, urlib and requests work perfectly on my local computer but they time out on my server. I'm thinking about some sort of cross origin or related issue. How can I fix this? -
I have a wordpress install on a separate server from my main app, and I want to serve it to users through /blog
I want to proxy /blog to a different server with nginx. I have this block, but it seems right now to just send me back to homepage of the main app I have written the below in nginx.cong of the main app, which I feel like should work. Do I need to write anything on the blog's server side, which is also using nginx? location /blog { proxy_pass http://the-blog-ip; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } I expect this to proxy to the blog server, but instead I am redirected to the homepage -
Django delete original image after ImageProcessor converted
im using the follwing model field to store images: views.py ... postcover = fields.ImageField( upload_to=get_file_path_user_uploads, validators=[default_image_size, default_image_file_extension], dependencies=[FileDependency(processor=ImageProcessor(format='JPEG',quality=99,scale={'max_width': 700, 'max_height': 700}))]) ... If i upload an picture to that field django create two unique files. It first is the original one and the second the proccessed one from ImageProcessor. How do i delete the original one after processing? Thanks -
Unsupported here action: [()]
Upon postback Django shows a 404 page that says Unsupported here action: [()]. I'm not sure about the relevant pieces of the code that could lead to this. My form looks like this: <form method="POST" action="{% url 'pqawV1:index' %}" id="quiz_form"> <input type="submit" class="action-font-size" value="{% trans 'Filter targets' %}" /> </form> In views.py the view function is simply defined as def index(request: HttpRequest): . In the project's urls.py file I have the following line for this application: urlpatterns = [ path('admin/', admin.site.urls), path('', include('pqawV1.urls')), ] \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then in application's urls.py I have the following code: app_name = 'pqawV1' urlpatterns = [ path('', views.index, name='index'), ] Could you tell me what could be the reason for this error or which else pieces of the application to provide here? -
How do I open a URL when there's a special character in the URL (but not the query string)?
I'm using Python 3.7. I have a URL with a "ñ" character in it, but that character does not appear in the query string. Unfortunately, this code results in an error when I try and open the URL ... req = urllib2.Request(url, headers=settings.HDR) html = urllib2.urlopen(req).read() which results in the error UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 75: ordinal not in range(128) I thought I could urlencode the url, but then this code req = urllib2.Request(urllib.parse.urlencode(url), headers=settings.HDR) html = urllib2.urlopen(req).read() results in the error TypeError: not a valid non-string sequence or mapping object I can't win! How do I successfully open this troublesome URL? -
Python3.6 requests error: RecursionError: maximum recursion depth exceeded while calling a Python object
I am using from multiprocessing.pool import ThreadPool and running requests in parallel. These requests call two external api libraries, here is my stack trace, has anyone encountered this issue? Traceback (most recent call last): File "./products/classes/api/amazon_api.py", line 46, in find_item SearchIndex=search_index, IdType=id_type) File "./vendor/amazonproduct/api.py", line 417, in item_lookup return self.call(**operators) File "./vendor/amazonproduct/api.py", line 298, in call fp = self._fetch(url) File "./vendor/amazonproduct/api.py", line 206, in _fetch 'User-Agent': USER_AGENT File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/requests/api.py", line 72, in get return request('get', url, params=params, **kwargs) File "/home/ec2-user/MYVENV/lib/python3.6/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/home/ec2-user/MYVENV/lib/python3.6/functools.py", line 370, in _method return self.func(*call_args, **call_keywords) File "/home/ec2-user/MYVENV/lib/python3.6/functools.py", line 370, in _method return self.func(*call_args, **call_keywords) File "/home/ec2-user/MYVENV/lib/python3.6/functools.py", line 370, in _method return self.func(*call_args, **call_keywords) [Previous line repeated 459 more times] File "/home/ec2-user/MYVENV/lib/python3.6/functools.py", line 368, in _method cls_or_self, *rest = args RecursionError: maximum recursion depth exceeded while calling a Python object It's not repeatable, it seems to occur late at night and the amount of traffic remains steady. I'm using python3.6. -
Django responsive web not working properly
I bought a template that I'm using to develop a responsive web with django, and when I put the browser in responsive mode, the mobile version does not work properly. I attach some pictures to illustrate it: This is my actual view And this is the template that I bought As you can see, my problem is that it looks bigger than the original template. Obviously the template I bought was 100% html, so I had to use staticfiles to make it work. This is the original header of the template: <link href="https://fonts.googleapis.com/css?family=Josefin+Sans:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Playball:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Bitter:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link href="./assets/stylesheets/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/fonts.googleapis.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/font-awesome.min.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/icon-font.min.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/social-buttons.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/cs.styles.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/font-icon.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/owl.carousel.min.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/spr.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/slideshow-fade.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/cs.animate.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/themepunch.revolution.css" rel="stylesheet" type="text/css" media="all"> <link href="./assets/stylesheets/jquery.fancybox.css" rel="stylesheet" type="text/css" media="all"> <script type="text/javascript" src="./assets/javascripts/jquery.min.js"></script> <script type="text/javascript" src="./assets/javascripts/classie.js"></script> <script type="text/javascript" src="./assets/javascripts/application-appear.js"></script> <script type="text/javascript" src="./assets/javascripts/jquery.themepunch.plugins.min.js"></script> <script type="text/javascript" src="./assets/javascripts/jquery.themepunch.revolution.min.js"></script> <script type="text/javascript" src="./assets/javascripts/cs.script.js"></script> <script type="text/javascript" src="./assets/javascripts/jquery.currencies.min.js"></script> <script type="text/javascript" src="./assets/javascripts/jquery.zoom.min.js"></script> <script type="text/javascript" src="./assets/javascripts/linkOptionSelectors.js"></script> <script type="text/javascript" src="./assets/javascripts/owl.carousel.min.js"></script> … -
Django fails when saving a serializer with foreign key references
So I had a model with one foreign key reference that was working really well for a few weeks. I ended up having to add another foreign key reference to the model and now I'm not able to save any records using a serializer. I should mention I'm using Django 2.1. Here's the model I'm using (some fields removed for simplicity): class Finding(models.Model): finding_id = models.IntegerField(null=False, blank=False, primary_key=True, db_index=True) name = models.CharField(null=True, blank=True, max_length=255) web_app = models.ForeignKey(WebApplication, on_delete=models.CASCADE) q_id = models.ForeignKey(StagingQkb, on_delete=models.CASCADE) The new FK is the q_id field. This was just a plain int before. I've actually blown away the old table and the new one is still totally empty so I know it's not a problem with the existing data (the tables with the foreign keys are still intact). When saving Findings before, I would just give the PK of the WebApplication object for 'web_app'. As far as I can tell this is still working. The 'q_id' field, when inserted the same way, complains that it needs an int/string/bytes instead of a StagingQkb object. Well, I'm not giving it a StagingQkb object so what gives! Here's the serializer: class FindingSerializer(serializers.ModelSerializer): class Meta: model = Finding fields = '__all__' … -
Why doesn't my model's "on_delete=models.CASCADE," geneate a cascading foreign key constraint?
I'm using Django, Python 3.7, and PostGres 9.5. How do I mark up my model such taht a cascading foreign key constraint gets generated? I currently have this in my models.py file ... class ArticleStat(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, ) When I run "make migrations my_project" in the management console, it produces a file that contains this ... migrations.CreateModel( name='ArticleStat', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ... ('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='my_project.Article')), ], ), However, when I run the migration (using "migrate my_project 0001"), the resulting foreign key does not contain a cascade delete constraint. This is what the description looks like in PostGres ... "my_project_articlesta_article_id_a02a5add_fk_my_project" FOREIGN KEY (article_id) REFERENCES my_project_article(id) DEFERRABLE INITIALLY DEFERRED How else can I get my models.py file to output a cascading delete foreign key constraint? -
Substituting values in a HTML table?
I am making a HTML table to display boxes (in a stockroom) that have been added, removed and changed. The headings are denoting the owner of the box, the type of change that has occurred and the new content of the box. Im using Django for my backend. Can I translate the values in the 'Type of Change' into English words rather than the symbols (~, - and +)? I am using Django simple-history to record changes to my models and it returns these symbols. I would like my table to read 'Changed', 'Removed' and 'Added' in place of '~', '-' and '+' respectfully. -
Django , open modal form with value , using javascript
I'm not really new at django and javascript , I try to open modal with value of rowid , I could pass value at last but can't open form with it here my code downbelow ; inside HTML: <thead> {% for customer in object_list %} <tr> <td>{{ customer.id }}</td> <td>{{ customer.name }}</td> <td>{{ customer.surname }}</td> <td>{{ customer.gender }}</td> <td>{{ customer.email }}</td> <td>{{ customer.phone }}</td> <td>{{ customer.bloodtype }}</td> <td><a href=# data-target="#my_modal" data-toggle="modal" class="identifyingClass" data-id="{{ customer.id }}">Open Modal</a> </td> </tr> {% endfor %} </thead> My Modal <h2>Modal</h2> <div class="modal fade" id="my_modal" tabindex="-1" role="dialog" aria-labelledby="my_modalLabel"> <div class="modal-dialog" role="dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Modal Title</h4> </div> <div class="modal-body"> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Update"> </form> <input type="hidden" name="hiddenValue" id="hiddenValue" value="{{ customer.id }} /> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">No</button> <button type="button" class="btn btn-primary">Yes</button> </div> </div> </div> Javascript <script type="text/javascript"> $(function () { $(".identifyingClass").click(function () { var my_id_value = $(this).data('id'); $(".modal-body #hiddenValue").val(my_id_value); }) }); </script> -
Setting a ManyToMany Relationship
I'm working on a Django application feature where a restaurant can add extras to his meals. So I set an extra model with two attributes (extra_n: extra name and extra_price : extra price) Then I associated this model to the meal model. models.py class Extra(models.Model): extra_n = models.CharField(max_length=200) extra_price = models.IntegerField(default=0) def __str__(self): return self.extra_n class Meal(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT) category = models.ForeignKey(MealCategory, on_delete=models.PROTECT) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='meal_images/', blank=False) price = models.IntegerField(default=0) extras = models.ManyToManyField(Extra) def __str__(self): return self.name I'm having a confusion. The goal is to create extras for each meal. Those extras are going to be associated to one meal and no other. while checking on the django admin I find that whenever I add an extra, it's associated to all meals. Can anyone please help figure out the problem ? -
Integrity Error in Django TabularInline model
im trying to add a tabularInline model to the User class so when the admin can modify a User and add an album to that User. Here are the involved models: Models.py class RegularUser(MyUser): MyUser.is_staff = False MyUser.is_superuser = False class Meta: verbose_name = 'Usuario Regular' verbose_name_plural = 'Usuarios Regulares' class AdminUser(MyUser): usuarios = models.ManyToManyField(RegularUser, help_text="Selecciona los usuarios que administra", blank=True) class Meta: verbose_name = 'Administrador' verbose_name_plural = 'Administradores' @classmethod def create(cls): adminUser = cls(is_staff=True) adminUser.save() return adminUser class Album(models.Model): id_album = models.AutoField(primary_key=True) titulo = models.CharField(max_length=40, null=False) .... usuario = models.ForeignKey(RegularUser, on_delete=models.CASCADE) created_by = models.ForeignKey(AdminUser, on_delete=models.CASCADE, related_name='Administrador', default=1) slug = models.SlugField(max_length=50, unique=True) class Meta: verbose_name_plural = "Álbumes" def __str__(self): return self.titulo def save(self, *args, **kwargs): self.slug = slugify(self.titulo) super(Album, self).save(*args, **kwargs) Admin.py @admin.register(Album) class AlbumAdmin(admin.ModelAdmin): fields = ['titulo', 'descripcion', 'thumbnail', 'evento', 'usuario', 'slug', 'created_by'] # prepopulated_fields = {'slug': ('titulo',)} readonly_fields = ['slug', 'created_by'] date_hierarchy = 'fecha_creacion' list_filter = ('fecha_creacion', 'usuario') list_display = ('Portada', 'titulo', 'usuario') inlines = [ImagenInstanceInline] def save_model(self, request, obj, form, change): obj.created_by = request.user.adminuser obj.slug = slugify(obj.titulo) super().save_model(request, obj, form, change) def get_queryset(self, request): qs = super(AlbumAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(created_by=request.user) class AlbumInstanceInline(admin.TabularInline): model = Album fields = ('thumbnail_tag', 'titulo', 'evento', 'thumbnail') readonly_fields = … -
How to make global views.py for the entire Django app
I don't know if it's right to call it a global views.py, but what I'm trying to do is to get data for my navigation bar since the navigation bar has a search field supporting auto completes. As the navigation bar shows up on any page of the website, I want to call the data for the search bar only once. Is that possible? I'm not sure because usually each Django app has its own views.py and those views.py is called as their app is called through their urs.py. -
duplicate key value violates unique constraint error when using update_or_create in django
My model: class DirectoryDoctors (models.Model): num = models.AutoField(primary_key=True) name = models.CharField(max_length=100) design_choices = ( ('IMO', 'IMO'), ('AIMO', 'AIMO'), ) designation = models.CharField( choices=design_choices, max_length=30, default='unspecified') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) email = models.CharField(max_length=50, default='', blank=True) dob = models.DateField(null=True, blank=True) specialiast_or_not_choices = ( ('Yes', 'Yes'), ('No', 'No'), ('Unspecified', 'Unspecified') ) specialiast = models.CharField( choices=specialiast_or_not_choices, max_length=30, default='Unspecified') specialty_choices = ( ('Internal Medicine', 'Internal Medicine'), ('General Surgery', 'General Surgery'), ('Not Applicable', 'Not Applicable') ) specialty = models.CharField( choices=specialty_choices, max_length=30, default='Unspecified') institution = models.ForeignKey(DirectoryHospital, on_delete=models.DO_NOTHING) bloodgroup_choices = (('apos', 'A+'), ('-', '-') ) bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=15, default='-', blank=True) spousename = models.CharField(max_length=100, blank=True) children = models.CharField(max_length=200, blank=True) present_address = models.CharField(max_length=200, blank=True) permanent_address = models.CharField(max_length=200, blank=True) class Meta: unique_together = ["name", "mobile", "email"] def __str__(self): st = f"{self.name}, {self.designation}, {self.institution}" return st And code while updating data: dirhosp = DirectoryHospital.objects.get(name = disp, insttype = hospordisp, district = district) try: dirdoc = DirectoryDoctors.objects.update_or_create(name = name, designation = desig, mobile = mob, alternate = alt, email = emailadd, dob = dob, specialiast = specialist_not, specialty = specialty, institution = dirhosp, bloodgroup = blgp, spousename = spouse, children = children, present_address = address_pres, permanent_address = address_perm) print(f"Saved name = {name}, designation = {desig}, mobile = … -
Django extend User Profile
Django 2.1 Python 3.6 Im trying to extend the Django User model and Display this in the Admin overview, but its not working with my workaround. #modely.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_confirmed = models.BooleanField(default=False) #some additional fields here #admin.py class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'E-mail settings' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('email', 'custom_group', 'is_active', 'is_staff', 'is_superuser'#, 'is_confirmed ' ) def custom_group(self, obj): return ','.join([g.name for g in obj.groups.all()]) if obj.groups.count() else '' now I try to display the field from profiles, is_confirmed in the user overview page in the admin as well. But this doesn't work for me. How do I get the field in there? example picture -
Django make field optional that gets check by integrity
i want to make a field at my sign-up page optional so that the content of that field only gets checked if the user has provided these information, if not, simply skip the check for the data integrity: pubpgp = PGPKey.from_blob(request.POST['pubpgp'].rstrip("\r\n"))[0] of the field pub pgp. But i don't know how to accomplishes this, any help is welcome. def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): pubpgp = PGPKey.from_blob(request.POST['pubpgp'].rstrip("\r\n"))[0] if pubpgp.key_algorithm == PubKeyAlgorithm.RSAEncryptOrSign: form.save() messages.add_message(request, messages.INFO, "Thanks for you Registration, you are now able to login.") return redirect(reverse('login')) else: messages.add_message(request, messages.INFO, "Only RSA based PGP keys are allowed.") else: return render(request, 'signup.html', {'form': form}) else: form = RegistrationForm() args = {'form': form} return render(request, 'signup.html', args) thanks in advance -
Django group by yield wrong result after filtering by annotated field
So, I mainly want to group by my result by a certain field which I know I can do like ModelName.objects.values('somefield').annotate(freq=Count('somefield')) But before that, I want to filter based on one annotated field, but this yields the wrong result, I tried, # Works fine filtered_queryset = ModelName.objects.annotate(c=Count('related_field')).filter(c__gt=0) # Yields wrong result. filtered_queryset.values('somefield').annotate(freq=Count('somefield')) I tried passing distinct=True but this didn't solve my problem. Why am I missing here? -
In a table, ordering by data thats not in a column?
Im using the Jquery 'Datatables' plug-in to create a table and Django for the backend. I would like to order my table by 'Date' but would not like to include the 'Date" field as a column. Is this possible? I have tried .order_by('-date_purchased') in my views but it is still not translating into my table. A simplified version of my code is below: Model: class Shopping(models.Model): fruit = models.CharField() colour = models.CharField() date_purchased = models.DateTimeField() View: def dashboard(request): fridge = Shopping.all().order_by('-date_purchased') HTML/ JQuery: <script> $(document).ready( function () { $('#Fruit').DataTable({ * some scripting is here * }); }); </script> <table id="Fruit"> <thead> <tr> <th>Fruit</th> <th>Colour</th> </tr> </thead> <tbody> {% for item in fridge %} <tr> <td>{{ item.fruit_name }}</td> <td>{{ item.fruit_colour }}</td> </tr> {% endfor %} </tbody> </table> -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ajax request
I have an ajax request, and in django view, i have following prints and outputs. I have the error in this line and i cant figured it out why. parsed_json = json.loads(request.body) AJAX CALL: $("#add_user_button").click(function (event) { event.preventDefault(); $.ajax({ type: "POST", url: '/user/', data: { 'action': "addUser", 'username': $('#id_username').val(), 'password': $('#id_password').val(), 'groups': $('#id_groups').val() } , contentType: 'application/json; charset=utf-8', processData: false, }); } DJANGO VIEW PRINTS: print(request.POST.get("username")) #print(request.encoding) #returns none print("Request body is :") print(request.body) print(type(request.body)) OUTPUTS: hello Request body is : b'username=hello&password=world&csrfmiddlewaretoken=&addUser=Add+User' <class 'bytes'> -
Reverse URL - keyword arguments '{'pk': ''}' not found
I am trying to get the reverse URL working so that the primary key of the initial page the user selects passes through to the url for the sub pages. I am getting the following error: Reverse for 'player_register' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account/club_home/(?P\d+)/player_registration/$'] Any other snippets of code needed let me know. Currently when the user selects a club from the index page, it brings them to the club home page this all works fine I am just trying to figure out when the user select the club that all those sub-pages clicked on after should relate to that club. urls.py url(r'^club_home/(?P<pk>\d+)/$', views.club_home, name='club_home_with_pk'), url(r'^club_home/(?P<pk>\d+)/player_registration/$', views.RegisterPlayer.as_view(), name='player_register'), views.py class RegisterPlayer(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'player_registration.html' def get(self, request, pk): serializer = PlayerRegistrationSerializer() club_pk = reverse('club_home_with_pk', kwargs={'pk': pk}) return Response({'serializer': serializer, 'club_pk': club_pk }) def post(self, request): serializer = PlayerRegistrationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(template_name='player_registration_complete.html') club_main_page.html <li><a class="navbar-link" href="{% url 'api:player_register' pk=club_pk.pk %}">Player Register</a></li>