Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render the options in a select of a Django form?
I would like to render two selects with Django (one multiple select, the other a simple one) and customize it with Materialize. I manage to code the following: In my forms.py class ZonesForm(forms.Form): zones_options = ( (1, 'Zone 1'), (2, 'Zone 2'), (3, 'Zone 3'), (4, 'Zone 4') ) zones = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=zones_options) conn_options = ( (1, 'ABCDE'), (2, 'FGHIJ'), ) connections = forms.ChoiceField(choices=conn_options) In my zones.html {% block content %} <div class="container"> <div class="row"> <form method="post"> <div class="input-field col s6"> <select multiple name="{{ form.zones.name }}"> {% for opt in form.zones %} <option value="{{ opt.id }}">{{ opt.label }}</option> {% endfor %} </select> <label>Zones</label> </div> <div class="input-field col s6"> <select name="form.connections.name"> {% for opt in form.connections %} <option value="{{ opt.id }}">{{ opt }}</option> {% endfor %} </select> <label>Connection</label> </div> </form> </div> </div> {% endblock %} My problem is: when the page is rendered, I get 4 checkboxes for the first select (as expected), and no names for it (all options are blank). For the second select I get 4 options (one blank, one with 'ABCDE', one blank, one with 'FGHIJ'). I suspect that the problem is with the attributes. I am not getting the right values for them (I have tried … -
Django Gmail API send EMails
Im already using Gmail API for login in my Django project. Im using social-auth-app-django 2.1.0 SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'XXXXXX.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XXXXXXX' now I want to extend this and also send emails via the Gmail API. This means that the sender of the email is the user's own email and not the one from the project page. I've been looking at the reference here. https://developers.google.com/api-client-library/python/guide/django But it doesn't seem to be up-to-date, already the modules CredentialsField and FlowField can't be imported. So my question is, is it possible to integrate this directly via social-auth-app-django as described? If so, how could this be implemented? Unfortunately I didn't find anything suitable on the internet how I could realize it in Django. Im using Django 2.1.3 on Python 2.5.4 -
How to merge the result of two queries using update
I have to show the name of the category and the quantity of items in each category. The items can change the category, so I save the history of the items in the table items_history To show all the category name I'm running this query: category_total = Category.objects.all() Example of result: <QuerySet [<Category: Drink>, <Category: Food>, <Category: Fun>, <Category: Suplies>]> To get the quantity of items in each category, I have to check in the table items_history: items_history = Category.objects.filter(items_history__current=1).annotate(qtd=Count("items_history__idea_id")) Example of result: <QuerySet [<Category: Food>]> items_history[0].name -> 'Food' items_history[0].qtd -> 5 In this case, I have only items in Food Category. So I can't do just one query in items_history, because I'm not gonna get the quantity of the items in the other categories (0, in this case). I need to get all the categories with their respective quantity, so if a category is not persisted in items_history I should get the category name and the quantity = 0. The result expected: items_history[0].name -> 'Drink' items_history[0].qtd -> 0 items_history[1].name -> 'Food' items_history[1].qtd -> 5 items_history[1].name -> 'Fun' items_history[1].qtd -> 0 items_history[1].name -> 'Suplies' items_history[1].qtd -> 0 I'm trying to use update to merge the result of category_total and items_history … -
registered router url returns 404
I'm using django and rest-framework to develop a website. I have a users app in which the models are shown below: class User(AbstractUser): pass class Comment(models.Model): comment_text = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,default=DefaultUser,on_delete=models.SET_DEFAULT,related_name='author') # DefaultUser is similar to AnonymousUser in django.contrib.aut.models date = models.DateTimeField(default=now) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) so it's basically a comment system where a user can comment on another user. I've used a rest framework serializer for posting comments: class User_CommentSerilizer(serializers.ModelSerializer): comment = User_Comment class Meta: model = User_Comment fields = ('comment_text','on_user') # extra_kwargs = {'password': {'write-only': True}} def create(self, validated_data): comment = User_Comment( author= User.objects.filter(username=self.context['request'].user)[0], on_user= User.objects.filter(username=validated_data["on_user"])[0], validated=False, comment_text= validated_data["comment_text"] ) comment.save() return comment and then using a UserCommentViewSet in views.py: class User_CommentViewSet(viewsets.ViewSet): serializer_class = User_CommentSerilizer queryset = User_Comment.objects.all() and finally in the urls file I've registered the view: router = DefaultRouter() router.register('profile' , views.UserViewSet) router.register('comment' , views.User_CommentViewSet) router.register('login' ,views.LoginViewSet, base_name='login') urlpatterns = [ # path('', views.GetUser.as_view()), path('users/', include(router.urls)), ] the profile and login routers are working fine. however the comment router is not showing at all (and returns 404) without raising any other error. I can't figure out what the problem is Although I did find out that it has something … -
django-compressor CACHE folders are empty when CACHES is set to MemcachedCache
I have the following installed on my project Django==2.1.4 django-compressor==2.1 python-memcached==1.59 with the following settings COMPRESS_ENABLED = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 3600, } } With this configuration, all css and js files are not loaded due to 404 errors. When I check the static folders, CACHE/css and CACHE/js are empty. This is a project that was upgraded from a lower django version. It was working with the same settings prior to upgrade. Previous working version: Django==1.8.4 django-compressor==1.5 python-memcached==1.57 Am I missing some configuration? -
Error moving SQL query from Postgres to MariaDB
This is part of a query which works fine in PostgreSQL (in a Django app): CASE WHEN abc.name = 'foo bar' AND user.first_login <= (now() - interval '{new_user_interval} day') THEN 0 ELSE COALESCE(abc.rank, 0) END AS interesting_value, However, when I try to run it in a MariaDB database, I get this error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') THEN 0\n ELSE COALESCE(abc.rank, 0)\n END AS interesti' at line 13" It seems to follow the MySQL case operator syntax fine. Why is this error occurring? -
RuntimeWarning for DateField in Django
Hello i'm using dates for search queries. But i am getting runtime error. RuntimeWarning: DateTimeField Jobs.job_created_on received a naive datetime (2019-01-17 00:00:00) while time zone support is active. Views.py class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) if 'status' in request.GET: form = JobSearchForm(request.GET) if form.is_valid(): status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] company = self.request.user.userprofile.user_company lookups = (Q(job_company=self.request.user.userprofile.user_company) ) if start_date: lookups = lookups | Q(job_created_on__gte=start_date) if end_date: lookups = lookups | Q(job_created_on__lte=end_date) jobs=Jobs.objects.exclude(job_is_deleted = True).filter(lookups) else: form = JobSearchForm() company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) return render(request, self.template_name, {'form': form, 'jobs': jobs}) Forms.py ACTIVE_CHOICES = ( ('AllStatus', 'Select Status'), ('Active', 'Active'), ('InActive', 'Inactive'), ) class JobSearchForm(forms.Form): start_date = forms.DateField(label=False) end_date = forms.DateField(label=False) status = forms.ChoiceField(choices=ACTIVE_CHOICES, label=False, initial="") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['placeholder'] = 'Start Date' self.fields['end_date'].widget.attrs['placeholder'] = 'End Date' # self.fields['status'].initial = 'Select Status' self.fields['start_date'].widget.attrs['class'] = 'job_date' self.fields['end_date'].widget.attrs['class'] = 'job_date' self.fields['start_date'].required=False self.fields['end_date'].required=False Template.html <form action="" method="GET" id="searchForm"> {% crispy form %} </form> -
edit django form with instance always loads with empty form fields
models.py class summary_model(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) summary=models.TextField(unique=False, blank=False, null=False) numberofprojects=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofinternships=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofjobs=models.CharField(max_length=264, unique=False, blank=False, null=False) def __str__(self): return str(self.username) forms.py class summary_form(forms.ModelForm): #fields from model class Meta: model = summary_model fields = ('summary','numberofprojects','numberofinternships','numberofjobs') views.py def summaryview(request): username=request.user if request.method == 'GET': try: summaryform=summary_form(request.GET or None,instance=summary_model.objects.get(username=username)) print(summaryform) except: summaryform=summary_form(request.GET or None) elif request.method == 'POST': form4=summary_form(request.POST or None,instance=summary_model.objects.get(username=username)) if form4.is_valid(): summary_obj = form4.save(commit=False) summary_obj.username = request.user summary_obj.save() return redirect('#anotherview') else: summaryform=summary_form(instance =summary_model.objects.get(username =username)) return render(request,'app/summary.html',{'summaryform':summary_form,}) template/summary.html {% block content %} <form action="" method="post" novalidate> {% csrf_token %} {{ summaryform.non_field_errors }} <div class="row form-row bg-white has-shadow"> <div class="col-12"> <span class="labelspan">{{ summaryform.summary.label }}</span> {{ summaryform.summary.errors }} <span class="inputfieldspan">{{ summaryform.summary}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofprojects.label }}</span> {{ summaryform.numberofprojects.errors }} <span class="inputfieldspan">{{ summaryform.numberofprojects}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofinternships.label }}</span> {{ summaryform.numberofinternships.errors }} <span class="inputfieldspan">{{ summaryform.numberofinternships}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofjobs.label }}</span> {{ summaryform.numberofjobs.errors }} <span class="inputfieldspan">{{ summaryform.numberofjobs}}</span> </div> </div> {{ summaryform.message.help_text }} <button type="submit" class="btn3">Save and Continue</button></form> {% endblock %} i need to take input in summary form and allow user to edit using the same view.when i save the filled data its updating but the main issue is its not populating data in the … -
get_context_data function doesn't return the 'form'
I have the following Django code (django version 1.11) of a form: class MyDocumentUpdateView(UpdateView): """ We extend UpdateView as we need to pass self.object in context as resource """ model = MyDocument def get_context_data(self, **context): context[self.context_object_name] = self.object context['resource'] = self.object #context['form'] = self.get_form() <-- if I uncomment this it works return context class DocumentUpdateView(MyDocumentUpdateView): form_class = MyDocumentForm def form_valid(self, form): doc = form.save(commit=False) doc.owner = self.request.user updateMyDocument(doc, form) return HttpResponseRedirect( reverse( 'mydocs_detail', args=( self.object.slug, ))) When I run this code, I get an error: 'str' object has no attribute 'fields' I realized that this error related with the return of the context variable. For some reason the context dictionary does not include the 'form'. As indicated in the documentation: get_context_data(**kwargs)¶ Calls get_form() and adds the result to the context data with the name ‘form’. But in my case the context dictionary does not include the 'form'. If I use the get_form() def, then everything works: context['form'] = self.get_form() But this seems like an overkill to me and I want to dig deeper on why this doesn't work. Then I have noticed that in my case I use: def get_context_data(self, **context): instead of: def get_context_data(self, **kwargs): So I defined the … -
mail_admin in Django + Apache2 = wsgi:error <3
I use mail_admin in my Django site but whan I call this in view all is good without that message come no, and this error in error.log of apache2 My view: def order(request): name = request.POST.get('name', '') telephone = request.POST.get('telephone', '') mail = request.POST.get('email', '') date = timezone.now() if name and telephone and mail: try: mail_admins( 'Product', '"New client '+name+' with phone: '+telephone+' and email: '+mail+' ...blah blah blah "', ['<I'm>@gmail.com', '<some>@gmail.com'],) except BadHeaderError: return HttpResponse('Invalid header found.') user = SmartLightUser(SmartLightUser_name=name, telephone=telephone, mail=mail, ord_date=date) user.save(); return HttpResponseRedirect(reverse('SmartLight:ordered', args=())) else: return HttpResponse('Make sure all fields are entered and valid.') apache2 error.log: [Thu Jan 17 14:32:53.511971 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Type: text/plain; charset="utf-8" [Thu Jan 17 14:32:53.512078 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] MIME-Version: 1.0 [Thu Jan 17 14:32:53.512094 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Transfer-Encoding: 8bit [Thu Jan 17 14:32:53.512110 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Subject: =?utf-8?b?W0RqYW5nb10gRml4ZSBNYXQg0LfQsNC80L7QstC70LXQvdC90Y8=?= [Thu Jan 17 14:32:53.512124 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] From: <site>@gmail.com [Thu Jan 17 14:32:53.512138 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] To: <i'm>@gmail.com [Thu Jan 17 14:32:53.512151 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Date: Thu, 17 Jan 2019 12:32:53 -0000 [Thu Jan 17 … -
Python web service for controlling TCP server
What is the best way to create a web API, that would be able to control TCP server? I've tried to do it the following way: import socket from flask import Flask # tcp server TCP_IP = '0.0.0.0' TCP_PORT = 5001 BUFFER_SIZE = 20 app = Flask(__name__) light_on = False @app.before_first_request def launchServer(): global light_on s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) CONN, addr = s.accept() while light_on: data = CONN.recv(1024) # SOME LOGIC HERE CONN.shutdown(socket.SHUT_RDWR) CONN.close() @app.route('/start') def start(): print('starting') global light_on light_on = True launchServer() return "Started" @app.route('/stop') def stop(): global light_on light_on = False return "Stopped" if __name__ == "__main__": app.run(host='0.0.0.0', debug=True, port=5000, use_reloader=False) Also, I've packed this app in docker file, and unfortunately I'm not even able to use /start handler. What is the proper/best way to create such web service (Flask is no strict requirement, I can use any python framework)? Service must be able to start, stop, send data back to TCP connection controlled by endpoints. -
Django Unittest that form field is required
I'm am trying to test the form fields have or don't have the required attribute, but I don't know where to find it. This is what I have tried: form.fields[field].widget.attrs['required'] But I get this error: form.fields[field].widget.attrs['required'] KeyError: 'required' -
Python/Django random DB query results due to "Default argument value is mutable" in method
I encountered a bug in my Django app yesterday and even though I fixed it since, I still do not understand its cause, neither how I resolved it. Well, actually I found the root cause while writing this question, thanks to SO "Questions with similar titles" feature. See "Least Astonishment" and the Mutable Default Argument Buuut, I still don't understand how could that affect my app in the way it affected it. So, let's dig in. I have a web page, which display a list of items. I query those items through the Model.get method, from the views.py file. Nothing out of the ordinary, basically fetching the DB from the model, calling the model from the view and providing a variable with the fetched values to the template. When using the faulty source code, I would refresh the page and the items would randomly either appear, or disappear. I figured the DB query would either return the items, or return an empty list. Here is the faulty source code (model.py): @classmethod def get(cls, school=None, additional_filters={}): if school: additional_filters['school'] = school return MyModel.objects.filter( **additional_filters ) And here is how I fixed it: @classmethod def get(cls, school=None, additional_filters=None): if not additional_filters: additional_filters … -
List index out of range error for loop on Json
I'm trying to request a json object and run through the object with a for loop and take out the data I need and save it to a model in django. I only want the first two attributes of runner_1_name and runner_2_name but in my json object the amount or runners varies inside each list. I keep getting list index out of range error. I have tried to use try and accept but when I try save to the model it's showing my save variables is referenced before assignment What's the best way of ignoring list index out or range error or fixing the list so the indexes are correct? I also want the code to run really fast as I will using this function as a background task to poll every two seconds. @shared_task() def mb_get_events(): mb = APIClient('username' , 'pass') tennis_events = mb.market_data.get_events(sport_ids= [9],states=MarketStates.All, per_page=200, offset=0, include_event_participants=Boolean.T, category_ids=None, price_depth=3, side=Side.All) for data in tennis_events: id = data['id'] event_name = data['name'] sport_id = data['sport-id'] start_time = data['start'] is_ip = data['in-running-flag'] par = data['event-participants'] event_id = par[0]['event-id'] cat_id = data['meta-tags'][0]['id'] cat_name = data['meta-tags'][0]['name'] cat_type = data['meta-tags'][0]['type'] url_name = data['meta-tags'][0]['type'] try: runner_1_name = data['markets'][0]['runners'][0]['name'] except IndexError: pass try: runner_2_name = data['markets'][0]['runners'][1]['name'] … -
Not able to load image in by using .html(text) method of jQuery in django/ChatterBot example
ChatterBot Training data set image_data.yml: categories: - myown conversations: - - Marazzo booking report random test one? - <img src="{% static 'img/Book.png' %}" height="50" width="50"> jQuery code: function createRow(text) { var $row = $('<li class="list-group-item"></li>'); $row.empty().html(text); $chatlog.append($row); } app.html: {% load staticfiles %} //on top of file ... .. ... <ul class="list-group chat-log js-chat-log"> </ul> Error: GET http://127.0.0.1:8000/%7B%%20static%20'img/Book.png'%20%%7D 404 (Not Found) Problem is, it is not considering {% load staticfiles %}. That's why it's not rendering my image. Can any one help me in this? Note: I have also tried to give complete local path, for that it is giving not allowed to load local resource error in chrome console. -
Conditional Django Query
I am using this query for search. I want to search list according to status, start_date and end_date status can be Active, Inactive, or AllStatus. start_date can be date or None(can be empty) end_date can be date or None(can be empty) status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] I made this below query but it is giving me error - Cannot use None as a query value. Can any tell me whats the problem and how should i query using status, start_date and end_date with sometimes value as None Jobs.objects.filter( Q(job_company=self.request.user.userprofile.user_company) | Q(job_created_on__range=[start_date, end_date]) | Q(job_created_on__gt=start_date) | Q(job_created_on__lt=end_date) | Q(job_status=status) ) -
How do I send an email that the password has been changed after password reset is done?
I'm using django 2.1 the default password reset according to documentation https://docs.djangoproject.com/en/2.1/topics/auth/default/ and I need after password reset is completed and the password is updated successfully to send the user an email that he has updated his password successfully How can I achieve that ? -
Bulk update with JSONField in Django
whens = [When(pk=x, then=_json['info'][str(x)]) for x in ids] Clinics.objects.filter(pk__in=ids).update( info_json=Case(*whens, output_field=JSONField()) ) I want to perform bulk update using Case-When statements for JSONField(). When I do this in a stupid cycle with save() on every iteration everithing works fine. But code above writes me:django.db.utils.ProgrammingError: can't adapt type 'dict' saying about second line. I also tried json.loads(), but it didn't work out. What should I do to perform this multiple update? I am using Python 3.6.3 and Django 1.11.16 -
Could not display the updated model using modelForm in django
I am new to django. I am having trouble in displaying some updated data from django model to the html file. I have a delete and add button in the html which will add or remove records to django model. When I click on delete, at the beginning it displays all the records and I can delete the record. Second time when I click, I am getting the previously deleted item also in the list. How can I remove it? I only wanted to display the current items from the model using modelForm. Following is my files: form.py class deleteFileChannelForm(forms.ModelForm): curChannels = getAllChannel('file') j = 0 channelList = [] for item in curChannels: tempTuple = (j, item) channelList.insert(j, tempTuple) j += 1 DeleteChannelName = forms.ChoiceField(widget=forms.Select(attrs={ 'class': 'form-control', }), choices=channelList) class Meta: model = deleteFileChannel fields = ('DeleteFileChannelName',) model.py class deleteFileChannel(models.Model): owaDeleteFileChannelName = models.CharField(max_length=25) def __str__(self): return self.owaDeleteFileChannelName view.py if request.method == "POST": deleteForm = deleteFileChannelForm(request.POST) if deleteForm.is_valid(): data = request.POST.copy() deleteChannelid = int(data.get('DeleteFileChannelName')) deleteChannelName = channelList[deleteChannelid][1] FileChannel.objects.get(FileChannelName=deleteChannelName).delete() return HttpResponseRedirect(reverse('fileChannel', )) else: print("Invalid form") else: formEditChannel = deleteFileChannelForm() return render(request, 'Channels/fileChannel.html',{'formAdd':formAddChannel,'formDelete': formEditChannel, 'channels':allFileChannel}) html file <div class="modal-body"> <form method="post" > {% csrf_token %} <div class="form-group"> <h5>Select channel to delete.</h5> {{formDelete.DeleteFileChannelName}} </div> … -
Django admin restrict access to list view
Here is a model: class Person(models.Model): name= models.CharField(max_length=100, blank=True) identity_number= models.IntegerField(unique=True) name field should be public, identity_number, however, should be confidential. I would like to show name in admin list view and both fields in change form view. I would like to create one group of users, who can access only list view and another group of users, who can access both views. This means that the first group of users should not see links to change form and if they try to access the change form page directly, 403 (or something like that) should be returned. How to achieve this? -
How to send null for Integerfield from form in DRF
I have a simple model: class TestRentalObject(models.Model): some_field = models.TextField() build_year = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MinValueValidator(1300), MaxValueValidator(2100)], ) with ModelSerializer: class TestRentObjectSerializer(serializers.ModelSerializer): class Meta: model = TestRentalObject fields = ( "some_field", "build_year" ) And here is input field from form: <input type="number" class="input-group__input input-group__input_no-require is-invalid" id="field-rent.build_year" placeholder="" name="rent.build_year"> When I keep this field empty, serializer sees it as invalid. In [8]: data = {'some_field': 'some_text', 'build_year': ''} In [9]: rs = TestRentObjectSerializer(data=data) In [10]: rs.is_valid() Out[10]: False In [11]: rs.errors Out[11]: {'build_year': [ErrorDetail(string='A valid integer is required.', code='invalid')]} I believe the problem is that I get build_year as an empty string and not None. But how to do it correctly? -
Django MIGRATION_MODULES in cookiecutter-django
I have been playing a bit with cookiecutter-django and I'm confused about something: They set MIGARATION_MODULES in settings as follows: MIGRATION_MODULES = { 'sites': 'my_awesome_project.contrib.sites.migrations' } and that module contains 3 migrations: 0001_initial.py 0002_alter_domain_unique.py 0003_set_site_domain_and_name.py Those first two are copies of the original Django Sites package, and the third one updates the db with the domain name of the project (as described here). This all makes sense. But what happens if The-Powers-That-Be make another migration in Django Sites? Presumably it would be dependant on migration 0002 as well, leading to a conflict. Would it even get read, given that the MIGRATION_MODULE for 'sites' no longer checks that original module? Just curious. -
Why didn't save Image from SignUpForm to Profile? Django 2.1.5
Faced the following problem. I create form for registration SignUpForm and Profile model. After rigistration image not save in db "Profiles". But if to upload image from admin-panel, it is save. Maybe, error in views.py? How fix it? settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') MEDIA_URL = '/media/' TEMPLATES = [ ... 'context_processors': [ ... 'django.template.context_processors.media' ]}}] urls.py ... + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Profile(models.Model): ... avatar = models.ImageField(upload_to='upload_location', verbose_name="Аватар", default='') ... forms.py class SignupForm(UserCreationForm): ... avatar = forms.ImageField(label='Аватар', required=False) ... views.py def signup(request): if request.method == 'POST': form = SignupForm(request.POST, request.FILES) if form.is_valid(): ... avatar = form.cleaned_data.get('avatar') ... user = form.save(commit=False) user.is_active = False user.save() profile = user.profile ... profile.avatar = avatar profile.save() current_site = get_current_site(request) mail_subject = 'Activate your blog account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return … -
Django migrate two databases, but one database in mysql was deleted?
There are two database setted in my Django project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'default_db', ... }, }, 'crm': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'crm_db', ... } } And I want to migrate my app ad_management's models into default_db: app structure: ├── ad_management ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tasks.py ├── tests.py ├── urls.py ├── utils models: from django.db import models class Name(models.Model): name = models.CharField(max_length=32) class Meta: managed = True Then I just run python manage.py makemigrations ad_management and python manage.py migrate ad_management, but the db crm_db was deleted as the default db django operating was my default_db. can anyone help me out of this confusion, thanks. -
what happens when we use on_delete=models.CASCADE in django
what happens when we use "on_delete=models.CASCADE" in django models class HospitalStay(models.Model): patient = models.ForeignKey(User, on_delete = models.CASCADE)