Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to connect an android device with adb server using python
Good Day..) I am able to connect android device with adb using USB cable but I want connect remote device with out USB cable and not rooted also. Basically I am running adb command through python. I am googling from 2 days most of the resources says we can't. If it's not please suggest me other resources. Big appreciation for your help.. Thanks -
pythonanywhere: Error code: Unhandled Exception
I am trying to host a website, But got stuck with this error enter image description here. Something went wrong :-( This website is hosted by PythonAnywhere, an online hosting environment. Something went wrong while trying to load it; please try again later. There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception what should be my next step? what can be the mistake for this error ? -
Showing application error after sucessfull deployment in python application
I made a new Python Project in Django, then deployed the application to the Heroku. When I open my application it shows me application error message. My logs don't indicate any errors as far as I can tell, but I'm receiving the following error when loading the site: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command. Below you can find the logs. Am I missing something here? (foodtasker) C:\Users\nikku\Desktop\foodtasker>heroku logs --tail 2021-02-11T10:52:05.964281+00:00 app[api]: Release v1 created by user nkarnwal07 @gmail.com 2021-02-11T10:52:05.964281+00:00 app[api]: Initial release by user nkarnwal07@gm ail.com 2021-02-11T10:52:06.223875+00:00 app[api]: Enable Logplex by user nkarnwal07@gma il.com 2021-02-11T10:52:06.223875+00:00 app[api]: Release v2 created by user nkarnwal07 @gmail.com 2021-02-11T11:10:53.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:11:06.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/96248b6d-f0dc-4016-b9bf-228f21fa2a87 2021-02-11T11:12:31.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:12:45.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/1a7d4064-5c4a-4e6b-a40a-b937ca3b4446 2021-02-11T11:16:22.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com 2021-02-11T11:16:39.000000+00:00 app[api]: Build failed -- check your build outp ut: https://dashboard.heroku.com/apps/8ca09b4c-2b22-4b60-9bef-ea151d6f0ace/activ ity/builds/482acec5-04d8-404e-a5f8-aaeaeba66ab7 2021-02-11T11:18:33.000000+00:00 app[api]: Build started by user nkarnwal07@gmai l.com … -
How to show message given by django admin to the user when he select a value from drop down.?
I know this will be very hard to understand my question. But I have a requirement where I need to show the message added by admin to a specific model(This will be same for all instances from that Model) I can use Ajax call to show the message but for my requirements I need to change the notification whenever I want from admin end instead of changing in code. I used notifix.co to get notifications with End Urls but though I used Ajax call I am unable to implement this on certain page where I cam getting data with Ajax call. Is there any way where I can manage my pop up messages up on clicking a certain model in user end and I can manage the messages in Admin. -
Any ideas on how to fix the django TypeError: expected string or bytes-like object?
I created a form page for staff to add multiple files for each patient (A radiograph image, a CT scan and a medical notes file). It works perfectly when running the website locally but shows a TypeError when it is run from heroku. Could this be related to the fact that the database changed from sqlite locally to postgresql in deployment? Here is part of my models.py code class Radiograph(models.Model): patient = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) image = models.ImageField(null=True, blank=True) ct_scan = models.FileField(null=True, blank=True) medical_notes = models.FileField(null=True, blank=True) Here is forms.py code: class AddRadiograph(forms.ModelForm): class Meta: model = models.Radiograph fields = ['patient', 'image', 'ct_scan', 'medical_notes'] And here is the part of my views.py code: @allowed_users(allowed_roles=['clinics']) def add_radiograph_view(request): if request.method == 'POST': form = forms.AddRadiograph(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('accounts:add_patient') else: form = forms.AddRadiograph() return render(request, 'patientfiles/add_radiograph.html', {'form':form}) The traceback also highlights only form.save() Please take it step by step as I am still new to this language. Any help is much appreciated! -
How to add password to dynamic PDF file in Django
I want my dynamic PDF invoice should generate with random password but when i try to do that it gives me blank invoice PDF file. I have used xhtml2pdf for creating PDF file and PyPDF2 to add password. this my views.py file #For password generation i have created a function def generate_random_password(): MAX_LEN = 12 DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] LOCASE_CHARACTERS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] COMBINED_LIST = DIGITS + LOCASE_CHARACTERS rand_digit = random.choice(DIGITS) rand_lower = random.choice(LOCASE_CHARACTERS) temp_pass = rand_digit + rand_lower for x in range(MAX_LEN - 4): temp_pass = temp_pass + random.choice(COMBINED_LIST) temp_pass_list = array.array('u', temp_pass) random.shuffle(temp_pass_list) password = "" for x in temp_pass_list: password = password + x return password and for creating PDF file i followed this blog https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ and this is how i am trying to add password def generate_invoice(): password = generate_random_password() print('////////password////////',password) data = Booking.objects.get(id=id) name = data.given_name+' '+data.surname email = data.email template = get_template('invoice.html') context = { "data":data } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: filename = "Invoice_%s.pdf" %(data.id) pdf_response = HttpResponse(pdf, content_type='application/pdf') content = "attachment; filename=%s " % (filename) pdf_response['Content-Disposition'] = content receipt_file = BytesIO(pdf.content) fs = File(receipt_file, … -
I'm getting error when i try to admin login using django framework
here is my traceback: 1)response = await sync_to_async(response_for_exception, thread_sensitive=False)(request, exc) return response return inner else: @wraps(get_response) def inner(request): try: response = get_response(request) … except Exception as exc: response = response_for_exception(request, exc) return response return inner ▶ Local vars 2)C:\Users\91807\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 179, in _get_response if response is None: wrapped_callback = self.make_view_atomic(callback) # If it is an asynchronous view, run it in a subthread. if asyncio.iscoroutinefunction(wrapped_callback): wrapped_callback = async_to_sync(wrapped_callback) try: response = wrapped_callback(request, *callback_args, **callback_kwargs) … except Exception as e: response = self.process_exception_by_middleware(e, request) if response is None: raise # Complain if the view returned None (a common error). -
How do i create a field in my model whose value is calculated using values from other fields?
I have a model that takes in 3 integers as part of its fields class TradeBill(models.Model): ...... first = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) second = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) third = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(2)]) ..... What I need to have is another positive integer field called score that adds up the value of the other three. Currently i just have it as this and thus taking care of it in the frontend: score = models.PositiveIntegerField(default= 0, validators=[MaxValueValidator(6)]) But thats not great because i can put any value i want for example from the admin or any front end input i have. Sure i can do frontend validation to stop it from happening but django never let me down when it comes to their features so im sure theres something i can do -
Filter django queryset according to condition on a field?
I have a model like this: class Story(models.Model): version = models.PositiveIntegerField(default=1) # other fields Now I am getting a dict of id: version like: id_ver_dict = { # id ver 23: 2, 24: 1, 25: 3 } I want to filter my queryset according to the given dict such that the version in my DB is greater than the version in the id_ver_dict. How can I filter this in a single query? Is there something like this: Story.objects.filter(id__in=id_ver_dict.keys(), version__gt=id_ver_dict_value) P.S.: I am using MySQL -
my stylesheet and images doesn't work with Jinja2 templates with parameters - Django
I successfully converted my website templates to Jinja2, everything works as it should, except in urls with parameters. I have this is views.py file path("profile/<id>", views.profile), When the template loads in my browser the css and images dont load. But when I remove the parameter and set id manually in the view function everything works. Am I doing anything wrong? -
Django allauth redirect to previous page
I am using Django allauth besides django auth to login users in my webapp. I want to return the users back to current page after logging in or signup when login using allauth. I have gone through some of the answers but none work in my case. Please see my code below: #settings.py ACCOUNT_ADAPTER = 'kvizmaster.adapter.MyAccountAdapter' #adaper.py from django.http import HttpResponseRedirect from django.conf import settings from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): print("in code") redirect_to = request.GET.get('next', '') print(redirect_to) return HttpResponseRedirect(redirect_to) Login URL <a title="Google" class="socialaccount_provider google" style="text-decoration:none;" href="/accounts/google/login/?process=login?next={{request.GET.next}}">Sign in with Google</a> Form Next Variable <input type="" name="next" value="{{ request.GET.next }}"/> The login url has correct href assigned and next variable works on the form. However, I am unable to access the "next" in adapter.py. Please suggest. -
repartition.js:1 Uncaught ReferenceError: Chart is not defined at file.js:1
I am working on a django project and can't load chartjs. I get the following error: repartition.js:1 Uncaught ReferenceError: Chart is not defined at file.js:1 the file that has the problem is: file.js this is the first line: Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif'; I have already loaded chart.js and it is working correctly on my environment. It is loaded on index.html as follow: <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script> Ps. working using django Any suggestions? Thanks. -
Filter django queryset by its related field
I have a DRF QuesionSet View inherited from generics.RetrieveUpdateDestroyAPIView I also have 2 models (simplified): Question(models.Model): question_set = models.ForeignKey(QuestionSet, related_name="questions") is_archived = models.BooleanField(default=False) ...other_fields QuestionSet(models.Model): ...fields Now I need to return a question_set object in the view, that only has questions that are True. Something like this: "id": 1, "questions": [ { "id": 1, "isArchived": true }, { "id": 1, "isArchived": true }, { "id": 1, "isArchived": true }, ] I am trying to override get_object() method in the view to return these values. So how do I achieve that? -
Can't make drf router work in a certain way
router = BulkRouter() router.register(r'', InventoryViewSet, basename='inventory') router.register(r'temporary/items', TemporaryInventoryViewSet, basename='temporary-inventory') this is part of my urls.py file the thing is I want to register route like this r'temporary' but it returns detail: not found in postman. but whenever I request "temporary/pk", I get desired item. The problem is, I can't make route "temporary" list all the objects. ('temporary/items' list all objects just fine, and 'temporary/items/pk' works great as well) I wonder what should I change to get the desired output -
Pagination button not highlighting the current page
So I'm trying to make a button which highlights as active when the page is the same as page number, but it does not work, It only highlights page 1, When I go to page 2 then page 1 is still highlighed, index function handles the page I'm talking about. views.py from django.shortcuts import render from .models import Listing from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator # Create your views here. def index(request): listings = Listing.objects.all() paginator = Paginator(listings, 3) page = request.GET.get('page') paged_listings = paginator.get_page(page) params = {'listings':paged_listings} return render(request, 'listings/listings.html', params) def listing(request, listing_id): return render(request, 'listings/listing.html') def search(request): return render(request, 'listings/search.html') listings.html {% extends 'base.html' %} {% block content %} {% load humanize %} <!-- Breadcrumb --> <section id="bc" class="mt-3"> <div class="container"> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="{% url 'index' %}"> <i class="fas fa-home"></i> Home</a> </li> <li class="breadcrumb-item active"> Browse Listings</li> </ol> </nav> </div> </section> <!-- Listings --> <section id="listings" class="py-4"> <div class="container"> <div class="row"> {% if listings %} {% for listing in listings %} <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ listing.photo_main.url }}" alt=""> <div class="card-img-overlay"> <h2> <span class="badge badge-secondary text-white">${{ listing.price | intcomma}}</span> </h2> </div> <div class="card-body"> <div class="listing-heading text-center"> <h4 … -
Heroku Build succeeded but "application error" {Django app}
heroku log: 2021-02-11T09:33:17.289297+00:00 app[web.1]: ModuleNotFoundError: No module named 'ivytasks' 2021-02-11T09:33:17.289983+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-02-11T09:33:17.306006+00:00 heroku[web.1]: State changed from starting to up 2021-02-11T09:33:17.429342+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Shutting down: Master 2021-02-11T09:33:17.429457+00:00 app[web.1]: [2021-02-11 09:33:17 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-02-11T09:33:17.511921+00:00 heroku[web.1]: Process exited with status 3 2021-02-11T09:33:17.647676+00:00 heroku[web.1]: State changed from up to crashed 2021-02-11T09:33:18.929260+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ivytasks.herokuapp.com request_id=1d65f0f2-d28b-4f75-a02b-3f55c4d2ae2a fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https 2021-02-11T09:33:19.373547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ivytasks.herokuapp.com request_id=36c5d48e-3181-4cf0-9f55-655dad447156 fwd="154.97.8.251" dyno= connect= service= status=503 bytes= protocol=https you can check the project repo link: github.com/osamamhd/ivyTasks -
Django queryset regex filter gives (3692, 'Incorrect description of a {min,max} interval)
Using Django 2.2 and MySQL database. I have a field (info) in the table containing stringified JSON data. I want to filter the data matching the regular expression. The example data in the info field is [{"type":"button","data":{"link":"https://example.com","label":"Click Here","tracking":{"id":"E3s06x","tag":"btn1"}}}] Where I want to match the expression "tracking":{"id":"(\S+)","tag":"(\S+)"} I tried using the regex filter in the Django ORM query = query.filter( info__iregex=r'"tracking":{"id":"(\S+)","tag":"(\S+)"}' ) But it is giving an error django.db.utils.OperationalError: (3692, 'Incorrect description of a {min,max} interval.') -
How to find the class index of a clicked element using javascript?
I have a tab-based website where tabs are created dynamically by cloning the default tab view, however, without knowing the index number of each element there is no way to perform logic on each tab. function search(){ window.addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); alert(click) var input = document.getElementsByClassName("myTextInputID")[click].value; if (input.includes("https://www.amazon.co.uk/")) { document.getElementsByClassName("prodcont")[click].style.display = "block" document.getElementsByClassName("imgcont")[click].innerHTML = '<img class="image" src="https://www.needforseat.de/media/image/22/15/b3/MAXNOMIC-R-_LVL_Edition_Pro_YkaFLtIVOgbL1_320x463.jpg">'; document.getElementsByClassName("h1")[click].innerHTML = prodName; document.getElementsByClassName("containFORM")[click].style.backgroundColor = "white" } else { URLerror.appendChild(urlerror); var cont = document.getElementsByClassName("containFORM")[click]; cont.insertAdjacentElement("afterend", URLerror); setTimeout(function() { URLerror.remove(); }, 2000); } } }); } The only solution I've managed to come up with is by iterating through all the classes and givingibng them a name that matches their class number then whenever the tab button is clicked it returns its name. However this only works for the first 2 tabs and only goes up to an index number of one however when I add an alert for the value of clicked it shows the right value but the code runs on class index [1] which is very confusing. <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" id="default" onclick="openPage('0', this, 'red'); buttonOnclick(this.name);"></button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center">+</button> </li> </ul> </ul> </div> … -
Django-smart-select with a through model on manytomany field
I am trying to implement django-smart-selects but my situation is not covered in the Docs. They cover two scenarios - those being class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ForeignKey**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) and class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent) name = models.CharField(max_length=255) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) However, my scenario looks like this - there is an additional through model; class Continent(models.Model): name = models.CharField(max_length=255) class Country(models.Model): continent = models.**ManyToMany**(Continent, through='CountryToContinent") name = models.CharField(max_length=255) class CountryToContinent(models.Model): continent = models.ForeignKey(Continent) name = models.ForeignKey(Country) class Location(models.Model): continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) city = models.CharField(max_length=50) street = models.CharField(max_length=100) in django admin I have registered the Location model and I have a tabular inline with continent and country fields but as there is the through model, the chained select does not work. Any guidance or hint would be appreciated. -
Django set auto-user from context, user field not be null, JWT
In my case,I use JWT authentication, and when I create new "Post"(my model), I want automatically set author to user that request it.But when I do it, I got an error { "author": [ "This field is required." ] } I know,I'm not passing user, but I want to set it automatically, and I dont know how. I just want to know how to avoid error, because when I pass value, that allows me to go ahead, the user is set automatically from context. Serializer class PostSerializer(FlexFieldsModelSerializer): class Meta: model = Post fields = ('title','content',author','category','likedBy') expandable_fields = { 'category': ('blogApi.CategorySerializer', {'many': True}), 'comments': ('blogApi.CommentSerializer', {'many': True}), 'likedBy': ('blogApi.LikedBySerializer', {'many': True}), } def create(self, validated_data): user = self.context['request'].user post = Post.objects.create( author=user, title=validated_data['title'], content=validated_data['content']) post.category.set(validated_data['category']) return post My create view class PostCreate(generics.CreateAPIView): queryset = Post.objects.all() serializer_class = PostSerializer permission_classes = [IsAuthenticated] Model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() category = models.ManyToManyField(Category, related_name='posts') author = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) likedBy = models.ManyToManyField(User, related_name='posts', blank=True) class Meta: ordering = ['-created'] def __str__(self): return self.title and when I create -
Related_name is returning an attribute error (NoneType) from a Django Forms. I'm trying to create a dynamic filter within forms
I'm using Django 3.1.4 with Python 3.7.8. I wanted to have form field for my ProductForm to automatically filter Category and Subcategory. I followed the suggest from https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. However I keep getting an AttributeError, saying NoneType object has no attribute list. I used Django shell to see if my related_name would work. It the error keeps popping up. Here is my models.py: class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField( default=slugify(name), unique=True ) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="list_of_subcategories" ) class Meta: verbose_name = 'Subcategory' verbose_name_plural = 'Subcategories' def __str__(self): return self.name Here is my forms.py: class ProductForm(ModelForm): class Meta: model = Product fields = [ 'sku', 'name', 'category', 'subcategory', 'short_description', 'description', 'price', ] def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['subcategory'].queryset = SubCategory.objects.none() if 'category' in self.data: try: category_id = int(self.data.get('category')) self.fields('subcategory').queryset = Category.objects.filter(category_id=category_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['category'].queryset = self.instance.category.list_of_subcategories.order_by('name') Here is my views.py: def loadSubcategory(request): category_id = request.GET.get('category') subcategories = SubCategory.objects.filter(category_id=category_id).order_by('name') return render(request, 'product/subcategory_drop_down.html', {'subcategories': subcategories}) def createProduct(request): if request.method == "POST": form = ProductForm(request.POST) if form.is_valid(): product_form = form.save(commit=False) product_form.company = request.user.company product_form.save() return redirect('dashboard:my_store') else: product_form = ProductForm() … -
Is it possible to deploy django + react app on digitalocean app platform?
I deployed my django app using digitalocean app platform(guide). I used js/jquery. And now I want to refactor my code and start using React. Is it possible to deploy django + react using app platform? -
django imagekit processors: changing Spec dependind on image dimensions
I want to generate thumbnails, whose bigger dimension is, say, 150px. Something like this: #models.py picture = models.ImageField(verbose_name=_('Image'), upload_to = "images") if image.width > image.height: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**width**=150)], format='JPEG', options={'quality': 100}) else: picture_thumbnail = ImageSpecField(source='picture', processors=[ResizeToFit(**height**=150)], format='JPEG', options={'quality': 100}) Please give me an advice how to do it in django and imagekit (or, at least, other image processing package). Think that I need somehow get image field properties in my model... -
I want to change the default model of Token. I have added authentication.py file and while importing that on settings.py it shows an import error
ImportError: Could not import 'Token.custom_token.authentication.MyOwnTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'Token.custom_token'. Project Name: Token App name: custom_token Inside app-> authenticate.py file from .models import MyOwnToken class MyOwnTokenAuthentication(TokenAuthentication): model = MyOwnToken In settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'project_name.app_name.authentication.MyOwnTokenAuthentication', ] } In models.py class Organisation_User(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) organisation_id = models.CharField(max_length=10) organisation_name = models.CharField(max_length = 20) class MyOwnToken(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) organisation = models.OneToOneField( Organisation_User, related_name='auth_token', on_delete=models.CASCADE, verbose_name="Organisation_User" ) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(MyOwnToken, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key -
continue next codes after end of "if", no loop or while here
I have some codes about profile edit in Django views.py def account_edit(request): if not request.user.is_authenticated or request.user.is_staff or request.user.is_superuser: return redirect("/account/login") elif request.method == "POST": new_username = request.POST['username'] new_email = request.POST['email'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] phone_number = request.POST['phone_number'] location = request.POST['location'] if not new_username == request.user.username: if User.objects.filter(username=new_username).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.username = new_username user_edit.save() ctx = {'message_good':'aaa'} elif not new_email == request.user.email: if User.objects.filter(email=new_email).exists(): ctx = {'message_bad':'aaa'} else: username = request.user user_edit = get_object_or_404(User, username=username) user_edit.email = new_email user_edit.save() ctx = {'message_good':'aaa'} else: ctx = {} else: username = request.user user = get_object_or_404(User, username=username) ctx = {'user':user} return render(request, "account/account_edit.html", ctx) But after user_edit.username = new_username user_edit.save() Codes become stop, I want after finishing first if, Codes continue to work and save others