Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing problems redirecting user using django post_save signal
When ever a user creates a new chat thread, i want to automatically redirect them to the thread. But facing problems example my models class Thread(models.Model): name=models.CharField() creator=models.ForeignKey(User) class Chat(models.Model): thread=models.ForeignKey(Thread) message=models.TextField() User creates a thread , and has to be redirected to the created thread('app:chat',pk) displaying the Chatform and thread name. I tried using django post_save signal to redirect the user after creating a thread def redirect_user(sender,instance,**kwargs) pk=instance.id url=('app:chat',pk) post_save.connect(redirect_user,sender=Thread) Well this is not working. Please help with a good approach to solve this problem. -
What is the default hashing algorithm used by Django cache
I am using caching in Django. My cache is a django-redis cache: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } I am using view based cache: @cache_page(timeout=60 * 10) def my_view(request: Request): # my view stuff What I would like to know is what is the algorithm used by Django to create the key? The docs just say that it's made from the URL and headers. But I would like to know the specifics or better yet the code that generates it. But the docs lack this information. So, how does Django derive keys for view based caches? -
How to check if data already exists in the table using django
I am new with django framework struggling to compare value from the database. this are my tables in models.py : class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) title = models.CharField(max_length=200) content = models.TextField() creationDate = models.DateTimeField(auto_now_add=True) lastEditDate = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Votes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) post_id = models.ForeignKey(Post, on_delete=models.CASCADE,) up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) class Meta: unique_together = (("user","post_id"),) I have data in the vote tabe like this: Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know. something which i tried was this code: def chk_table(): user_id = request.user post_id = id votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists() return votes_table but this function is checking in hole table not just in just in one row... -
Django and mongodb
Any good tutorial for python django mongodb? I have python 3.7.3 installed. I grabbed django 1.6 from https://github.com/django-nonrel/django (that's really old). Followed the instruction of https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html The "python manager.py runserver" show some htmlparser errors. File "D:\apps\Python37\lib\site-packages\django\utils\html.py", line 14, in from .html_parser import HTMLParser, HTMLParseError File "D:\apps\Python37\lib\site-packages\django\utils\html_parser.py", line 12, in HTMLParseError = _html_parser.HTMLParseError AttributeError: module 'html.parser' has no attribute 'HTMLParseError' Any recommendations to have them work together? -
Data migration causes error AttributeError: type object 'User' has no attribute 'normalize_username'?
I'm trying to create a data migration to add a user to the database. However, I get an attribute error when I try to do so. I've ran ipdb to troubleshoot the problem, I've tried commenting out fields of the user object to see if one of those was causing the error, and I've tried adding "user.save()" # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-02-08 21:23 from __future__ import unicode_literals from django.db import migrations from django.conf import settings def create_urechr_user(apps, schema_editor): staffPosition = apps.get_model("hr", "staffPosition") User = apps.get_model(settings.AUTH_USER_MODEL) user = User.objects.create_user( username = "myName", password = "test", is_active = True, email = "", ) staff = staffPosition.objects.get(pk = 95) user.save() urec_staff = staffPosition.objects.create( parent_staff_position = staff, user_id = user, title = "URec Human Resources", ) urec_staff.save() class Migration(migrations.Migration): dependencies = [ ('hr', '0003_add_verbose_name_20190213_1519'), ] operations = [ migrations.RunPython(create_urechr_user), ] AttributeError: type object 'User' has no attribute 'normalize_username' -
Assign a widget to ModelForm field after initialization
I have a ModelForm which looks more or less like this one: class SomeModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SomeModelForm, self).__init__(*args, **kwargs) <some fields/code> # the problematic line below self.fields['date'].widget = forms.DateInput(attrs={ 'type': 'date', 'class': 'form-control input-lg', }), class Meta: model = models.SomeModel fields = [<some fields>, 'date',] And the problem is I'm getting an error: Exception Type: AttributeError Exception Value: 'tuple' object has no attribute 'is_hidden' It looks that I cannot assign forms.DateInput() widget to already existing field (as you can see I have to execute super().__init__() because of popping a field from **kwargs). Is there any solution to do this without exceptions? -
How do I make sure entered integer is greater than current value before updating model field?
I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation. I have tried an if statement in the form_valid() of the CreateView and a save() method in the model. class Vehicle(models.Model): name = models.CharField(blank=True, max_length=100) make = models.CharField(blank=True, max_length=100) model = models.CharField(blank=True, max_length=100) year = models.IntegerField(blank=True, null=True) vin = models.CharField(blank=True, max_length=17) gvw = models.IntegerField(blank=True, null=True) license_plate = models.CharField(blank=True, max_length=100) purchase_date = models.DateField() current_mileage = models.IntegerField(blank=True, null=True) class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk}) @property def get_current_mileage(self): return self.current_mileage class FuelEntry(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) fuel_choices = ( ('EMPTY', 'Empty'), ('1/8', '1/8'), ('1/4', '1/4'), ('1/2', '1/2'), ('3/4', '3/4'), ('FULL', 'Full'), ) current = models.CharField(max_length=5, choices=fuel_choices) after = models.CharField(max_length=5, choices=fuel_choices, blank=True) gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0') cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0') mileage = models.IntegerField(blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['-date', 'vehicle'] def __str__(self): return self.vehicle.name def get_absolute_url(self): return reverse('fuellog:entry_detail', kwargs={'pk':self.pk}) class CreateEntry(CreateView): model = … -
Continuously check if file exists with AJAX in Django
I've developed an application in Django where a user goes to a form on a site and enters in an Elasticsearch query, then generating a report for the user to download. It all works fine and dandy, but lately in testing some more queries we've noticed that some return a lot of results which leads to a timeout request. What we've figured out that we'd like to do is have Django continuously check if a file exists (because it won't be written to the local system until it's completed) to prevent that timeout issue. Additionally, once the file is done being created we want to add a download button so that the user knows it is done. Following this tutorial, I added a function to my views.py and associated it with a url which is then called by a javascript code block in my html form. Because I am brand new to using AJAX, JQuery, Javascript, and Django I'm not quite sure how to get it to work. Mainly, I'm trying to figure out how to get it to keep checking if the file is done being created yet. If this were just using basic Python I would do a … -
Django, on registering a user: AttributeError: 'AnonymousUser' object has no attribute '_meta'
I added the field 'description' (as a test) to the registration form, and am also attempting to create two different profiles for two different users (WPs and Ws). I have created, as you will see below, a seperate registration page for wps (user type2), referenced by profile_wp, register_WP etc, and on trying to register a user using this form, I receive the following error: AttributeError: 'AnonymousUser' object has no attribute '_meta' There are various answers on this, but none solved my problem. The various relevant bits of my code are below forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform email = forms.EmailField() class Meta: model = User class Register_WP_Form(UserCreationForm): #form that inherits from the usercreationform email = forms.EmailField() description=forms.EmailField() #choice = forms.ChoiceField(required=True, widget=forms.RadioSelect( #attrs={'class': 'Radio'}), choices=(('option1','I am a W'),('option2','I am a WP'),)) class Meta: model = User #when this form validates it creates a new user #type the fields to be shown on your form, in that order. fields = ['username','email','password1','password2','description'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username','email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model= Profile fields=['image'] views.py #USERS … -
After connecting to remote database, migrating gives error: Errno61, Connection Refused
I recently started using sql and connected to an remote sql server. I can run queries on it in python shell and get correct results. However, when I manage.py runserver It tells me that there I need to migrate, however when I migrate I get an error saying: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '*host*' ([Errno 61] Connection refused)") What should I do to fix this error. setting.py database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*name*', 'USER': '*user*', 'PASSWORD': '********', 'HOST': '*host*', 'PORT': '****', 'OPTIONS': { 'sql_mode': 'traditional', } } } full error list here: File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 727, in create_connection raise err File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/Users/lwyss/PycharmProjects/NewWebsite/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'masspike.ctqk1lhawxna.us-west-2.rds.amazonaws.com' ([Errno 61] Connection … -
Django queryset to a string
I have a queryset by doing: chart_data = DetailChange.objects.extra(select={'day': 'date(captured_date)'})\ .values('item_id__store_id__store_name', 'day')\ .annotate(total_sale=Sum('amount_sold')) then I have a queryset like this: {'day': datetime.date(2019, 6, 24), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 706.0} {'day': datetime.date(2019, 6, 25), 'item_id__store_id__store_name': 'Keyboard Pro', 'total_sale': 18.0} ... now what I want to do is get one single string that combines all the days in it, separated by ",". Like: "2019-6-24, 2019-6-25, 2019-6-26, ..." Is there an easy way to get it done? -
Why won't import models work in a utility file in the same directory?
From views.py I'm calling a function that's in another file in the same directory (utils.py). utils.py errors because it can't import models from models.py which is in the same directory. I get the following error: File "/home/myuser/site/core/utils.py", line 1, in 2019-06-26 15:22:46,645: from .models import( 2019-06-26 15:22:46,645: *************************************************** 2019-06-26 15:22:46,646: If you're seeing an import error and don't know why, 2019-06-26 15:22:46,646: we have a dedicated help page to help you debug: 2019-06-26 15:22:46,646: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2019-06-26 15:22:46,646: *************************************************** 2019-06-26 15:22:51,962: Error running WSGI application 2019-06-26 15:22:51,963: ImportError: cannot import name 'Movie' utils.py from .models import( Movie, Album, Book) def get_weekly_tops(): start_date, end_date = getThisWeekStartEnd() book = Book.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).order_by('-amazon_rating')[:1] theater = Movie.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).filter(bluray_date__isnull=True).order_by('-imdb_rating')[:1] bluray = Movie.objects.filter(bluray_date__range=[start_date, end_date]).filter(active=True).filter(bluray_date__isnull=False).order_by('-imdb_rating')[:1] album = Album.objects.filter(release_date__range=[start_date, end_date]).filter(active=True).order_by('-base_rating')[:1] if len(book) == 0: book = Book.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).order_by('-amazon_rating')[:1] if len(theater) == 0: theater = Movie.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).filter(bluray_date__isnull=True).order_by('-imdb_rating')[:1] if len(bluray) == 0: bluray = Movie.objects.filter(bluray_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).filter(bluray_date__isnull=False).order_by('-imdb_rating')[:1] if len(album) == 0: album = Album.objects.filter(release_date__range=[start_date + timedelta(days=-6), end_date + timedelta(days=-6)]).filter(active=True).order_by('-base_rating')[:1] return {'book':book, 'theater':theater, 'bluray':bluray, 'album':album} views.py from .utils import( get_weekly_tops) def index(request): weekly_tops = get_weekly_tops() return render( request, 'index.html', context={ 'weekly_tops':weekly_tops }, ) -
django-imagekit generates thumbnail images when getting a request to access a page and it makes the page load really slow
I'm using django-imagekit to thumbnail images, I use image_thumbnail field to access thumbnails, but the problem is that ImageSpecField makes my website to work really slowly as it creates thumbnails when the page is requested. I thought it would be much faster if I make thumbnails when initially uploading original images in Django admin. Is it possible to keep images with various sizes when uploading an original image in Django admin? models.py class Image(TimeStampedModel): image = ProcessedImageField(upload_to=image_path, format='JPEG', processors=[Thumbnail(1500)]) image_thumbnail = ImageSpecField(source='image', processors=[Thumbnail(280)], format='JPEG', options={'quality': 60}) -
How to Select specific Row from the Tabel Using Django Query
I am new with django framework i have no idea about how query works in django, this are my tables in models.py : class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) title = models.CharField(max_length=200) content = models.TextField() creationDate = models.DateTimeField(auto_now_add=True) lastEditDate = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Votes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) post_id = models.ForeignKey(Post, on_delete=models.CASCADE,) up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)]) class Meta: unique_together = (("user","post_id"),) I have data in the vote tabe like this: Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know. something which i tried was this code: def chk_table(): user_id = request.user post_id = id votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists() return votes_table but this function is checking in hole table not just in just in one row... -
Django inline formset want to auto-save user and datetime
I am having 2 models: Study Request Concept and Comments. Study request Concept can have multiple comments. *models.py: class StudyRequestConcept(models.Model): CHOICES = ( ('Yes', 'Yes'), ('No', 'No'), ) REQUEST_STATUS = ( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Denied', 'Denied'), ) APPROVER_CHOICES = ( ('Amey Kelekar', 'Amey Kelekar'), ) requestor_name = models.CharField(max_length=240, blank=False, null=False) project = models.CharField(max_length=240, blank=False, null=False) date_of_request = models.DateField(blank=False, null=False) brief_summary = models.CharField(max_length=4000, blank=False, null=False) scientific_question = models.CharField(max_length=2000, blank=False, null=False) strategic_fit = models.CharField(max_length=2000, blank=False, null=False) collaborators = models.CharField(max_length=1000, blank=False, null=False) risk_assessment = models.CharField(max_length=2000, blank=False, null=False) devices = models.CharField(max_length=1000, blank=False, null=False) statistics = models.CharField(max_length=2000, blank=False, null=False) personnel = models.CharField(max_length=1000, blank=False, null=False) sample_size = models.PositiveIntegerField(blank=False, null=False, default=0) population = models.CharField(max_length=2000, blank=False, null=False) dmti_study_start_date = models.DateField(blank=False, null=False) duration = models.PositiveIntegerField(blank=False, null=False, default=0) decision_date = models.DateField(blank=False, null=False) deliverables = models.CharField(max_length=4000, blank=False, null=False) logistics_flag = models.CharField(max_length=3, choices=CHOICES, default='No') status = models.CharField(max_length=20, choices=REQUEST_STATUS, default='Pending') approver_date = models.DateField(blank=True, null=True) approver_name = models.CharField(max_length=240, choices=APPROVER_CHOICES, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse('update_StudyRequestConcept', kwargs={'pk': self.pk}) def get_commentsStudyRequestConcept(self): return ','.join([str(i) for i in self.commentsStudyRequestConcept.all().values_list('id', flat=True)]) class CommentsStudyRequestConcept(models.Model): comments = models.CharField('Comment', max_length=2000, blank=True, null=True) commented_on = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) studyRequestConcept = models.ForeignKey(StudyRequestConcept, related_name='commentsStudyRequestConcept', on_delete=models.CASCADE) def __str__(self): return str(self.id) Now when the user enters … -
Django admin login won't grant me access even though information is correct
I have created a custom user model in django called 'Agent'. The command-line allows me to successfully create a superuser but the admin page won't allow me access even though all the credentials are correct. My app is included under INSTALLED_APPS and my AUTH_USER_MODEL = Audit.Agent I have registerred my model under admin.py but still, nothing. I am probably forgetting something small, but still can't find it. A guide in any direction would be of extreme value. Thank you in advance class AgentManager(BaseUserManager): def create_user(self, agent_email, agent_name, validation_date, company_name, password=None, **extra_fields): if not agent_email: raise ValueError("Given email must be set") email = self.normalize_email(agent_email) agent = self.model(agent_email=agent_email, agent_name=agent_name, company_name=company_name, validation_date=validation_date, **extra_fields) agent.save(using=self._db) return agent def create_superuser(self, agent_email, agent_name, validation_date, company_name, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(agent_email, agent_name, validation_date, company_name, password=password, **extra_fields) class Agent(AbstractBaseUser, PermissionsMixin): agent_email = models.EmailField(unique=True, verbose_name='Agent email') agent_name = models.CharField(max_length=100, verbose_name='Agent name') validation_date = models.DateField(default=timezone.now, verbose_name='Validation date') company_name = models.CharField(max_length=150, verbose_name='Company name') is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'agent_email' REQUIRED_FIELDS = ('agent_name', 'validation_date', 'company_name') -
Register signals or receivers in django
I did not like the idea of putting my receivers in my models.py file and I started to investigate where should my code live? as for my receivers. Then I realized that it is best practice for the receivers to be located in a file called signals.py, but this leads to the need to register the receivers, so that they work correctly, I started researching the subject and I gave realize that there are 2 ways to do it. Importing or establishing the connection of the receivers in the file models.py. Importing the receivers or establishing the connection in the apps.py file, precisely in theready ()method. This was specified in the documentation of Django but in a way not very clear or specific from my point of view. I started to investigate more about the subject and in different cases, I saw that many problems arose, either using the first method or the second one, and therefore, a question arose. Why have to register the receivers ?, specifically Why the need to have to import them? What is the best method or the best option to use ?. And what exactly is the ready () method? Thanks in advance for … -
The viewset didn't return an HttpResponse object. It returned None instead
I am returning TemplateResponse from viewset like this: return TemplateResponse(request, 'payments/cybersource_stampduty.html', template_data) but I am getting error: The view payments.views.CyberSourceResponseViewSet didn't return an HttpResponse object. It returned None instead. Why am I getting this error? incase if someone want to see entire function, here is how it looks like def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) transaction = CyberSourceTransaction.objects.filter( uuid=request.data['req_transaction_uuid']).first() # if its a stampduty if transaction.selected_plan_name == 'stampduty': template_data = { 'consumer': transaction.transfer_to, 'decision': request.data['decision'], 'transaction_uuid': request.data['req_transaction_uuid'], 'reference_number': transaction.reference_number, 'amount': transaction.amount, 'currency': transaction.currency, 'wukla_url': settings.WUKLA_URL, 'paksign_url': settings.PAKSIGN_URL, 'subscription_url': settings.DOMAIN } logger.info("Handling Cybersource transaction response with transaction_uuid: " + request.data['req_transaction_uuid'], extra={'user': ''}) return TemplateResponse \ (request, 'payments/cybersource_stampduty.html', template_data) -
Cant create a record within viewset custom view based on url parameters
Hello I have a django rest framework view set. For the create view I want to create a custom view that will create a new record based on two different parameters that are passed on through the url which are namespace and path. I looked at the documentation but i couldnt find how it should look like. I am noit sure what I need to do in order to create a record based on both url parameters. I basically tried setting the create to a CreateAPIView but it did not work class PreferenceViewSet(viewsets.ViewSet): queryset = Preference.objects.all() serializer_class = PreferenceSerializer def get_permissions(self): if self.action == 'create' or self.action == 'destroy': permission_classes = [IsAuthenticated] else: permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] def list(self, request): queryset = Preference.objects.all() serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): queryset = Preference.objects.all() serializer = PreferenceSerializer(queryset, many=True) return Response(serializer.data) I want to setup the create to create a preference with the two parameters that are passe in the url path('preferences/<str:namespace>/<str:path>', preference_path, name='preference-path'), I wanted it to create a new object with the namespace and path -
Data Migration produces ValueError that must be "User" instance but it is?
I'm trying to add a staff member to the database. I'm doing this via a data migration. I am able to add a User through the migration but I'm not able to assign it to user_id of the StaffPosition I am trying to create. The error I get is a ValueError that says I need to use a "User" instance but I thought I was doing that. I've used ipdb to troubleshoot this and look at what the values of some properties are. I've also tried grabbing user different ways, such as with the pk or id of the User instance. Another thing I did was comment out all lines of code in create_urechr_user except for the section that creates the User object. With that, I was able to successfully add the User to the database. But I'm unable to make my StaffPosition's user_id that User. # -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2019-02-08 21:23 from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import User def create_urechr_user(apps, schema_editor): staffPosition = apps.get_model("hr", "staffPosition") User.objects.create_user( username = "urechr", password = "TechOps", is_active = True, email = "", ) staff = staffPosition.objects.get(pk = 95) user = User.objects.get(username … -
How to solve - Provisional headers are shown?
How to solve - Provisional headers are shown? I have a Django application using rest_framework, simple JWT and corsheaders. GET request works perfectly, however POST I get a 200 code, but with restrictions. Provisional headers are shown Authentication works perfectly, however I am having problem in request. INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ... ] CORS_ORIGIN_ALLOW_ALL = True REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'lbuser_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(days=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } -
Why is my Class-based delete view not working?
My delete view is not working and the error message is: Page not found (404) Request Method: GET. I am trying to delete my uploaded file based on its primary key and so far, my url is able to link me correctly based on the pk. This is my urls.py: path('post/<int:post_id>/lesson_delete/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'), My views.py: class LessonDeleteView(DeleteView): model = Lesson success_url = '../' template_name = 'lesson_confirm_delete.html' This is the html template that brings user to the delete view: {% extends "store/base.html" %} {% block content %} <div id="main"> <table class="table mb-0"> <thead> <tr> <th>Title</th> <th>Author</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for l in Lesson %} <tr> <td> {% if l.file %} {{ l.title }} {% else %} <h6>Not available</h6> {% endif %} </td> <td>{{ l.post.author }}</td> <td>{% if l.file %} <a href="{{ l.file.url }}" class="btn btn-primary btn-sm" target="_blank">Download</a> {% else %} <h6>Not available</h6> {% endif %} </td> <td> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'lesson_delete' lesson_id=l.id %}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} This is my html template for DeleteView: {% extends "store/base.html" %} {% block content %} <div class="content-section" id="main"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete Lesson</legend> … -
mysql query function works in python shell but ImproperlyConfigured error when run in python
I am practicing using mysql in django and wanted to run a simply query on a database that I set up in my settings.py. I am connected to the database and can run the query fine in the manage.py shell. However, when I run the same code in a python file it does not work. Does anybody know why the query does not work in the python file? query : from django.db import connections def query(id): c = connections['default'].cursor() c.execute("SELECT * FROM `peptides_proteins_000005 WHERE protein_id=%s;",[id]) rows = c.fetchone() return rows print(query(4519)) In the shell I will get a row back with the information I want however, when run in the python file I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
render template after form submit ajax django
i have a form which getting user input and i'm passing to python script on view.py and then rendering to html template. i want all this done without refreshing the page. view.py: def index(request): if request.method == 'POST': form = PnrForm(request.POST) if form.is_valid(): pnr_numbers = form.cleaned_data['pnr_number'] api_key = "df566" base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/" complete_url = base_url + pnr_numbers + "/apikey/" + api_key + "/" response_ob = requests.get(complete_url) output = response_ob.json() if output["response_code"] == 200: train_name = output["train"]["name"] passengers_list = output["passengers"] aka = "this is the" for passenger in passengers_list: # store the value or data # of "no" key in variable passenger_num = passenger["no"] # store the value or data of # "current_status" key in variable current_status = passenger["current_status"] # store the value or data of # "booking_status" key in variable booking_status = passenger["booking_status"] # print following values print(" passenger number : " + str(passenger_num) + "\n current status : " + str(current_status) + "\n booking_status : " + str(booking_status)) aka = str(passenger_num) else: print("record is not found for given request") return render(request, 'main_site/index.html', {'form': form,'output': aka}) else: form = PnrForm() #print(pnr_numbers) return render(request, 'main_site/index.html', {'form': form}) index.html: <form method="POST" id="pnr_form"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> … -
Django ORM concat for related rows
Two simple models: class Thread(models.Model): pass class Message(models.Model): thread = models.ForeignKey(Thread, related_name='messages') Is it possible to do something like this? >>> thread = Thread.objects.create() >>> Message.objects.create(thread=thread, content='One') >>> Message.objects.create(thread=thread, content='Two') >>> Message.objects.create(thread=thread, content='Three') >>> t = Thread.objects.annotate( message_content=MySuperConcat('messages__content')).first() >>> t.messages_content OneTwoThree Seems like Django's Concat can't do this and now I'm not sure if desired behavior is possible at all. Note: we are using PostgreSQL 9.5 and Django 1.11.