Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Returning user's name instead of it's ID in a many-to-one relationship in Django Rest Framework
I'm returning all the "posts" in response of a get request like this # views.py class PostView(APIView): def get(self, request): serializer = PostsSerializer(Post.objects.all(), many=True) return Response(serializer.data) And here's the serializer # serializers.py class PostsSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['description', 'files', 'created_at', 'author'] And here's the model # models.py class Post(models.Model): author = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) files = models.FileField(upload_to=upload_path) created_at = models.DateTimeField(auto_now_add=True) description = models.TextField(default="No Description Has Been Added") def __str__(self): return self.description So as you can see in the models, I have a field called author which has a many-to-one relationship with the user who created the post. Now here's the problem: In the response of that get request, I get authors IDs instead of their names. Each author has a displayname field and that's the field that I want. I thought of iterating each Post and replacing each author's value with it's name by querying the model that contains them (Account). Like this # views.py class PostView(APIView): def get(self, request): serializer = PostsSerializer(Post.objects.all(), many=True) dataList = serializer.data for index in range(len(dataList)): for key in dataList[index]: if key == 'author': dataList[index][key] = Account.objects.get(id=dataList[index][key]) return Response(dataList) But this throws back Object of type Account is not JSON serializable … -
Search outlooks in django
How can I make the search word look like this. I want it to be tabbed, no need for the user to click on the word. -
Django does not respect environment variables set in venv activate script
I have perused the similar questions available, but don't see any that explicitly match the behavior I am seeing in my project. Like many other folks, I am trying to move my sensitive key information out of my settings.py file. To do this, I have added multiple export statements to the end of the activate script for my local venv environment, like ###env/bin/activate export AWS_ACCESS_KEY_ID="**********" export AWS_SECRET_ACCESS_KEY="************" From there, I can reload the environment and confirm that they key value pairs are available by running python manage.py shell >> import os >> os.environ Which shows the correct values for the keys. Additionally, I can launch the development server with python manage runserver 0:8080 And am able to post files to the AWS S3 bucket as desired. However, once I reboot the server to restart the uWSGI process and access the site from its domain, I am unable to post files to S3. Instead I get a NoCredentials error, despite the fact that I can see the relevant AWS key information in the settings information available when the debug setting is set to TRUE. Why are the variables exported in the activate script available when launching the development server but not … -
Constraint of a single True value in many-to-many through table BooleanField
I want to achieve the following: Listings can be tagged under multiple categories A listing can have at most one main category. This is the category that best describes it, of all the categories it is tagged with. Admins should not be able to mark multiple main categories for a single listing. In my models.py I have: from django.db import models from django.db.models import UniqueConstraint, CheckConstraint class Listing(models.Model): title = models.CharField(max_length=50), content = models.TextField(), categories = models.ManyToManyField( 'Category', through='CategoryMembership', related_name='listings' ) class Category(models.Model): title = models.CharField(max_length=50), class CategoryMembership(models.Model): listing = models.ForeignKey( Listing, on_delete=models.CASCADE ) category = models.ForeignKey( Category, on_delete=models.CASCADE ) main_category = models.BooleanField(default=False) class Meta: constraints = [ UniqueConstraint( name='unique_listing_category_membership', fields=['listing', 'category'] )] To achieve 2 and 3 I thought I could add another constraint to CategoryMembership's Meta class. But I am not sure how to proceed as I do not want to prevent listings having multiple categories where main_category == False in the through table. Is such a constraint possible? Or is there a smarter way to structure the models to achieve this? -
Django Serializer's Source argument is not working
My two models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=200) customer_code = models.CharField(max_length=300, blank=True, null=True, default=None) class Bill(models.Model): customer = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True, related_name="customer_bill" ) payable_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) View: class BillView(APIView): def get(self, request, format=None): q = Bill.objects.all().select_related('customer') s = BillSerializer(q, many=True) return JsonResponse({ "bill": s.data }) Serializer: class BillSerializer(serializers.ModelSerializer): customer_code = serializers.CharField(source='user.customer_code', read_only=True) class Meta: model = Bill fields = ('id','payable_amount','customer_code') # binding customer_code here Current Output: "bill": [ { "id": 1, "payable_amount": "1000.00" }, { "id": 2, "payable_amount": "2000.00" } ] Expected Result: "bill": [ { "id": 1, "payable_amount": "1000.00", "customer_code": "CUS10001" # want this to be attached }, { "id": 2, "payable_amount": "2000.00", "customer_code": "CUS10002" # want this to be attached } ] I am trying to get all the bills and their customer-related details (i.e. 'customer_code', 'email' etc.) with it. However, "source='user.customer_code" does not seem to have any effect at all. What am I missing? Please suggest me. I have been following along this: this stackoverflow post with no luck. -
If statement on Django template based on model data
I have an if statement on my django template on what to display. but It wont change, it stays at *No warning*, whats wrong in my code? Thanks! condition: if my app detects 15 entries of extreme it will display Warning else if it detects more than 15 entries of extreme it will display Critical. models.py class Data(models.Model): level = models.CharField(max_length=10, blank=True, default='') amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def update_level(self): if 0.1 <= self.amount < 2.5: return 'Low' elif 2.5 <= self.amount < 7.5: return 'Medium' elif 7.5 < self.amount < 15: return 'High' elif 15 <= self.amount < 30: return 'Very High' elif 30 <= self.amount < 200: return 'Extreme' views.py def index(request): num = Data.objects.all() context = {'num': num} return render(request, 'analytics.html', context) html <h3>{{ num.level }}</h3> {% if num.level < 15 %} <h3 style="color:red;">Critical</h3> {% elif num.level == 15 %} <h3 style="color:yellow;">Warning</h3> {% else %} <h3>No Warning</h3> {% endif %} -
How to use multiple database in Django
I have to use two databases, one is a third party db(MySql) for which I only have read access. Another db is my Django application's db(Postgres). I need to access the third party's sql db , to run some calculations and use my Django applications db(Postgres) to store those calculated values. I am very new to Django, I understand the concept of Models , but my knowledge is very limited to adding users logging them in etc. Can anybody point me in the right direction or let me know about some best practices to be followed in order to achieve this ? To stream line my question, after adding both db details in settings.py what will happen when I run migrate command ? Especially the third party db ? -
How to add items in a dictionary?
Here I have two different types of data lists. I want to add value list inside property list. How can I do this ? "property": [ { "proeprty1": "name1" }, { "property2": "name2" }, { "property3":"name3" } ], "value": [ 1700, 1500, 1000 ], The desired output I want is: "property": [ { "proeprty1": "name1", "value": 1700 }, { "property2": "name2", "value": 1500 }, { "property3":"name3", "value": 1000 } ], -
Can I have a folder instead file for a Django custom command?
The only way I know to create a custom Django command is by putting the file in the project/app/management/commands folder like this project/app/management/commands/my_custom_command.py But I would like to know if there is a way to make a directory (like a python package) instead of a single file. It should be something like this: project ├── app | ├── management | | └── commands | | ├── my_custom_command | | | ├── __init__.py | | | └── ... (other stuff like settings and output files) | | └── ... | └── ... ├── manage.py └── ... There is a way to do something like that? I think it is possible to use a whole app folder to do something similar saving the command stuff in the app folder, but I don't like that solution. -
Why does Django ORM not find related object in post_delete signal?
When I delete a PumpLog I delete the related Invoice via on_delete = models.CASCADE. Invoices have a post_delete signal that queries on that relationship (see the line with #ERROR). So it goes: user deletes PumpLog -> which triggers delete Invoice -> which triggers Invoice post_delete signal models.py class PumpLog(BasicModelFields): gallons = models.PositiveIntegerField(blank=True, null=True, editable=False) class Invoice(models.Model): pump_log = models.ForeignKey('PumpLog', on_delete = models.CASCADE) def post_invoice_delete(sender, instance, **kwargs): instance.pump_log #ERROR # or print(instance.pump_log_id) #displays the correct id. But the below query fails. PumpLog.objects.filter(index = instance.pump_log_id) #ERROR The error: records.models.PumpLog.DoesNotExist: PumpLog matching query does not exist. I understand to some degree that the PumpLog could be deleted according to the docs: Note that the object will no longer be in the database, so be very careful what you do with this instance. Technically this warning refers to the Invoice in this case NOT the PumpLog. Plus in PGAdmin I can query the database directly and see the PumpLog and Invoice are still there. So why is the ORM having trouble finding the PumpLog? Is the PumpLog artificially removed from the scope of the ORM even though it hasn't been removed from the database yet? Or am I not understanding this correctly? -
How to import posts from Wordpress to Wagtail 2 (Draftail editor) including images?
I'm trying to import posts from Wordpress to Wagtail including images. I'm conscious about the fact that Draftail editor saves images with a dedicated tag, ex: <embed alt="fonctionnement-pim-schema-640.png" embedtype="image" format="fullwidth" id="412" /> When I import my posts from Wordpress, I convert img tags to embed tags. Bellow a snippet of my code: resp = requests.get(img["src"], stream=True) if resp.status_code != requests.codes.ok: print("Unable to import " + img["src"]) continue fp = BytesIO() fp.write(resp.content) image = Image(title=file_name, width=width, height=height) image.file.save(file_name, File(fp)) image.save() try: embed_id = image.get_rendition("original").id embed_alt = image.get_rendition("original").alt new_tag = soup.new_tag('embed', alt=f'{embed_alt}', embedtype="image", format="fullwidth", id=f'{embed_id}') img.replace_with(new_tag) It seems to work. When I check the database all img tags are replaced with a correctly formatted embed tag and all images are downloaded to the media folder. Unfortunately, when I check the admin area. The embed tag exists but the image is not recognized: When I a use a generic embed tag in my import script (I mean without using "format" but the same embed code for all images) the import is working well (including within Draftail). Could "format" or "f string" introduce something wrong? Any help would be much appreciated! Thank in advance. -
Django-Zappa deployment error: Error: Your app_function value is not a modular path. It needs to be in the format `your_module.your_app_object`
Zappa is not recognizing my django application I am getting this error: error While zappa init, zappa automatically get that its django application while in my case I am getting this: error source Thanks in advance! -
How do i display a ModelForm into HTMLtemplate?
I have a template in which i display a Form for users to upload images. In the same template i want the images uploaded from users to be shown so i can make a gallery from users uploads. The problem is that the Form is being displayed without any problem but i am struggling to display the photos uploaded. (They are uploaded to the Data Base withouh any error too.) My models.py looks like this class categoria(models.Model): nombre = models.CharField(verbose_name = "nombre categoria", max_length = 20) def __str__(self): return self.nombre class imagen(models.Model): titulo = models.CharField(verbose_name = "el titulo de la imagen", max_length = 20) imagen = models.ImageField(verbose_name = "imagen que se suba", upload_to = "galeria") descripcion = models.CharField(verbose_name = "descripcion de la imagen", max_length=60, null = True, blank = True) creada = models.DateTimeField(auto_now_add=True) categorias = models.ManyToManyField(categoria) def __str__(self): return "El titulo es: {}, la imagen: {}, la descripcion: {}, ha sido creada en: {}, y pertenece a las categorias: {}".format(self.titulo, self.imagen, self.descripcion, self.creada, self.categorias) class formulario_img(ModelForm): class Meta: model = imagen fields = ['titulo', 'imagen', 'descripcion', 'categorias'] The view for showing the images looks like this from .models import formulario_img, imagenfrom def imagenes_galeria(request): imagenes = formulario_img.objects.all() return render(request, "galeria/galeria.html", {"imagenes":imagenes}) … -
Django form – sending uploaded files as attachments over email
Basically, the title says it all. This is the code I'm using: documents = self.request.FILES.getlist('my_documents') mail = EmailMessage( 'Subject Line', 'Message Body!', 'from_email', ['to_email'] ) for d in documents: mail.attach(d.name, d.file.read(), d.content_type) mail.send() Sending the email works fine, and I do get the attachments. However, there seems to be a problem with the content of those attachments. Trying to open the files does not work. What am I doing wrong? I suspect it has something to do with the encoding of the second argument of the mail.attach function, but I can't seem to figure it out. Thanks! -
Why am I getting a No Reverse Match Error
HI working on a new site using Django. can't seem to figure this bug out. First the intended site will be structured as; Home page - Showing different languages with links to countries you can learn those languages in. Click on a country on home page -> Country page Country page will list all fo the schools that teach that language in that country. Click on a school on country page -> School page. I figured out this line of code in the Country page is causing the issue, but I don't know how to fix it <a href="{% url 'schools' schools.id %}"> <div class="left"><h4>Test Link</h4></div> </a> This is the error I get in the browser NoReverseMatch at /5/ Reverse for 'schools' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<country_id>[0-9]+)/(?P<schools_id>[0-9]+)/$'] Code from the project: Models.py from django.db import models class Languages(models.Model): language = models.CharField(max_length=100, blank=True, null=True) country = models.ManyToManyField('Country', blank=True) image = models.CharField(max_length=100, blank=True) def __str__(self): return self.language class Country(models.Model): country_name = models.CharField(max_length=50) country_image = models.CharField(max_length=100, blank=True) country_city = models.ManyToManyField('City', blank=True) def __str__(self): return self.country_name class City(models.Model): city_name = models.CharField(max_length=50) city_image = models.CharField(max_length=1000, blank=True) city_schools_in = models.ManyToManyField('Schools', blank=True) def __str__(self): return self.city_name class Schools(models.Model): school_name = models.CharField(max_length=100) school_image = … -
When I send a reset password email, my program closes
The problem : I am setting up the "forgot password" functionality for my website but whenever it is triggered it shuts down the website. (when I hit the "submit" it waits for a while and then shuts down.) I have checked all the code multiple times and I don't understand why you smart people are my last hope! URLS: path('reset_password/', auth_views.PasswordResetView.as_view(), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name="password_reset_complete"), SETTINGS #SMTP Config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '*****@gmail.com' EMAIL_HOST_PASSWORD = '********' the command line output that it gives out just before closing: [07/Feb/2021 15:51:31] "GET / HTTP/1.1" 200 25 [07/Feb/2021 15:51:40] "GET /reset_password/ HTTP/1.1" 200 1903 [07/Feb/2021 15:51:50] "POST /reset_password/ HTTP/1.1" 302 0 -
how to deleting extra OrderItems in Orders?
this is my order admin. when a customer reserve a product it goes to order item section in the down. but there are some extra order items that they are empty. i want to when a customer adds a product just that product be in the admin panel. how i can remove that empty order items??? model: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') ref_code = models.CharField(max_length=20, blank=True, null=True) # products = models.ManyToManyField(OrderItem) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True, blank=True, related_name='addresses') created_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null=True, blank=True) ordered = models.BooleanField(default=False) def __str__(self): return self.user.full_name class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='products') ordered = models.BooleanField(default=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.product.name}" serializer: class OrderItemSerializer(serializers.ModelSerializer): product = serializers.SerializerMethodField() final_price = serializers.SerializerMethodField() class Meta: model = OrderItem fields = ( 'id', 'product', 'quantity', 'final_price' ) def get_product(self, obj): return ProductSerializer(obj.product).data def get_final_price(self, obj): return obj.get_final_price() class OrderSerializer(serializers.ModelSerializer): order_items = serializers.SerializerMethodField() total = serializers.SerializerMethodField() class Meta: model = Order fields = ( 'id', 'order_items', 'total', ) def get_order_items(self, obj): return OrderItemSerializer(obj.products.all(), many=True).data def get_total(self, obj): return obj.total_price() -
Not being able to upload image to django project
While I have the images stored into my 'img' file it isn't showing up inside of my virtual environment, I will provide a screenshot of both the images inside of my file plus the virtual environment folder structure. Below is the error message. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/projects/img/todo.png 'projects\img\todo.png' could not be found You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Django problems with static files on AWS S3 Bucket
I have a very weird situation with my Django Website. I put all my static and media files on an Amazon S3 bucket. The media folder is for profile, blog pictures and the static folder holds, all the css, js, img, scss etc. Everything is working fine except that the website is loading properly just when I use Safari, in Chrome it doesn't load my tags which have bootstrap classes for images and on firefox id doesn't load the tags and the js as well. The js is rendering my charts. What could be the problem. I'll put my cod configuration for AWS S3 and a screenshot from Safari, Chrome and Firefox. settings.py AWS_ACCESS_KEY_ID = aws_access_key_id AWS_SECRET_ACCESS_KEY = aws_secret_access_key AWS_STORAGE_BUCKET_NAME = aws_storage_bucket_name AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'ecomon.storages.MediaStore' storages.py which I use for DEFAULT_FILE_STORAGE (media folder): from storages.backends.s3boto3 import S3Boto3Storage class MediaStore(S3Boto3Storage): location = 'media' file_overwrite = False How it's on Safari: How it's on Chrome: How it's on Firefox: In case it's needed, the media folder it's working fine, … -
NoReverseMatch at /alumni/2/alumni_cv/ Reverse for 'alumni_profile' with arguments '('',)' not found
I am facing problem. code in template: alumni_cv.html___ <a href="{% url 'alumni_cv' user.alumniprofile.id %}" class="btn btn-primary btn-block"><b>CV</b></a> When I click this button the above NoReverseMatch at /alumni/2/alumni_cv/ Reverse for 'alumni_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['alumni/alumni_profile/(?P[^/]+)/$'] models.py_____ class AlumniProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) phone = models.CharField(max_length=50) occupation = models.CharField(max_length=50) image = models.ImageField( upload_to='alumni/', null=True, blank=True, default="default_user_avatar.jpg") bio = models.TextField() date_of_birth = models.DateField(null=True, blank=True) district_of_birth = models.ForeignKey( TownCityDistrict, on_delete=models.CASCADE, null=True, blank=True) gender = models.CharField(max_length=20, choices=genders) present_address = models.CharField(max_length=254) permanent_address = models.CharField(max_length=254) blood_group = models.CharField(max_length=10, choices=blood_groups) university_bachelor_session = models.CharField(max_length=50) university_masters_session = models.CharField(max_length=50) university_hall = models.CharField(max_length=100) university_batch = models.CharField(max_length=20) slug = models.SlugField() facebook_url = models.URLField(blank=True, null=True) linkedin_url = models.URLField(blank=True, null=True) instagram_url = models.URLField(blank=True, null=True) twitter_url = models.URLField(blank=True, null=True) skype_id = models.CharField(max_length=100, blank=True, null=True) zoom_id = models.CharField(max_length=100, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) visible_to_public = models.BooleanField(default=True) def __str__(self): return str(self.phone) class Meta: verbose_name_plural = 'Alumni' class AlumniEducation(models.Model): user = models.ForeignKey(AlumniProfile, null=True, on_delete=models.CASCADE) exam = models.CharField( max_length=50, verbose_name='Examination/Degree', blank=True, null=True) exam_year = models.DateField( verbose_name='Examination Year', blank=True, null=True) institute = models.CharField( max_length=100, verbose_name='Institute Name', blank=True, null=True) board_university = models.CharField( max_length=50, verbose_name='Board/University', blank=True, null=True) result = models.CharField( verbose_name='Result/Grade', max_length=20, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) visible_to_public = models.BooleanField(default=True) def … -
Why are my users able to log in despite having is_Active set to false?
I am using abstractbaseuser and baseusermanager. Why are my users able to log in despite having is_Active set to false? I thought that is_active=False by default makes it such that users cannot login? If my undeerstanding is wrong, how can I make it a default? models.py class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = MyAccountManager() def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True -
Get Average of Date Range in Django Queryset
I have been beating myself with this for hours and now decided to put my hands up for help. Question: What I would like to show all the records from BBSO_Records which does not have a BBSO_Record_Actions as well as which has a BBSO_Record_Actions(SQL left Join). Then use this queryset to run a date difference on the date_record and today and calcuate the average on this new field. My models are as follows: # MODELS class BBSO_Records(models.Model): date_recorded = models.DateField() details_of_observation = models.TextField() class BBSO_Record_Actions(models.Model): bbso_record_ID = models.ForeignKey(BBSO_Records, on_delete=models.CASCADE, verbose_name="BBSO Record") recommended_action = models.TextField(verbose_name='Recommended Action') date_closed = models.DateField(blank=True, null=True) # views which i am testing is this def open_avg_records(): x = BBSO_Records.objects.filter(bbso_record_actions__date_closed__isnull=True)\ .aggregate(avg_diff=Avg(ExpressionWrapper(F('date_recorded') - date.today(), output_field=DurationField()))) return x.avg_diff if I do a print of x I get the following: {'avg_diff': datetime.timedelta(0)} Any guidance will be greatly appreciated. -
how to implement live page reload with ajax?
i am new to ajax. i created function where you can submit form without reloading the page. and it worked perfectly.but i want to extend it more further in my django ajax app, when i submit the form the template where the form details are stored should also be updated live. when i submit form and to see the post i need to reload the post page. i want to remove that.. basically when i submit form my other templace should update that template live so i don't have to update it add_post.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>hello</h1> <form id="post_form"> {% csrf_token %} <p>name:</p> <input type="text" id="name" name="name"><br> <p>email:</p> <input type="text" id="email" name="email"><br> <p>bio:</p> <input type="text" id="bio" name="bio"><br> <input type="submit"> </form> <script> $(document).on('submit','#post_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url:'create/', data:{ name: $('#name').val(), email: $('#email').val(), bio: $('#bio').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ } }); }); </script> </body> </html> views.py def create(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] bio = request.POST['bio'] new_profile =post(name=name,email=email,bio=bio) new_profile.save() success = 'user'+name+'created successfully' return HttpResponse(success) listview is temporary just for testing class posts(ListView): model = post template_name = 'ajax_app/posts.html' postpage.html <html … -
django.db.utils.ProgrammingError: (1146, "Table 'Project.django_apscheduler_djangojob' doesn't exist")
I am learning django-apscheduler on the window system, And used python manage.py showmigrations command in terminal but the result is 'django.db.utils.ProgrammingError: (1146, "Table 'Project.django_apscheduler_djangojob' doesn't exist")' My DB setting DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Product', # 数据库名称, 'HOST': '127.0.0.1', # 主机地址 'USER': 'root', # 数据库用户 'PASSWORD': 'password', # 密码 'PORT': 3306 # mysql的端口默认3306 } } Please help me, Thank you a lot -
Django decorators . Need help to find a solution for class based views
This is the files I'm working on. How do I restrict user to access this page? I want only admin to access this page. I've tried to use the custom decorators but it shows error for class-based-view. I'm a beginner so anyone can help?? views.py class student_register(CreateView): model = User form_class = StudentSignUpForm template_name = 'registration/student_register.html' def form_valid(self, form_class): user = form_class.save() # login(self.request, user) return redirect('datapage') forms.py class StudentSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) phone_number = forms.CharField(required=True) semester = forms.CharField(required=True) email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_student = True user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.email = self.cleaned_data.get('email') user.username = self.cleaned_data.get('username') user.password1 = self.cleaned_data.get('password1') user.password2 = self.cleaned_data.get('password2') user.save() student = Student.objects.create(user=user) student.phone_number=self.cleaned_data.get('phone_number') student.semester=self.cleaned_data.get('semester') student.save() return user urls.py urlpatterns = [ path("loginrequest/", views.login_request, name="login"), path("logoutrequest", views.logout_request, name="logout"), path('student_register/', student_register.as_view(), name='student_register'), path('teacher_register/',views.teacher_register.as_view(), name='teacher_register'), ] student_register.html <div class="container my-3"> <div class="form-group"> <h3>Register here!</h3> <br> <form method="POST" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ form.media}} <button type="submit" class="btn btn-success">Register</button> </form> </div>