Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error missing positional argument (request)
I am trying to build a webapp with Django and using Djano class based views to call other functions within views.py. I'm fairly new to programming and think I'm confusing myself here. I'm getting following error: make_connection_to_user() missing 1 required positional argument: 'request' Views.py: from .models import UserInfo def make_connection_to_user(request): current_user = UserInfo.objects.get(user_id=request.user.id) user_token = current_user.access_token connection = MyApp(user_token) return connection def get_user_info(): used = make_connection_to_user().users_get_space_usage().used allocated_space = make_connection_to_user().users_get_space_usage().allocation.get_individual().allocated return used, allocated class DashboardMainPage(View): def get(self, request): used_space = get_user_space_info()[0] allocated_space = get_user_space_info()[1] return render(request, 'analyzer/dashboard.html', {'used_space': used_space, 'allocated_space': allocated_space}) Urls.py: urlpatterns = [ path('dashboard/', views.DashboardMainPage.as_view(), name='dashoard'), ] -
Django Correct Usage of Models.Cascade (on_delete)
I am trying to work what is the correct usage of the models.cascade statement. I have two models Cart and Entry. If I delete an Entry the deletion is not updated on the Cart Entry. I have checked this via the admin interface. My models.py is as below: class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0) -
how to properly override serializer save on a POST request in DRF?
I have a model that has a DateTime field and a serializer for that model. I have an API endpoint that is POST only to create the model object, but the problem is the service that will be POSTing to this endpoint will send a completely different date/time value, and so this will need to be correct on Django's end before creating the object. Normally (without DRF), I would just override the models save method, but now with the introduction of DRF, I'm confused if I should be override the save method for the model or the serializer? I'm thinking if I override the save method for the model so that it reformats the date/time value before saving. Then the serializer.is_valid() itself will throw an error when receiving the wrong date time format since the serializer maps directly to the model fields and has no knowledge of the models save method? What is the best way to go about doing this? models.py class Job(models.Model): name = models.CharField(max_length=150) age = models.CharField(max_length=200) start_time = models.DateTimeField() class Meta: unique_together = ('name', 'age', 'start_time') serializers.py class JobSerializer(serializers.ModelSerializer): name = serializers.CharField() age = serializers.CharField(required=False) start_time = serializers.CharField(required=False) class Meta: model = Job fields = ('name', … -
Conflict of app name in Django with old app name
I am sort of new to Django so I'm using the tutorial on the offical website here So I created an environment, installed django 2.0.2 and any other packages I needed. Then I opened a terminal and created my polls app with python manage.py startapp polls. As I progressed, I decided I wanted to do some things differently and as I'd not really progressed very far, I just deleted my project files and started fresh. However, on the second pass through when I tried creating my polls app, I get an error that "'polls' conflicts with the name of an existing Python module and cannot be used as an app name." I have tried deleting the environment and creating a new one but that doesn't work. I tried starting a brand new project, that doesn't work either. There was no problem creating the app the first time so I'm guessing that it is still located somewhere. Is there a method for completely removing apps in django 2.0.2? All the resources I've seen are for earlier versions. -
Customize raw_id field query on an inline form
How do I customize the spyglass query in an inline form for a raw_id foreignkey? I tried overriding formfield_for_foreignkey but that did nothing and I think it's because it's for dropdown foreignkeys rather than raw_id. I also tried a custom widget but that doesn't seem to work on inline. -
IntegrityError: NOT NULL constraint when trying to save a model instance
I know this has been asked a lot but none of the answers were able to help me I have two models: one that stores messages and one that stores sender info: class SenderInfo(models.Model): #to create unique id numbers sender = models.CharField(max_length=15) id_number = models.IntegerField(blank=True, null=True, default=None) class Messages(models.Model): message = models.ForeignKey(SenderInfo, related_name='messages') message_body = models.TextField() And when I try to make an instance and save() it I keep getting IntegrityError: NOT NULL constraint failed: appconvo_messages.message_id -
How to insert dynamic data from HTML file to DynamoDB through Django?
I am trying to insert dynamic data from HTML form to DynamoDB table via Django. I am using put-item to insert a single item, but I can't figure out how to access the field using ID (If that is possible) and insert data IN DynamoDB using that ID? Please help ! I am posting the code below. views.py def Contact(request): if request.POST: name = request.GET.get('name') email = request.GET.get('email') subject = request.GET.get('subject') message = request.GET.get('message') Contact.object.create(name, email, subject, message) models.py import boto3 # Get the service resource. from django.db import models dynamodb = boto3.resource('dynamodb', region_name="us-west-2", endpoint_url="http://localhost:8080") class Contact(models.Model): name = models.CharField(max_length=32, unique=True) email = models.CharField(max_length=32, unique=True) subject = models.CharField(max_length=32, unique=True) message = models.CharField(max_length=32, unique=True) Contact.object.create(name, email, subject, message) table = dynamodb.Table('ContactForm') table.put_item( Item={ 'name': models.Contact.name, 'email': models.Contact.email, 'subject': models.Contact.subject, 'message': models.Contact.message, } ) print("Put Item Success") -
Stripe does not accept my token
I am trying to create a django shopping site. But I can't get stripe to work. I don't belive it is anything workng in my code. It works fine withe the "tok_visa" sendt with javascript. But it does not accept my token. I have even tried manuelly writing it in. views.py if form.is_valid(): token = form.cleaned_data['token'] try: stripe.Charge.create( amount = 20000, currency = "nok", description = ""+form.cleaned_data['etternavn']+", "+form.cleaned_data['fornavn'], source = token, ) form.save() return HttpResponse("<p>"+form.cleaned_data['fornavn']+"</p>") except stripe.CardError as e: form.add_error("Kortet ble ikke akseptert "+token) Jquery Stripe.setPublishableKey('pk_test_H1PZQA7ypCa8UIlEy6S9ovhE'); $( '#payment-form' ).submit(function(e){ $form = $(this); $form.find('button').prop('disabled', true); Stripe.card.createToken($form, function(status, response){ if(response.error){ $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); } else{ var token = response.id; $form.find('input[id="id_token"]').val(token); $('#id_token').val(token); $form.get(0).submit(); } }); return false; }); Thank you for the help -
How to do a Customer Logger for Django to Capture Response and Request
I'm looking into differen't ways to capture the response object, request object, and performance in Django to create a custom json elk logger that will build audit logs. I'm not sure what approach is best to take here. I was looking at custom middleware but I've never done that. I tried to look up if it was possible to use a decorator to do this but doesn't seem like it. Also, I use the django rest framework so I also have to figure out how to integrate the middleware if thats the route or whatever solution to DRF as well. Looking for suggestions. -
Why do I not get any content with python requests get, but still a 200 response?
I'm doing a requests.get(url='url', verify=False), from my django application hosted on an Ubuntu server from AWS, to a url that has a Django Rest Framework. There are no permissions or authentication on the DRF, because I'm the one that made it. I've added headers such as headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}, but wasn't able to get any content. BUT when I do run ./manage.py shell and run the exact same command, I get the output that I need! -
AttributeError when creating a new user
I am getting this error: Internal Server Error: /signup/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\utils\deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "C:\python\lib\site-packages\django\middleware\clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' When trying to render this view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) subject = "Activate your DC-Elects account" message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.id)), 'token': account_activation_token.make_token(new_user), }) new_user.email_user(subject, message) return reverse('elections:account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html',{ 'form': form, }) The error message is not very descriptive, but the email is sending with the link correctly, so I'm very confused as to why there is an error. How do I prevent this error and render the next view correctly? -
how to run our function in Django restframwork
I want to run my function to do something in a request to url of serializer my serializer : class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my view for serializer: class usersCreate(generics.CreateAPIView): queryset=users.objects.all() serializer_class=usersSerializer my function: def f(): now=datetime.now() now10=now + timedelta(minutes = 10) quer=users.objects.last() rcode=randint(1000,9999) a=SMS(users_id=quer,code=rcode,expireTime=now10) a.save() SMS is another table users_id ====> foreigne key to id in users table I want to when I send request to user create url changed two table : users SMS models: class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.DateTimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") expireTime=models.DateTimeField() status=models.BooleanField(default=False) -
Django won't serve on Apache/Fedora 23 VM since i changed PCs
I recently got a new PC and put my Fedora 23/Apache VM on it. I had Django site serving successfully previously through this VM before switching PCs. Now when i run: systemctl start httpd.service i don't appear to get errors, but when i put the ip address (inet, non-loopback) in my web browser, nothing happens, no data is sent. my etc/hosts file: 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 my httpd.conf file: ServerName localhost when i run 'hostname -f', i get "localhost". is there another IP address i need to add to any of the above files in order to get this working? i looked at other posts related to this, but couldn't figure out which IP address, if any, to add. help? -
Overwrited delete method doesn't work when cascading delete
I have an application which simulates the comportment and arborescence of xml balises. My first model, IdBalise, is used to link parents with children. It is linked with diferent balise models with a GenericForeignKey : class IdBalise(models.Model): idBalise=models.AutoField(primary_key=True) parent = models.ForeignKey('IdBalise', on_delete=models.CASCADE, related_name="parentbal", null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I use then many balise models like the one below : class BiblBalise(Balise): idbal = GenericRelation(IdBalise, content_type_field="content_type", object_id_field="object_id", on_delete=models.CASCADE) baliseName='bibl' In order to delete the balise content when I delete an IdBalise, I overwrited the delete method of IdBalise : def delete(self): self.content_object.delete() super(IdBalise, self).delete() It works perfectly. When I delete an IdBalise, its related content (for instance, the entry in BiblBalise) is deleted. My problem is, when I delete a parent, the children's content doesn't delete. The children IdBalise are deleted, because of the on_delete=models.CASCADE on the "parent" field. But their content (for instance, the entry in BiblBalise) isn't deleted. Why my overwrited delete method doesn't work when the children IdBalise is deleted ? Any ideas ? Thanks -
Is having the SECRET KEY in an environment variable better than having it in an untracked settings file?
In a scenario where the project's settings.py file is split into base, development, and production, and only the base file is tracked in VCS. Is it a problem if the SECRET_KEY is hard-coded in the production settings file. Or will having it in an environment variable a better choice? If so, why? Is having it pulled from the system somehow more secure than written in plain text inside the file? -
How do I create an instance of a model in views.py?
I'm sorry if this is a stupid question, but I'm having trouble finding out how to create a new instance of a model inside the views. Referencing this question, I tried doing foo = FooModel() save() but I got a NameError: name 'save' is not defined. I then tried bar = BarModel.objects.create() but got AttributeError: 'Manager' object has no attribute 'Create'. Am I not understanding something very trivial? Maybe those commands are just for the command line? In that case, how do I create new objects, or filter them, etc... from code? -
Django: Queryset not saving changes to value?
Here, result is a Queryset. I am going through it and updating the value for it's price attribute to match what I get from the price_map.price value in my second query to Product.objects. This works and updates the prices accordingly. Until it goes into the .order_by method. Then, all of the values of price return to what they originally were. if sort_by in valid_sorts: for item in result: retrieved_item = Product.objects.get(name=item.name).get_pricing_info(self.request.session.get('visitors_country')) if retrieved_item['price_map'] is None: print 'we got a none here! ', item.name else: item.price = retrieved_item['price_map'].price if sort_by == 'highlow': result = result.order_by('-price') elif sort_by == 'lowhigh': result = result.order_by('price') elif sort_by == 'newest': result = result.order_by('-date','-price') elif sort_by == 'relevancy': pass If I add in some print statements for just before and just after the .order_by call, here is the output I get: Just before the order! 79.99 119.99 99.99 69.99 119.99 89.99 69.99 69.99 99.99 44.99 599.99 599.99 69.99 69.99 69.99 69.99 249.99 799.99 119.99 139.99 199.99 249.99 139.99 149.99 139.99 69.99 139.99 199.99 69.99 29.99 0.0 139.99 34.99 54.99 119.99 149.99 69.99 69.99 89.99 119.99 119.99 149.99 149.99 1699.99 69.99 249.99 39.99 39.99 39.99 599.99 999.99 199.99 49.99 119.99 119.99 249.99 99.99 99.99 199.99 69.99 99.99 … -
How to make a subcategory belong to a specific category in Django
I have a little problem with display subcategories belongs only in specific categories. For example: I have a categories: Business, Factory, Health ... and after I can add subcategories for example Own Company in category Business. In this case if I choose category Business I need to have only visible subcategories belongs to this category. How to make it? This is my code. models.py from django.db import models from slugify import slugify class Kategoria(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Nazwa kategorii') slug = models.SlugField(verbose_name='Adres SEO') class Meta: verbose_name_plural = 'Kategorie' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Kategoria, self).save(*args, **kwargs) def __str__(self): return self.name class Subkategoria(models.Model): category = models.ForeignKey('Kategoria', related_name='subkategoria', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Kategoria główna') name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Subkategorie' def __str__(self): return self.name class Strona(models.Model): name = models.CharField(max_length=250, verbose_name='Nazwa strony') slug = models.SlugField(verbose_name='Adres SEO') www = models.CharField(max_length=200, verbose_name='Adres strony', unique=True) content = models.TextField(verbose_name='Opis') category = models.ForeignKey('Kategoria', verbose_name='Kategoria', on_delete=models.CASCADE) subcategory = models.ForeignKey('Subkategoria', verbose_name='Subkategoria', on_delete=models.CASCADE) publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name_plural = 'Strony' def __str__(self): return self.name -
Am I able to create a form that is able to add a new django.contrib.auth User without logging in to the admin panel?
Have created a form but unsure if is right and also unable to add a user, it will show TypeError/ This is how the form I want it to look like The following is my coding: class Form_Add_User(forms.Form): name=forms.CharField(label="Name", max_length=50) dateofbirth=forms.DateField(label="Date of Birth", widget=forms.widgets.DateInput(format="%m/%d/%Y")) contactnum=forms.CharField(label="Contact Number", max_length=9) def adduser(request): if len(request.POST)>0: form=Form_Add_User(request.POST) if(form.is_valid()): name=form.cleaned_data['name'] dateofbirth=form.cleaned_data['dateofbirth'] contactnum=form.cleaned_data['contactnum'] new_user=User(name=name,dateofbirth=dateofbirth,contactnum=contactnum) new_user.save() return redirect('/adduser') else: return render(request,'adduser.html',{'form':form}) else: form=Form_Add_User return render(request,'adduser.html',{'form':form}) -
TypeError when creating a new user
After following this tutorial to create a signup view, I have encountered an error. Here is the view: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): new_user = form.save(commit=False) new_user.is_active = False new_user.save() current_site = get_current_site(request) subject = "Activate your DC-Elects account" message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(used.id)), 'token': account_activation_token.make_token(user), }) new_user.email_user(subject, message) return reverse('elections:account_activation_sent') else: form = SignUpForm() return render(request, 'registration/signup.html',{ 'form': form, }) Here is the extended user model: class Profile(models.Model): UserID = models.OneToOneField(User, on_delete=models.CASCADE) GENDERS = (("M","Male"), ("F","Female")) Gender = models.CharField(max_length=1, choices=GENDERS) UserTypeID = models.ForeignKey(UserType, on_delete=models.PROTECT, blank=True, null=True) ProfilePicture = models.ImageField(default='default_profile.png', upload_to="imageposts/") EmailConfirmed = models.BooleanField(default=False) # For student number, can you have choices - Teacher or input()? @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Everything goes fine when filling out the form as the user, but when I submit the form, I get this error: Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\cbuch1800\Coursework\mysite\elections\views.py", line 325, in signup new_user.save() File "C:\python\lib\site-packages\django\contrib\auth\base_user.py", line … -
Javascipt error Uncaught SyntaxError: Unexpected identifier
I am making a website using HTML5 Javascript and Django 1.8 , Python 3.5 and I am getting the following error Uncaught SyntaxError: Unexpected identifier class User { constructor(nothing) { //doNothing } function myFunction(p1, p2) { return p1 * p2; // The function returns the product of p1 and p2 } function afunc() { var mydata = "kk"; return (mydata); } } var abc = new User(); var kk = abc.myFunction(1, 2); console.log(kk); -
Django: how to fully decouple apps when it seems they are coupled?
Note: I am not a proper python programmer... but I use python extensively. I do things like write classes with inheritance, use iterators and comprehension, etc. My point is that I do not have a full grasp of the language, e.g. what exactly constitutes an python object, why __init__.py is needed other than to specify a module, etc. In relation to Django, I have written multi-app sites (with the help of S.O.) and have really enjoyed Django's templating system, blocks, and how they can be nested. Now are my apps fully decoupled and reusable? That this is subject of this post. I state this disclaimer because a lot of the Django resources seem to assume that one knows these things. This makes understanding some of the documentation and S.O. questions difficult for a person who is just an (subpower)-user. So please answer this question with that in mind. Question These questions are inspired by both the question When to create a new app with startapp in django? by @håkan and the answer given by @antti rasinen which links to James Bennett's 2008 PyCon presentation A few key points from Bennett's presentation are: sites are a collection of apps an app … -
Django app : unit tests because of django.db.utils.IntegrityError
On a Django 2.0 project, i have the following issue on my unit tests and I can't find the cause. I am implementing a model which tracks any change on another model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Investment(models.Model): """the main model""" status = models.IntegerField() class InvestmentStatusTrack(models.Model): """track every change of status on an investment""" investment = models.ForeignKey(Investment, on_delete=models.CASCADE) status = models.IntegerField() modified_on = models.DateTimeField( blank=True, null=True, default=None, verbose_name=_('modified on'), db_index=True ) modified_by = models.ForeignKey( User, blank=True, null=True, default=None, verbose_name=_('modified by'), on_delete=models.CASCADE ) class Meta: ordering = ('-modified_on', ) def __str__(self): return '{0} - {1}'.format(self.investment, self.status) @receiver(post_save, sender=Investment) def handle_status_track(sender, instance, created, **kwargs): """add a new track every time the investment status change""" request = get_request() # a way to get the current request modified_by = None if request and request.user and request.user.is_authenticated: modified_by = request.user InvestmentStatusTrack.objects.create( investment=instance, status=instance.status, modified_on=datetime.now(), modified_by=modified_by ) Most of my unit test fails with the following traceback Traceback (most recent call last): File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 209, in __call__ self._post_teardown() File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 893, in _post_teardown self._fixture_teardown() File "/env/lib/python3.6/site-packages/django/test/testcases.py", line 1041, in _fixture_teardown connections[db_name].check_constraints() File "/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 235, in check_constraints self.cursor().execute('SET CONSTRAINTS ALL IMMEDIATE') File … -
Hide a field in a Django admin inline editor
How do you include a hidden field in an inline editor? This question suggests using form.fields['field_name'].widget = forms.HiddenInput() for an admin form, but what do I do for an inline? -
create a input box on a app using django
I am tasked with a project of creating an app with python. We have decided to use django for this purpose. Basically, I need to create an app where users can go on to a website, type their names, addresses and get the required information about their historical product purchase. Now, I am using mariadb in python to query the names. The function I created successfully gets the users name using some name matching algorithm and gets their required information. If the user misspells his/her name, the program also outputs suggested names that match what the user implied. Hence, if the user clicks on his/her name, he will get all historical purchase history for that user. I managed to use django to create a basic website. But, I want to create input boxes where users can put in their info. Do I actually go to models.py in django and create a names model? Also, is an administrative site required for this purpose? Thanks