Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago Generic View Data validation
I have a model Item with a foreing key in Row model. models.py from django.db import models from django.urls import reverse from django.utils import timezone class Item(models.Model): item_name = models.CharField(max_length=100, unique=True, validators=[validate_test]) number_of_questions = models.IntegerField(default=0) number_of_read_questions = models.IntegerField(default=0) def get_absolute_url(self): return reverse('uni_checker:main_editor') class Row(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) row_name = models.CharField(max_length=100, validators=[validate_test]) is_completed = models.BooleanField(default=False) deadline = models.DateField(default=timezone.now()) I'm looking for solution that will allow me to create something like that on one page: Item1_name: Row1_name; Row2_name; Row3_name; Item2_name: Row4_name; Row5_name; Row6_name; screenshot Problem For creating objects I use CreateView with form_class = Item, and context variable formset with Row forms. Problem is that I don't know how to validate data not only in form, but also in formset. If I input invalid data in row_name field, it just saves Item object, without saving Row object or showing errors. I know that something is wrong in view class or in form creation, but i couldn't find how to do it right way. Code views.py from django.views.generic import ListView from .models import Item from django.urls import reverse from .forms import ExampleFormSetHelper, CreateRowFormSet, ItemForm from crispy_forms.layout import Submit class ItemCreateView(CreateView): model = Item template_name = "uni_checker/item_create.html" form_class = ItemForm def get_context_data(self, **kwargs): … -
getting “no such table: accounts_user” after migrating and creating super user
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not … -
why am I not getting the tokens created when I tell django to do it?
I am trying to create a password reset in Django, but once the input finds the email in the database then send an email with their token similar to http://localhost:8000/account/account-recovery/process-reset/7d498a893edc45aa921a48f81f4826d3. it works amazingly until here, but after checking in Django shell the function that checks tokens. I have another problem it returns False that means no token was generated in the database. >>> verify_password_token('7d498a893edc45aa921a48f81f4826d3') False models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(pre_save, sender='account.User') def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') helper.py def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): return False if token is not None: return True else: return False my view only contains, if an email was found then send the email form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')): -
Get request parameter not triggering if statement in Django
Django newbie. I'm trying to pass 'id_numb' as a get request, here's the URL: mysite/?id_numb=1. However, it does not make it to the second if statement. if request.GET['id_numb']: id_numb = request.GET['id_numb'] if id_numb == 1: # doesn't make it here - never get to this code, even when 1 is passed ....different code else: ....some code else: .... some other code -
Unable to save null to ForeignKey in an intermediate model - Django
My use case is, there is a Workshop and there are multiple positions (Workshop_Position) in it. For any position there will be multiple applications. The workshop owner has to approve an application for the user to be a team_member in the workshop. I am using a ManyToMany relationship for this, see below my models. class Workshop(models.Model): ... team_members = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='member_in_workshops', through='Membership') ... class Workshop_Position(models.Model): position_heading = models.CharField(max_length=100, null=False, blank=False) ... class Membership(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='membership', blank=True, null=True, on_delete=models.CASCADE) position = models.ForeignKey('Workshop_Position', related_name='membership', on_delete=models.CASCADE) workshop = models.ForeignKey('Workshop', related_name='membership', on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ("position", "user") So when a new position is created, I am saving the position to the Workshop_Position table and attempting to save the workshop the position belongs to with a null user into the Membership. I need to save this with a null user because there are going to be multiple applications to a Workshop_Position and the owner selects which user gets into the position. I am doing the below, { "user": " ", "position": "3", "workshop": "1" } But I get an error when I try to save the above to the Membership model. "user": [ "This field may not be null." … -
Why use @apiDefine together with @apiPermission in apiDocjs?
I am using apiDocjs in order to document my API. I have to define some Permissions, but when I simply use @apiPermission, this line just appears as plain text. When I add @apiDefine (https://apidocjs.com/#param-api-define) prior to that - I get no error, but it does not seem to change anything. I thought it would at least make it appear as a text with heading in HTML. So, what is the sense in using @apiDefine prior to @apiPermission? I am a beginner, and I cannot see any difference with or without @apiDefine - both HTMLs look the same to me. Here is a part of the code: class ArticleList(generics.ListAPIView): """ @apiDefine Authenticated user Only logged in users can use this functionality """ """ @api {get} / Retrieve all articles @apiName GetArticles @apiGroup Articles @apiPermission Authenticated user @apiSuccess {Object[]} articles List of articles. @apiSuccess {Number} id ID of the article @apiSuccess {String} author Name of the author @apiSuccess {String} title Title of the article @apiSuccess {String} body Text of the article @apiSuccess {Date} created_at Date when the article was published And the image below shows how the HTML looks like. Thank you! -
How to create APIs for UserProfile with rest framework?
I have created a UserProfile model with OneToOne relationship with User model. The UserProfile model is shown below. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile_number = models.IntegerField(blank=True, unique=True, null=True) profile_image = models.ImageField(upload_to="media", blank=True ) current_location= models.CharField(max_length=300, unique=False, blank=True) created_at = models.DateTimeField("created at", auto_now_add=True) university = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) The serializer class is shown below. from rest_framework import serializers from .models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ( 'mobile_number', 'current_location' ,'university','profile_image') Iam using token authentication. How can I use the ListCreateViewand other classes to implement the post, put ,get and delete method in the best way possible. I also need to validate these data before saving(like mobile_number length should be 10 and mandatory) -
how can I improve my helpers / models to give me true / false instead of returning me invalid token view?
I am trying to fix this error which works as expected, but however at the moment to send the link confirmation link. I notice it never changes, and my update password view it doesn't seem to be created, and it always will display the form I have if not token Invalid. I am not sure a decent way to fix these errors especially the ### helpers from django.contrib.auth import authenticate, login, get_user_model from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.core.mail import EmailMessage def generate_password_reset_token(request, email): try: user = get_user_model().objects.get(email=email) except get_user_model().DoesNotExist: return False get_user_model().objects.filter(email=user).delete() created = get_user_model().objects.create(email=user, token=user.token) email_subject = 'account recovery code' current_site = get_current_site(request) html_message = render_to_string('email/account-recovery.html', { 'domain': current_site.domain, 'token': user.token }) mail = EmailMessage(email_subject, html_message, to=[email]) mail.content_subtype = "html" created = mail.send() if not created: return False return True def verify_password_token(token): try: token = get_user_model().objects.get(token=token) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): token = None if token is not None: return True else: return False views class ResetPassword(View): def get(self, request): return render(request, 'account/forgot-password.html', { 'form': AuthenticationForm }) def post(self, request): form = RequestRestoreCodeForm(request.POST) if form.is_valid(): if generate_password_reset_token(request, form.cleaned_data.get('email')): return JsonResponse({'message': "Please check your registered email for instructions on recovering your account."}) # valid else: return … -
Methods from a single view to different endpoints: keep APIs for HTML and for JSON separated (Django Rest Framework)
Could you help suggesting how to keep coding style organised to keep endpoints from HTML and JSON separated, in Django Rest Framework ? In Flask I am used to keeps endpoints for serving Json, and ones for serving HTML, separated, like: @application.route('/api/') def api_root(): #... return jsonify({'data' : data}) and @application.route('/home/<string:page>/', endpoint='page_template') #... return render_template(template, page) And so I could serve the APIs like: /api/page => serve the json for the page, say for AJAX etc. /page => serve the corresponding html page In Django RF, I read that a ModelViewSet can serve both. So I could keep everything in one place. However, when I come to map views on the router, I would have all the endpoint served respect the path related my model, they would be all sub-path of /api Could you help in advising a good coding practice to make use of ModelViewSet, and route endpoints for html separated from APIs ? This is the example Im working on, my doubts are in comments: from rest_framework import viewsets from rest_framework import generics from rest_framework.decorators import action from rest_framework.response import Response from .serializers import PersonSerializer from .models import Person class PersonViewSet( viewsets.ModelViewSet): queryset = Person.objects.all().order_by('name') serializer_class = PersonSerializer … -
how to execute a user supplied python script on button click django
I have set up a template in django app. It has two inputs (i.e absolute path of python script and argument) and a button. On button click, I want python script supplied by user in input 1 to be executed with input 2 as argument. Output of that script should then be printed to same html page. -
Django receive a signal when a model value gets changed from a different application or when manually edited in database
I'm currently in a peculiar situation where I am not allowed to use a new database even though the product owner wants a new and improved application. This means that my new application will have to work with the old database. This database doesn't use foreign key constraints, which makes the usage of modules such as Django tables 2 nearly impossible. The solution I thought up is the following: Add in an extra foreign key field to required tables Users in the old app change an id of sorts, let's say team id of a news article Django app sees this change, finds the correct team model and links that team model to the foreign key field What I've tried so far to achieve this: Add in a custom save method to my model. This does work when I change the model with a view or CLI, but doesn't do anything when I manually change a value in the database or use a different application to change any values. class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) intra = models.ForeignKey(Intra, on_delete=models.DO_NOTHING) def save(self, force_insert=False, force_update=False): print("test") The next solution I tried is using a receiver. This again works in CLI … -
my profile object is not getting serialized in the user serializer
I am using Django rest auth to authenticate my users, that works well. how my model is set up is that I have the custom user model for authentication and I also have a profile model that gets created with a signal. I want that when the users are fetched in its URL, the profile for that user is also called an object in user. my models.py (I didnt include some models like the user managers, skill, e.t.c as i felt they werent relevant) class User(AbstractBaseUser, PermissionsMixin): username = None email = models.EmailField(max_length=254, unique=True) fullname = models.CharField(max_length=250) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = UserManager() class Profile(models.Model): ''' Note: profile photo is expecting photos link gotten from cloudnairy from the frontend - The height is calculated in feets and inches - Need to sort out location (lives in) - Need to add an age function - Need to add achievemnet as a foreign field - Need to add education also as a foreign field - Add follow functionality ''' user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_of_birth = models.DateField(blank=True, verbose_name="DOB", null=True) bio = models.TextField(max_length=500, blank=True, null=True) … -
Authorization Vk, output a list of friends?
Made authorization Vk with the help django allauth, until that perhaps simply start pressing hard on authorization he will go, but not will display outcome As after authorization see displaying the name of authorized user and 5 any friends user. Also, when Perezhogin to the site authorization does not fly. examples of prompt. -
How to disable 'required' attribute of model's fields only for one form? Django
I have Post model which has such tables as title, body and etc. I want to create form in which this fields won't be required. At the moment, my form looks like this: class CreateUpdatePostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "body"] -
How can I create new 'draft' object with class based UpdateView before form filling?
I have a product model that has a lot of field. When user click to "Create New Product" I want create new object (just create object that it has id, seller, draft status), and show blank form. Because I want to use Ajax asyncronous upload to this object. User fills the object's other fields (like upload images) and save. Also user should be able to edit own draft products on own dashboard. First problem: I used UpdateView, but If I override get_object method and I click "Create New Product", django calls twice this method and create two object?! I want call just one time. Second problem: When users wants to edit draft items, they go to dashboard and edit someone. Should I create new class-based view for this or can I use same view for both operation? Maybe I can add get_or_create method to my get_object method, is It possible? my model: class Product(models.Model): seller = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="Seller", default=None) category = models.ForeignKey("Category", on_delete=models.CASCADE, verbose_name="Category Name", blank=True, null=True) title = models.CharField(max_length=50, verbose_name="Product Title", blank=True, null=True) status = models.IntegerField(choices=((x.value, x.name.title()) for x in Status), default=Status.TASK) images = models.ManyToManyField("ProductImages", blank=True, null=True) my class-based view: class ProductCreateViewTest(LoginRequiredMixin, UpdateView): template_name = 'product/add.html' form_class = … -
modal popup on hyperlink click in hovertext in plotly
i want to open modal dialog on click of hyperlink in hovertext in PLOTLY PYTHON. i had included hyperlink in data from backend, but when i add class or id to it the graph doesn't myPlot.on('plotly_click', function(data){ var eventid = ''; for(var i=0; i < data.points.length; i++) { ClickIndex = data.points[i].pointIndex; eventid = data.points[i].data.DID[ClickIndex]; } if(eventid) { openFormPopup(eventid) } }); i want to run same function on click of a hyperlink in graph. Show Summary is hyperlink Show summary is hyperlink i have send from backend. i want to fire same function which runs on plotly_click. -
How can i generate pdf from html code and pdf file along with sendgrid API V3 uisng python django
i have a variable which contain the template code like template = ''' <html> <div> Hello world </div> </html> ''' i want to generate a pdf and attach file with the sendgrid code below import os from sendgrid import SendGridAPIClient template = ''' <html> <div> Hello world </div> </html> message = { 'personalizations': [ { 'to': [ { 'email': 'test@example.com' } ], 'subject': 'Sending with Twilio SendGrid is Fun' } ], 'from': { 'email': 'test@example.com' }, 'content': [ { 'type': 'text/plain', 'value': template } ] } try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(str(e)) currently i have created a template of invoice and now i want to know how to generate a pdf with that template and attach that pdf file with the email my template code is too lengthy so im not including it here -
Call function when click function django
I want to call my python function, when user clicked button "submit" on this page http://junjob.ru/accounts/login/ How can I do it? My code: views.py class BBLoginView(LoginView): template_name = 'vacancy_list/login.html' class BBLogoutView(LoginRequiredMixin, LogoutView): template_name = 'vacancy_list/vacancy_list.html' next_page = reverse_lazy('vacancy_list') urls.py urlpatterns = [ path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), ... login.html {% block content %} <div class="container" style="margin-top:10px"> <h2>Login</h2> {% if user.is_authenticated %} <p>You are already registered</p> {% else %} <form method="post"> {% csrf_token %} {% bootstrap_form form layout='horizontal' %} <input type="hidden" name="next" value="{{ next }}"> {% buttons submit="Submit" %} {% endbuttons %} </form> {% endif %} </div> {% endblock %} -
Django template rendering HTML elements in the wrong order
This is a Django beginner question (or possibly just an HTML problem). I'm rendering a very simple HTML page with a template (I'll make it look nice later). It has two divs, each containing a header and a table. If I print the rendered content in my view, it looks right, but the HTML delivered to the browser has both headings, then both tables. Template <!doctype html> <html style=\"font-family:Helvetica\> <head> <meta charset="utf-8"> <title>Choir Database</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/choirdb.css' %}"> </head> <body> <!-- MAIN TABLE --> <div> <h1>{{ title1 }}</h1> {% if value_list1 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list1 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> <!-- SECONDARY TABLE --> <div> <h2>{{ title2 }}</h2> {% if value_list2 %} <table style=\"width:25%;font-family:Helvetica\"> <tr/> {% for valuePair in value_list2 %} <tr><td>{{ valuePair.0 }}</td> <td>{{ valuePair.1 }}</td></tr> {% endfor %} <tr> <td><a href=\"..\">Home</a></td> {% else %} <p>No values found</p> {% endif %} </div> </body> </html> View context = { 'title1': 'Liturgy Detail', 'value_list1': nameValuePairsPiece, 'title2': 'Laudate Recommendations', 'value_list2': rec_details, } output = render(request, 'two_tables.html', context) print ("output is " … -
Why my slug related field shows users object(1) instead of suggested field name in Django?
I wrote an app named as credentials. models, serializers and views are : models.py : from django.db import models class Users(models.Model): username = models.CharField(max_length=20, blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('inserted_timestamp',) class UsersDetails(models.Model): user = models.ForeignKey( Users, related_name='id_user_details', on_delete=models.DO_NOTHING, ) user_title = models.CharField(max_length=30, blank=True) user_first_name = models.CharField(max_length=25, blank=True) user_last_name = models.CharField(max_length=40, blank=True) user_birthdate = models.DateField(blank=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) details_creator = models.ForeignKey( Users, related_name='dtlcreator_user_details', on_delete=models.DO_NOTHING, # default=1 ) class Meta: ordering = ('user_id',) class UsersPasswords(models.Model): user = models.ForeignKey( Users, related_name='id_user_password', on_delete=models.DO_NOTHING) salt = models.CharField(max_length=200, blank=True) pwdhash = models.CharField(max_length=200, blank=True) inserted_timestamp = models.DateTimeField(auto_now_add=True) pwd_creator = models.ForeignKey( Users, related_name='pwdcreator_user_details', on_delete=models.DO_NOTHING) class Meta: ordering = ('user_id',) Here is serializers.py : from rest_framework import serializers from credentials.models import Users from credentials.models import UsersDetails from credentials.models import UsersPasswords class UsersSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Users fields = ( 'url', 'pk', 'username', 'inserted_timestamp', ) class UsersDetailsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) details_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username', ) class Meta: model = UsersDetails fields = ( 'url', 'pk', 'user', 'user_title', 'user_first_name', 'user_last_name', 'user_birthdate', 'inserted_timestamp', 'details_creator' ) class UsersPasswordsSerializer(serializers.HyperlinkedModelSerializer): user = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) pwd_creator = serializers.SlugRelatedField( queryset=Users.objects.all(), slug_field='username' ) class Meta: model = UsersPasswords fields = ( 'pk', 'user', 'salt', 'pwdhash', 'inserted_timestamp', 'pwd_creator' ) … -
Django REST framework adding multiple default objects
I am creating an app for my School which lets you add Teachers/Subjects/lessons...basic school life managing app...I want to give the user a list of the most basic/common subjects. I know that you can assign a default value in Django Models... but that would only create one Object with all the subjects in it... Is there a way to create multiple default object when a new user is created ? Thanks in advance django==2.2 djangorestframework==3.9.2 note : the user should be able to edit the subject list later. -
Build Firebase google signin in Django
I am looking to integrate firebase auth google sign in with Django. But I am not getting a clear picture of how can I achieve it. As Pyrebase has an attribute sign_in_with_email_and_password but not any for Google SignIn. How will view and template be designed? -
django: adding custom permissions stopped working
I have a django project with multiple apps. In one of the apps when I add custom permissions to any model and run makemigration, the migration-file to add the permission is created. When I apply the migration I get no error messages but the permission isn't added to the auth_permission table. class Meta: app_label = 'my_app' permissions = ( ('test_perm', 'Testing'), ) I have tried doing the same in other apps and that works. I have also tried adding a column to the current app and that works as well. Anyone got any idea what it could be? I am running django 1.11.26 -
Pycharm identifies new Django test file as a unittest, not a django test
How do I tell pycharm that the new test file I created is a django test file, and not a unittest file? I have pycharm setup with a django project. I can run all django tests as django tests with the test runner. I created a new test file, wrote a simple unittest on it. The tests run fine with manage.py and with the run configuration for running all tests. But, when I try to run an individual test within the new test file from pycharm it fails because pycharm is trying to run it as a unittest instead of a django test. As shown in the screenshots below, pycharm considers this new file a unittest file, not a django test file. Yet both files are in the same directory, both implement a class that extends Unittest, and both have tests. -
display data in html from django
I tried to display the data (the result return back from upload_file in views.py) in HTML from django, but it didn't show anything after clicking submit button, only jump back to the initial ui. undex.html <!DOCTYPE html> <head> <title>Detect Pothole</title> </head> <body> <p>upload image</p> <form method="post" enctype="multipart/form-data">{% csrf_token %} <input type="file" name="img" accept="image/*" onchange="loadFile(event)"></input> <img id="output"/> <script> <!--view selected image --> var loadFile = function(event) { var output = document.getElementById('output'); output.src = URL.createObjectURL(event.target.files[0]); }; </script> <input method='POST' type="Submit" name="submit" value="submut"></input> </form> {% if submitbutton == "Submit" %} {% for res in result %} {{res}} {% endfor %} {% endif %} </body> </html> view.py def upload_file(request): submitbutton= request.POST.get("submit") if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['img']) result=process('a.png') ## will return 0 or 1 print(result) context= {'form': form, 'submitbutton': submitbutton,'result':result} return render(request, 'index.html', context) else: form = UploadFileForm() return render(request, 'ui.html', {'form': form})