Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django(python), invalid literal for int() with base 10: '' Problems arise
class DoctorList(models.Model): d_code = models.AutoField(primary_key=True) name = models.CharField(max_length=300) position = models.CharField(max_length=200) code = models.ForeignKey(HospitalList, on_delete=models.CASCADE, db_column="code") def __str__(self): return str(self.d_code) def increment_helpdesk_number(): last_helpdesk = DoctorList.objects.all().order_by('d_code').last() help_id = last_helpdesk.help_num help_int = help_id[13:17] new_help_int = int(help_int) + 1 new_help_id = 'd_' + str(new_help_int).zfill(4) return new_help_id help_num = models.CharField(max_length=17, unique=True, default=increment_helpdesk_number, editable=False) error code: invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/api/doctor/ Django Version: 3.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: D:\test\Backserver\test\src\com\doctor\models.py, line 22, in increment_helpdesk_number I want to create an autofield called d_0001, d_0002 d_0003... To do that, I referred to this site. Reference link But ValueError: invalid literal for int() with base 10: '' I get an error. How can I fix it? -
Is Django a backend or full stack framework [closed]
First of all, I'm an Android Developer, I want to learn how to make a restful APIs for my apps on my own, I want to go with Django to accomplish that. Currently, I'm going through the official tutorials and I'm doing very well, but I have questions about it I couldn't find useful answers on the web First: is Django a full stack or backend? can someone use Django for backed stuff and the front end developer work on the front end? Do I need to know about HTML, CCS, and javascript to be a backend developer? how much I need to know about Django to start building APIs. if you notice any misconceptions on my question please let me know, I'm new on web stuff. -
How to create a cart with Django rest framework?
I'm coding a REST API with Django REST framework I want to create a cart for a coffee shop with Django rest but I don't know how to create views and serializers.py for my project . I created my models and the cart class but I can't write views.py and Serializers.py and urls.py please help me . this is my model and cart class: #models.py from django.db import models from coffishop import settings class Food(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() type = models.CharField(max_length=50) info = models.TextField() image = models.ImageField(upload_to='images/') def __str__(self): return self.name class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Food, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity #cart class from menu.models import Food CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): food_ids = self.cart.keys() foods = Food.objects.filter(id__in=food_ids) cart = self.cart.copy() … -
How can I make my text appear below the navbar?
I'm currently coding my first website and I'm experiencing a problem I don't know how to solve. I have a home page with a navbar, and when I put text in the page, it appears cut because the text starts behind the navbar. How can I make the text appear below the navbar? Here's the code. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset= "UTF-8"> <title>DNA TRANSLATOR</title> <meta charset= "UTF-8"/> <meta name= "viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href= '{% static "css/style.css" %}'> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <style> body { background-attachment: fixed; background-color: rosybrown; } </style> </head> <body> <nav class="navbar fixed-top navbar-expand-lg navbar-light" style='background-color: snow;'> <div class = 'container'> <a class="navbar-brand" href="#">DNA Translator</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mx-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="">Translator</a> </li> <li class="nav-item"> <a class="nav-link" href="#" >Process</a> </li> </ul> </div> </div> </nav> <div class = "container"> {% block content%} {% endblock content%} </div> </body> </html> -
Django Rest Framework — no module named rest_framework. Rest_framework is installed and venv is active
I clone repository from github on my second computer, runserver does works but when typing python manage.py makemigrations Bash notice about 'no module name rest_framework' This situation is a second time. Lately I install again rest_framework but then I had install other modules. Finally I create new project but now I want resolve this problem. Screenshot is below with my venv and packages enter image description here -
How to store a large, very frequently accessed list on a server using Django?
So I'm creating a video streaming application using Django. I'm using Cassandra as my database to hold all user content, and video content. Eventually once I'm finished, the app is going to run in the Amazon cloud. Each video held in the database has about 10 (give or take) columns in it, ranging from large text files to small floats. In my app, I have a function that goes through every video entry in the database and saves each one as a dictionary (matching column names to column values as key names and values), and then creates a large list of all of the dictionaries. The database is constantly changing (every time any user watches something it changes), so the function has to run every time the page loads in order to have the most up-to-date video files. This is leading to a clear issue, in that if the list becomes very large - say 100,000+ videos - then the program is having to search through and modify 100,000+ items in a list every time the page loads. My question is, how do I go about having a list of videos on the server that is constantly being updated and … -
How to use in built Auth model in django to manage login for 4000-5000 users belongs to different Company
I am new to Django and i am working on one requirement where i have multiple company for example A,B,C,D and each Company will have 1000 Users. I have used Django inbuilt Auth Module for authentication purpose and created one model as shown below. class ShiftChange(models.Model): ldap_id = models.CharField(max_length=64) Vendor_Company = models.CharField(max_length=64,choices=VENDOR_CHOICES,default='genesys') EmailID = models.EmailField(max_length=64,unique=True) Shift_timing = models.CharField(max_length=64,choices=SHIFT_CHOICES,default='General_Shift') Reason = models.TextField(max_length=256) # updated_time = models.DateTimeField(auto_now=True) Below are the things which i have created. For login i'm using django inbuilt User model and i am using email id to filter result as shown below in my view so in this when user is login based on his email id data getting filter and he Can see only his data. def retrieve_view(request): # alluser = ShiftChange.objects.all() alluser = ShiftChange.objects.filter(EmailID=request.user.email) # alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) return render(request, 'apple/shift2.html', {'alluser': alluser}) Task: Instead of asking all 4000 user to login by Creating account i want if this can be possible by creating some group from django admin where i Can add all user belonging to one Company and create only one login access and share it with respective POC of Company A(Company A person should not see data of Company B,C,D). 2.other way … -
How can I get URL of model being serialized in Django REST Framework?
I am trying to create an API using Django REST Framework that looks like this: [ "expression": { "expression": e, "url": e_url }, "definition": d ] I am having problems retrieving the url field inside the expression object. I am trying to use HyperlinkedRelatedField but could not make it work. I want to point out that url is NOT a field in my Expression model. class ExpressionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedRelatedField( view_name="dictionary:expression", lookup_field="slug", read_only=True, many=False, ) class Meta: model = Expression fields = ["url", "expression"] class DefinitionSerializer(serializers.ModelSerializer): expression = ExpressionSerializer(many=False) class Meta: model = Definition fields = ["expression", "definition"] How can I retrieve the URL for expression? -
How can I test registering jira issue in Django
I'm trying to test function that connects to Jira and creates Jira issue My services.py def get_jira_client(): global jira_client if jira_client is None: jira_client = JIRA(server=JIRA_URL, auth=(jira_user, jira_password)) return jira_client def register_jira_issue(ticket_id): jira = get_jira_client() ticket = Ticket.objects.prefetch_related(Prefetch('attachments', to_attr='ticket_attachments'), Prefetch('tags', to_attr='ticket_tags')).filter(id=ticket_id).first() new_issue = add_issue(jira, ticket, ticket.owner) set_tags(new_issue, *ticket.ticket_tags) add_attachments(ticket.ticket_attachments, new_issue) def add_issue(jira, ticket, owner): issue_dict = { 'project': {'key': project_key}, 'summary': ticket.title, 'description': format_text_for_jira(ticket.description), 'issuetype': {'name': issuetype_name}, cf_username: str(owner.username), cf_hd_grant_id: ticket.grant_id, cf_user_email: str(owner.email), cf_user_fullname: f"{owner.first_name} {owner.last_name}" } new_issue = jira.create_issue(issue_dict) ticket.key = new_issue ticket.save() logger.info(f'User {ticket.owner} added issue ') return new_issue def set_tags(jira_issue, tags): tags_dict = Tags.objects.filter(id=tags.id).values()[0] chosen_tags = [key for key, _ in tags_dict.items() if _ is True] if tags_dict['cluster_calculations'] or tags_dict['cluster_installation']: chosen_tags.append(tags_dict['cluster']) jira_issue.update(fields={"labels": chosen_tags}) logger.info(f'User set tags {chosen_tags} to issue {jira_issue}') def add_attachments(files, jira_issue): jira = get_jira_client() for file in files: jira.add_attachment(issue=jira_issue, attachment=file.file) logger.info(f'User added attachment {file} to issue {jira_issue}.') function register jira issue is asynchronously called in views.py and it uses these functions: add_issue - registers issue in jira set_tags - sets labels for issue add_attachments - adds attachment to issue Does anyone know a way to test ticket registration in jira? I've tried requests_mock but it didn't work for me. I also saw some exapmples of … -
How do I revert an unfinished makemigration after adding a non-nullable field(Foreign) and filling it
I made the mistake of adding a non-nullablle field and filling it with 1. contest = models.ForeignKey(Contest, on_delete=models.CASCADE) (Contest is empty, new table) >>> python manage.py makemigrations contests You are trying to add a non-nullable field 'contest' to contestentry without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt >>> 1 When migrating it gave an error because the table of the model is empty. >>> python manage.py migrate contests psycopg2.errors.ForeignKeyViolation: insert or update on table "contests_contestentry" violates foreign key constraint "contests_contestentr_contest_id_7f53b874_fk_contests_" DETAIL: Key (contest_id)=(1) is not present in table "contests_contest". I removed the field and tried to migrate back but it didn't work then I tried to revert the migrations but it gave the following error: >>> python manage.py migrate contests 0007_remove_contestentry_nvotes Operations to perform: Target specific migration: … -
I want to change django's AutoField value
mycode.py class playerList(models.Model): d_code = models.AutoField(primary_key=True) name = models.CharField(max_length=300) position = models.CharField(max_length=200) def __str__(self): return str(self.d_code) Currently, the value of d_code is created as 1,2,3,4... What I want is to stretch like d_0001, d_0002, d_0003... How can I make it like this? Is that difficult? Please let me know -
Django upgrade adds boto to .yml file (under pip)
I'm trying to upgrade Django to 2.2.16 via pip by doing the following: Update working environment: pip install --upgrade django==2.2.16 Export working environment: conda env export --no-builds > myenv.yml However this adds boto 2.49.0 under pip: - pip: - appdirs==1.4.3 - asn1crypto==0.24.0 - bcrypt==3.1.6 - boto==2.49.0 I don't want to add boto to pip. Is there a way to avoid this? -
Django Expire token Authentication
I am working on expiring a django Token for this I am following this https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05 and my accounts/authentication.py file is like from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.exceptions import AuthenticationFailed from datetime import timedelta from django.utils import timezone from django.conf import settings # this return left time def expires_in(token): time_elapsed = timezone.now() - token.created left_time = timedelta(seconds=settings.TOKEN_EXPIRED_AFTER_SECONDS) - time_elapsed return left_time # token checker if token expired or not def is_token_expired(token): return expires_in(token) < timedelta(seconds=0) # if token is expired new token will be established # If token is expired then it will be removed # and new one with different key will be created def token_expire_handler(token): is_expired = is_token_expired(token) if is_expired: token.delete() token = Token.objects.create(user=token.user) return is_expired, token # ________________________________________________ # DEFAULT_AUTHENTICATION_CLASSES class ExpiringTokenAuthentication(TokenAuthentication): """ If token is expired then it will be removed and new one with different key will be created """ def authenticate_credentials(self, key): try: token = Token.objects.get(key=key) except Token.DoesNotExist: raise AuthenticationFailed("Invalid Token") if not token.user.is_active: raise AuthenticationFailed("User is not active") is_expired, token = token_expire_handler(token) if is_expired: raise AuthenticationFailed("The Token is expired") return (token.user, token) and I have added in settings.py like this REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'accounts.authentication.ExpiringTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', … -
Django app not displaying data in template
im brand new to Django and attempting to make my first ECommerce site. I'm attempting to get a list of products from a .JSON file to display in my products.html template. The products are in place, as shown in the Django admin portal, productsis definied with in my views.py file and i've done loaddata but nothing comes through. I've added some screenshots and code below to further explain. Views.py Code: from django.shortcuts import render from .models import Product def all_products(request): products = Product.objects.all() context = { 'products': products, } return render(request, 'products/products.html', context) products.html Template: {% extends "base.html" %} {% load static %} {% block page_header %} <div class="container header-container"> <div class="row"> <div class="col"></div> </div> </div> {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col"> {{ products }} </div> </div> </div> {% endblock %} My folder structure is correct but I'll post it here just incase: Any help would be great as i've been stuck with this for a while now. Thanks! -
return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable
Hello am new to python and django and i am practicing django but when i command python manage.py makemigration and python manage.py migrate then i got an error as show in the title. the full error is mentioned below. seeking for help, thankyou ** full error ** C:\Users\Manan\python projects\djangoandmongo\new_Socrai>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\core\management\base.py", line 341, in run _from_argv connections.close_all() File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Manan\python projects\djangoandmongo\dandm_env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, … -
Web Socket is working in local but not in production
I develop a web app using django channels. It is working properly in local but not in production. here is my configurations. I didn't know what I'm missing. project.service asgi.py here is nginx configurations. upstream channels-backend { server 127.0.0.1:9001; } server { listen 80; server_name edseedwhiteboard.yarshatech.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sandeep/EdSeed_WhiteBoard; } location /media/ { root /home/sandeep/EdSeed_WhiteBoard; } location /ws/ { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { include proxy_params; proxy_pass http://unix:/run/whiteboard.sock; } } and here is actual error after depoyed. -
Django Save Multiple Objects At Once
I have been practicing Django for a while now. Currently I am using it in a project where I'm fetching Facebook data via GET requests and then saving it to an sqlite database using Django models. I would like to know how can I improve the following code and save a list of Facebook posts and their metrics efficiently. In my current situation, I am using a for loop to iterate on a list containing several Facebook Posts and their respective metrics which is then associated to the specific Django model and finally saved. def save_post(post_id, page_id): facebook_post = Post(post_id=post_id, access_token=fb_access_token) post_db = PostsModel(page_id=page_id, post_id=post.post_id) post_db.message = facebook_post.message post_db.story = facebook_post.story post_db.full_picture = facebook_post.full_picture post_db.reactions_count = facebook_post.reactions_count post_db.comments_count = facebook_post.comments_count post_db.shares_count = facebook_post.shares_count post_db.interactions_count = facebook_post.interactions_count post_db.created_time = facebook_post.created_time post_db.published = facebook_post.published post_db.attachment_title = facebook_post.attachment_title post_db.attachment_description = facebook_post.attachment_description post_db.attachment_target_url = facebook_post.attachment_target_url post_db.save() post_db is a Django model object instantiated using PostsModel while Post is a normal Python Class which I wrote. The latter is simply a collection of GET requests which fetches data from Facebook's Graph API and returns JSON data whereby I associate relevant data to class attributes (message, 'shares_count`). I read about the bulk_create function from Django's documentation … -
How can I receive the recorded file with django?
I record the audio file by using 'XMLHttpRequest' recorder in javascript. (record, save and upload are done) I changed this file into blob and sent to server. I tried to check it with django but it was empty {}. How can I receive the recorded file with django? -
How to change admin panel pages separately for each model?
I need to add on the root model page (not a page for record editing) some fields for editing records in other models and the save button to save them. For example This fields going to save data in tables with one record limitation so each field will save data to specified record in specified model. This is only example. So how to make custom editions on model pages in admin panel? Is it possible? -
can something happen like changing the parameters of django model fields according to conditions changing parametrs of timefield
Iam working on a project and I have the following model : class Meeting(models.Model): topic = models.CharField(max_length=200, null=True) subject = models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True) date = models.DateField(default=date.today, null=True) STATUS = ( ('Incomplete', 'Incomplete'), ('Concluded', 'Concluded'), ('Deleted', 'Deleted') ) STD = ( ('8', '8'), ('9', '9'), ('10', '10') ) std = models.CharField(max_length=3, choices=STD, null=True) link = models.URLField(max_length=500, null=True) status = models.CharField(max_length=40, null=True, choices=STATUS, default="Incomplete") participents = models.ManyToManyField(Student, blank=True) time = models.TimeField(auto_now_add=False, null=True) def __str__(self): return self.topic so what I want is if a user is trying to edit a meeting , the date should not be added by default , but the user should select it , and if the user creates meeting then by default todays date should be added . my views.py function for updating meeting: @allowed_users(allowed_roles=['Teachers']) def upd_meeting(request, id): meeting = Meeting.objects.get(id=id) form = MeetingCreationForm(instance=meeting) if request.method == "POST": form = MeetingCreationForm(request.POST, instance=meeting) print(request.POST["topic"]) if form.is_valid(): form.save() return redirect('dashboard_pg') else: return HttpResponse("Something went wrong pls try again") context = {'form': form} return render(request, 'main/crt_meeting.html', context) my forms.py file : class MeetingCreationForm(ModelForm): date = forms.DateField() class Meta: model = Meeting fields = ['topic', 'subject', 'std', 'link', 'time', 'date'] -
CSS files not updating on Heroku
Hi, i am running a Django webapp on a Heroku dyno. My problem is the following one: Sometimes, CSS files are not updated after deploy. They are updated on the GitHub repo, but not in the server. I have manually checked them using:heroku run bash -a myapp**, and the code is different from github (I am sure that I checked the deployed branch), they remain in older versions. Static files are served correctly, i do not get any 404 and it only happens with CSS files. I have tried `heroku restart -a myapp`, but it does not work. If I rename the files, the problem is solved, but as you can imagine this is not a viable solution. I use the GitHub deploy method, so I do the add, commit, push cycle and then i manually select and deploy the branch from the heroku dashboard. Does anyone know how can i solve this without changing files' names? Thanks! -
How to I make my review model form show the name of the current user when rendered in template
I am trying yo create a review form in django. I have rendered the form but I would like the form to display the name of the current logged in user. To enable me associate each review with a user. here is my model: class Review(models.Model): company = models.ForeignKey(Company, null=True, on_delete=models.SET_NULL) # SET_NULL ensures that when a company is deleted, their reviews remains reviewers_name = models.CharField(max_length=250, verbose_name='Reviewed By: (Your Name)') review_text = models.TextField(max_length=500, verbose_name='Your Review: (Maximum of 200 Words)') rating = Int_max.IntegerRangeField(min_value=1, max_value=5) date_added = models.DateField('Review Date', auto_now_add=True) Here is my view: def submit_review(request): form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid: form.save() # gets the company that was immediately submitted in the review form company = request.POST.get('company') # gets the rating that was immediately submitted in the review form rating = request.POST.get('rating') # uses the name of the company submitted to instantiate the company from the Company database companyone = Company.objects.get(pk=company) """ emloys companyone above to retrieve already existing average rating associated with it adds this to the current rating sent by the user and stores the total back to the average rating field of companyone """ companyone.average_rating = round((int(rating) + int(companyone.average_rating))/2) companyone.save() return redirect('review-submitted') … -
Django error when using mysql-connector-python
I want to set the mysql database using mysql-connector-python for setting up a web site made with Django using a database backend but I get this error: django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My credentials (name, user, password, host, port) works fine, so the problem isn't here. DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'library', 'USER': 'username', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { 'autocommit': True, 'use_pure': True, }, } } I'm using python 3.8.5 and mysql-connector-python 8.0.21 and I understand that mysql-connector-python, starting from version 8.0.13, has a bug, which makes it impossible to use with Django and to avoid the bug I added ‘use_pure’: True in database options. But it doesn't work. I found this question but it doesn't say anything about using ‘use_pure’: True. If the mysql-connector-python isn't compatible with python 3, what can I use instead? (I can't wait for the support release). -
Django - Disable Foreign key constraints is failing
For some reasons I am trying to temporarily disable foreign key constrains check on MySQL. It is forced and enabled by default by django. Trying to disable it manually fails with syntax error as below. Python 3.6/Django2.2 (Pdb) cursor.db.cursor().execute("SET FOREIGN_KEY_CHECKS=0;") *** django.db.utils.OperationalError: near "SET": syntax error I saw different posts using the above command and that it should work. Any help or pointer for what I am missing will be very helpful. -
django view dont show anything
I'm working to create an event page in my Django work. Although I wrote a code to obtain database data when I try to load the front page(from exhibition_view.html), just the exhibition.view_html loads and no article return and does not show in that page. the weird thing is that seminar_view and exhibition_view are the same, and seminar_view does work! I tried very much to solve the issue, but had no idea what is happening! below is my code: Model.py from django.db import models from django.utils import timezone from tinymce.models import HTMLField class EventType(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: verbose_name_plural = "Event Types" def get_deleted_event_type(): return EventType.objects.get(name='no-category') class Event(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) EVENT_CHOICES = ( ('seminar', 'seminar'), ('exhibition', 'exhibition'), ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=250, unique_for_date='publish', allow_unicode=True, unique=True) body = HTMLField() publish = models.DateTimeField(default=timezone.now) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) events = models.ForeignKey(EventType, on_delete=models.SET(get_deleted_event_type)) event_type = models.CharField(max_length=15, choices=EVENT_CHOICES, default='seminar') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') event_index = models.IntegerField() class Meta: ordering = ('-publish',) verbose_name_plural = "Events" def __str__(self): return self.title Views.py from django.shortcuts import render from .models import Event from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q def seminar_detail(request, slug): …