Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - multiple url params with included template
I'm trying to include an template and utilize it in two different views, where the first one gets one url param and the second gets the same plus another one. Inside my included template there is an iteration with a {% url %} tag that I need to pass both params, since the second view needs them, but doing this causes NoReverseMatch when trying to render my first view, probably because it only accepts one param. Is there any way to specifying the second param is optional? Here is my code: urls.py ... url(r'^portfolio/(?P<category_slug>[-\w]+)/$', views.category, name='category'), url(r'^portfolio/(?P<category_slug>[-\w]+)/(?P<album_slug>[-\w]+)/$', views.album, name='album'), ... models.py ... class Album(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) description = models.CharField(max_length=200, blank=True) posts = models.ManyToManyField(Post, blank=True) slug = models.SlugField(max_length=200) class Category(models.Model): cover = models.ImageField() title = models.CharField(max_length=200, unique=True) albums = models.ManyToManyField(Album, blank=True) slug = models.SlugField(max_length=200) @receiver(pre_save, sender=Album) @receiver(pre_save, sender=Category) def save_slug(sender, instance, *args, **kwargs): instance.slug = slugify(instance.title) ... views.py ... def index(request): main_categories = Category.objects.filter(...) return render(request, 'index.html', {'main_categories': main_categories}) def category(request, category_slug): try: category_selected = Category.objects.get(slug=category_slug) except Category.DoesNotExist: category_selected = None albums = category_selected.albums.all() return render(request, 'category.html', { 'category_selected': category_selected, 'albums': albums }) def album(request, category_slug, album_slug): try: category_selected = Category.objects.get(slug=category_slug) album_selected = Album.objects.get(slug=album_slug) except Category.DoesNotExist: … -
Django-celery-beat is scheduling interval tasks continuously
I recently followed this tutorial: https://www.codingforentrepreneurs.com/blog/celery-redis-django/ in order to configure django-celery-beat. Everything works fine if I start the beat worker like this: celery -A proj beat -l info however, if I get the beat scheduler to use the django DB, as follows: celery -A proj beat -l info -S django it starts to stream out tasks to the worker continuously (and not based on the specified interval. What could be the issue? -
Cannot assign "<TheModel>": "RelatedModel.the_model" must be a "TheModel" instance
So I have a ForeignKey field on what we'll call RelatedModel, which references what we'll call TheModel. The ORM is completely freaking out when I try to access instances of RelatedModel through an instance of TheModel, example: the_model_instance.related_models.all() ValueError: Cannot assign "<TheModel: 403:>": "RelatedModel.the_model" must be a "TheModel" instance. the_model_instance.related_models.create() ValueError: Cannot assign "<TheModel: 403:>": "RelatedModel.the_model" must be a "TheModel" instance. I can still get instances of RelatedModel via the Manager just fine, but it'd be a shame to lose the convenience/syntax of getting them through the parent. Has anyone encountered this before/ have any ideas?? Also the relationship is pretty standard: class RelatedModel(models.Model): the_model = models.ForeignKey(TheModel, related_name='related_models', null=False) -
Reverse for 'sending_message' not found. 'sending_message' is not a valid view function or pattern name
I have an app called com when I try to access viewing_user template which contains a form with action to another view get the error above this is urls.py app_name = 'com' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<name>[\w\-]+)/$',views.viewing_user, name='viewing_user'), ] this is the views.py from django.shortcuts import render from django.contrib.auth.models import User # Create your views here. RECEIVER_ID = 0 def index(request): return render(request, 'com/index.html',{}) def viewing_user(request, name): #username = request.GET.get('username','') try: User_obj = User.objects.get(username = name) RECEIVER_ID = User_obj.id except User.DoesNotExist: User_obj = None return render(request, 'com/viewing_user.html',{'u':name,'obj':User_obj}) def sending_message(request): form = MessageForm() if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid: message = message_form.save(commit = False) message.date = datetime.date.now() message.from_user = user.id message._to = RECEIVER_ID message.save() else: print form.errors return render(request, 'com/viewing_user.html', {'form':form}) this is the template vieweing_user.html which seems that has a problem in the action of the form <html> {% if obj == None %} <h2>Sorry this user ({{u}}) DoesNotExist</h2> {% else %} <h3>Be honest, and Tellme what you want</h3> <br> <i>{{obj.username}}</i> <form method="post" action="{%url 'com:sending_message' %}"> {%csrf_token%} {% for hidden in form.hidden_fields%} {{hidden}} {%endfor%} {% for visible in form.visible_fields%} {{visible}} {%endfor%} <input type="submit" value='Tell'/> </form> {%endif%} </html> -
django - method only works after the first call when using multi table inheritance
I'm trying to extend the Group and Permission models of django.contrib.auth.models to have some extra functionality. This is what i've done so far: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, ContentType, Permission as Auth_Permission, Group as Auth_Group class Group(Auth_Group): # Inherited attributes from django.contrib.auth.Group # name = models.Charfield() code = models.CharField(max_length=40, unique=True) group = models.OneToOneField(Auth_Group, on_delete=models.CASCADE, parent_link=True, related_name="group_extra" ) description = models.CharField(max_length=400, null=True, blank=True) def __unicode__(self): return self.code class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=40, unique=True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) groups = models.ManyToManyField( Group, verbose_name=_('groups'), blank=True, help_text=_( 'The groups this user belongs to. A user will get all permissions ' 'granted to each of their groups.' ), related_name="user_set", related_query_name="user", ) I'm trying to override the representation of Group in the PermissionsMixin Model, so that when I call, for instance, first_group = <Account>.groups.all()[0], it returns the object as my Group class and I can then call first_group.code (This seems to be working fine). The problem lies when I try to call <Account>.get_all_permissions()... This is what happens: >>> fmt = Account.objects.all()[0] >>> fmt.get_all_permissions() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\projects\Project\App\authentication\models.py", line 158, in get_all_permissions return _user_get_all_permissions(self, obj) File "C:\projects\python3-venv\lib\site-packages\django\contrib\auth\models.py", line 178, in _user_get_all_permissions … -
Django Relation Model
i'm working around with a python test and i'm stuck here. 1) For each Book in the Book list we would like to know how many Submissions were completed. 2) For each Book in the book list we would like to know how many Submissions have Brand data. You should be able to determine if a Profile has brands data by checking to see if the Profile has associated brands ids. My Model class Books(models.Model): name = models.CharField(max_length=128, unique=True) class Submission(models.Model): book = models.ForeignKey(Activation, on_delete=models.CASCADE, related_name='submissions') profile_id = models.UUIDField() class Meta: unique_together = [ ('activation', 'profile_id') ] My Serializer class BooksSerializer(serializers.Serializer): name = serializers.CharField() class ProfileSerializer(serializers.Serializer): id = serializers.CharField(source='_id') brand_ids = serializers.SerializerMethodField() def get_brand_ids(self, obj): return list(obj.brand_ids or []) My Testing code: @classmethod def setUpClass(cls): super().setUpClass() ProfileDocType.reset() book = Books.objects.create(name='Test Book') cls.profile1 = ProfileDocType( meta={'id': str(uuid.uuid4())}, brand_ids=[1, 2], ) cls.profile1.save() cls.profile2 = ProfileDocType( meta={'id': str(uuid.uuid4())}, brand_ids=[], ) cls.profile2.save() book.submissions.create(profile_id=cls.profile1._id) book.submissions.create(profile_id=cls.profile2._id) -
Cron in Docker container parallel with Django
I am currently running a Django web application in a Docker compose setup on Rancher. Because I want the server to run Django management commands periodically I've setup a crontab for it. * * * * * root /usr/local/bin/python /usr/src/app/manage.py updatesomething >> /usr/src/app/cron.log 2>&1 I am using the Dockerfile shown below and as you can see I've tried running the crontab standalone with CMD ["cron", "-f"]. This works fine and runs the command as it should. The idea however is that it can run parallel and trigger management commands on the web app. I've also verified that the crontab file is present. The cron.log file remained empty for over 10 minutes so cron clearly is not doing its job here. Does anyone have a solution to running cron parallel in a python:3 container? Supervisor is not really an option as I have a Python 3 codebase. And I couldn't yet get Circus to work with the database in another container. ############################################################ # Dockerfile to run a Django-based web application # Based on a Python 3 image ############################################################ # Set the base image to use to Python 3 FROM python:3 RUN apt-get update -qq && apt-get install -y -qq --force-yes cron … -
Time format while using django channels
I am using Django channels to update a realtime data on my website. class VisitorBinding(WebsocketBinding): model = VisitorInfo stream = "livelist" fields = ["user_id", "ip","device_type","time_stamp","last_active","active"] @classmethod def group_names(cls, *args, **kwargs): print("grouped"); return ["binding.values"] def has_permission(self, user, action, pk): return True The time i recive in the frontend is 2017-11-07T14:27:37.683Z, where as the actual time rendered through the views is Nov 07, 2017, 07:56 pm How can I make it timezone aware and use the same time formatting? html code: <script> $(function () { var ws_path = "/stream/"; console.log("Connecting to " + ws_path); var webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect(ws_path); webSocketBridge.listen(); webSocketBridge.demultiplex('livelist', function(payload, streamName) { // Handle different actions // Handle different actions console.log("a"); if (payload.action == "create") { // Create the new integer value console.log("b"); var content = "<tr id='" + payload.pk + "'><td id=1><a href=\"/action_map/"+payload.pk+"\">" + payload.data.user_id + "</a></td> <td id=2><a href=\"/action_map/"+payload.pk+"\">" + payload.data.ip + "</a></td><td id=3><a href=\"/action_map/"+payload.pk+"\">" + payload.data.device_type + "</a></td> <td id=4><a href=\"/action_map/"+payload.pk+"\">" + payload.data.last_active + "</a></td> <td id=5><a href=\"/action_map/"+payload.pk+"\">" + payload.data.active + "</a></td> </tr>"; $("#table2").prepend(content); } else if (payload.action == "update") { if($('#'+payload.pk).length){ if(payload.data.active==false) { $("tr[id=" + payload.pk + "]").remove(); }else{ $("tr[id=" + payload.pk + "] td[id="+1+"]a").text(payload.data.user_id); $("tr[id=" + payload.pk + "] td[id="+2+"]a").text(payload.data.ip); $("tr[id=" + payload.pk + … -
Django count of each subgroup
Imagine I've the following models: class User(): pass class Category(): title = CharField class Photo(): owner = models.ForeignKey(User, related_name='photos') category = models.ForeignKey(Category) published = models.BooleanField() I want to have the number of published photos users posted for each category for each user. I tried something like: User.objects.annotate(num_entries=Count( Case(When(photos_published=True, then=1), output_field=IntegerField())) ) but couldn't find how to group this by category.. The result I want to get is something like this: user0: 5 for category1 3 for category2 user4: 2 for category2 I can resort to raw sql if this doesn't work, since there are millions of users I don't want to loop over them. I am using PostgreSQL. -
views from another app doesnt work in django?
I have two apps 1. posts 2. boards. I need to create url link in boards template to view from posts app. my root urls.py: urlpatterns = [ url(r'^', include('boards.urls')), url(r'^', include('posts.urls', namespace="posts")), ] posts.urls: # -*- coding: utf-8 -*- from django.conf.urls import include, url from views import ( listofposts, create_post, detail, update_post, category, ) urlpatterns = [ url(r'^create/', create_post , name='create_post'), url(r'^category/(?P<slug>[-\w]+)/$', category, name='category'), url(r'^(?P<slug>[-\w]+)/edit/$', update_post, name = 'update_post'), url(r'^(?P<slug>[-\w]+)/$', detail, name = 'detail'), url(r'^$', listofposts , name='listofpost'), ] Boards template link <a class="navbar-brand" href="{% url 'posts:listofposts' %}">Home</a> I got the mistake : Exception Value: Reverse for 'listofposts' not found. 'listofposts' is not a valid view function or pattern name. -
Sum of fields for filtered queryset using django_filters
I have the following view class AuthorList(FilterView): model = Author filterset_class = AuthorFilter context_object_name = 'authors' In the template, one of the field is {{ author.value }}, which is an integer. What I would like to do is to show the sum of all {{ author.value }} in my template, but in a dynamic way (if some filters are used, the sum is updated with the current Queryset). I have tried adding extra context with get_context_data but I couldn't find out how to make it in a dynamic way. -
django + nginx https redirect shows (414 Request-URI Too Large)
I am trying to solve nginx redirect to https but when I use www.ozkandurakoglu.com I am getting 414 Request-URI Too Large error. Here is my settings for nginx: upstream ozkan_server { server unix:/home/ytsejam/public_html/ozkansimple/run/gunicorn.sock fail_timeout=10s; } server { listen 80; server_name ozkandurakoglu.com www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com; return 301 $scheme:https://ozkandurakoglu.com$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/ozkandurakoglu.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ozkandurakoglu.com/privkey.pem; ssl_trusted_certificate /etc/letsencrypt/live/ozkandurakoglu.com/chain.pem; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security max-age=15768000; ssl_stapling on; ssl_stapling_verify on; server_name www.ozkandurakoglu.com ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; error_log /home/ytsejam/public_html/ozkansimple/logs/nginx-error.log warn; large_client_header_buffers 6 16k; ... } can you help me ? Thanks -
request.user is not letting me make changes to the current user?
In my view function, I'm trying to make 2 modifications to the current user; consider him a premium subscriber by marking model field is_premium_subscriber as True and adding him to a group named Premium Agents. However the changes don't seem to be registering in my views.py! Here is my code: def payment_response(request): new_charge = PremiumSubscriptionCharge() if request.method == "POST": ... Some code here try: ... lots of code here new_charge.agent = request.user # This line is working fine, meaning request.user is properly assigned to the current user request.user.is_premium_subscriber = True # This is not working, is_premium_subscriber is still false after the request premium_agent_group = Group.objects.get(name='Premium Agents') premium_agent_group.user_set.add(request.user) # This is not working either, the current user does not get added to the group. request.user.save() # I don't know if this is necessary, but I put it here just in case. except stripe.error.CardError as ce: ... some code else: ... some code My user model for reference. I created a custom User model by inheriting AbstractUser... could this have caused the issue? class Agent(AbstractUser): is_premium_subscriber = models.BooleanField(default=False) -
Get the matched url pattern on Django
I am working on an existing Django application where there are many url patterns with same name. For example these three url patterns have same url name / view method: url(r'^create/type/(?P<negotiation_type>.*)/(?P<infomodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/type/(?P<negotiation_type>.*)/$', 'setup_negotiation', name='setup_negotiation'), url(r'^create/(?P<processmodel_uuid>.*)/$', 'setup_negotiation', name='setup_negotiation'), I want to know which pattern current url is matched with. I can get named url from resolve(request.path_info).url_name but what I need is to get the matched pattern string '^create/(?P<processmodel_uuid>.*)/$' or something like that. -
Website not sending any data : ERR_EMPTY_RESPONSE unreliably.
I have a (Https) website running with django 1.17.11, nginx 1.4.6 and gunicorn 19.7.6. Yesterday my website seemed to be running correctly, but since today it's displaying an error. It is inconsistent but this is what appears to be happening. First time, the site will load without problem. Upon refresh, or while navigating to another page on the website, the site will either load or display {my-site} didn’t send any data. ERR_EMPTY_RESPONSE Once a page display ERR_EMPTY_RESPONSE once, it will consistently display this error. Even though the homepage might display the error, a different page could still be working. (E.g. site.com doesn't work, but site.com/a does work) This is happening in Chrome and Firefox (haven't tested in other browsers) This happens on windows 10, Ubuntu 14.04 and Android Oreo (only ones tested) There do not appear to be any additional errors, nor anything related reported in the error logs. Does anybody know what this could be related to? Or any additional tests I could run to try to get at least an consistent error? Any possible fixes? -
Django query join with another query on the same table
I have a model like this: class mymodel(models.Model): user1 = models.CharField(max_length=255, null=True, blank=True) user2 = models.CharField(max_length=255, null=True, blank=True) paid = models.FloatField(default=0) reason = models.CharField(max_length=150, choices=REASON_NAMES, null=True, blank=True) and I have two queries like this: users_trx1 = mymodel.objects.values('user1').annotate(r1_c=Count( Case( When(reason='REASON1', then=1), output_field=IntegerField() ) )).annotate(r2_c=Count( Case( When(reason='REASON2', then=1), output_field=IntegerField() ) )).order_by('user1') The second query gets the sum paid to user2: users_trx2 = mymodel.objects.values('user2').annotate(r1_s=Sum( Case( When(reason='REASON1', then='paid'), default=0.0, output_field=FloatField() ) )).annotate(r2_s=Count( Case( When(reason='REASON2', then='paid'), default=0.0, output_field=FloatField() ) )).order_by('user2') Now I need a way to left join the two queries. Meaning, that I need a new query that will get me in each row: (user1, r1_c, r1_s, r2_c, r2_s). I need the join to get user2 values from users_trx2 query that match user1 from users_trx1 query. I'm using Django 1.11 with mysql backend -
Iterate JSON in a django template
I have a json coming from a view in below format , [ { "model":"booking.bookeditem", "pk":192, "fields":{ "Booking_id":155, "hoarding":9, "date_from":"2017-11-21", "date_until":"2017-12-06", "price_net":"34500", "created":"2017-11-07T11:35:49.675Z" } } ] I need to iterate through this json and print it in the template.Actually, I want to create an invoice email for the user after booking is performed for that I passed bookeditems as context to email templates. Here is the view to create booking, views.py : def create_order(request,checkout): booking = checkout.create_order() if not booking: return None, redirect('cart:index') checkout.clear_storage() checkout.cart.clear() bookingitems = BookedItem.objects.filter(Booking_id=booking.pk) booking.send_invoice_email(booking,user,bookingitems) return booking, redirect('home') Function to send invoice email, def send_invoice_email(self,booking,user,bookingitems): customer_email = self.get_user_current_email() data = serializers.serialize('json',bookingitems) subject ="invoice" ctx = { 'hoardings':data } send_invoice.delay(customer_email, subject, ctx) and i'm using celery&django EmailMessage to sending invoice email. task.py: @shared_task(name="task.send_invoice") def send_invoice(customer_email, subject, ctx): to=[customer_email] from_email = 'example@gmail.com' message = get_template('email/invoice_email.html').render(ctx) msg = EmailMessage(subject,message,to=to,from_email=from_email) msg.content_subtype = 'html' msg.send() I tried this : {% for i in hoardings %} <tr> <td>{{ i.pk }}</td> </tr> {% endfor %} But it is not working , and the loop are iterating for each and every string. Where am i going wrong in the iteration? Please help.. -
django one queryset for two tables ( one to many related )
I have created one to many relationship ( two tables ) in this way that every user has it's own ip connections list - every user has many connections. It looks as shown below: class Conn(models.Model): src_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) src_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) dst_ip = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) dst_port = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) proto = models.CharField(max_length=6, unique=False,default=None,blank=True,null=True) start_data = models.CharField(max_length=18, unique=False,default=None,blank=True,null=True) r_user = models.ForeignKey(User, on_delete=models.CASCADE) class User(models.Model): e_user = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True) e_dev = models.CharField(max_length=15, unique=False,default=None,blank=True,null=True) e_session = models.CharField(max_length=9, unique=False,default=None,blank=True,null=True) e_start = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_stop = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_summary = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) e_ip = models.CharField(max_length=20, unique=False,default=None,blank=True,null=True) I'm trying to get all Users with their connections ( Conn ) in one queryset and then display everything in template. So far I can display every User without any problems with q=Users.objects.all() and passing queryset to template. The question may be a bit not smart but how can I query all Users table including related connections ( Conn ) as one queryset ant then enumerate this connections in a form ? Thank you in advance -
url pattern matching string parameter with space
I had problem matching URL pattern with a regular expression in Django. urlpattern: url(r'^search/(?P[\w\s ]+)/$',views.specs, name='spec'), url I am trying to match: /search/%20Iphone7%20jet%20black/ the title is something like this " iPhone 7 jet black" Thanks in advance. -
My datatable has a button per row and I want to perform a filter (with the selected data) in another table when I click. How can I do that in Django?
I am testing a application that has 2 datatables. I am using django_tables2 and django_filter The first, has one button per row, and when it is clicked it extracts a content from the second column of its row. I want to use this data to apply a filter request in a second datatable which is displayed in the same page. As it is a large ammount of data it should be a new request instead of load everything and manipulate it using javascript. I am quite lost.. How could I do that??? Please any help?? Table.py class MyColumn(tables.Column): empty_values = list() def render(self, value, record): return mark_safe('<button id="%s" class="btn btn-info">Submit</button>' % escape(record.id)) class AdTable(tables.Table): submit = MyColumn() class Meta: model = Ad attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_ad'} class PtTable(tables.Table): class Meta: model = Pt attrs = {'class': 'table table-striped table-bordered table- hover','id':'id_pt'} HTML <body> <div> <h1> "This is the Table" </h1> </div> <div> <table> {% render_table ad_table %} </table> </div> <div> {% block content %} <div> <form method="get"> {{ form.as_p }} <button type="submit">Search</button> </form> </div> {% endblock %} </div> <div> <table> {% render_table pt_table %} </table> </div> <script> $(document).ready(function(){ $('#id_ad').DataTable(); $('#id_ad').on('click','.btn',function(){ var currow = $(this).closest('tr'); var result … -
want to customise django cms forms using custom styling
I'm following this tutorial (https://pypi.python.org/pypi/djangocms-forms/) to create custom forms with django-forms in this tutorial, Essentially, I want to know how to define my own "FORM TEMPLATE" for this plugin.I want to include my own styling and post requests too. Thank you -
How do i get content_type of a file
I am creating a file. I sent base64 string as an argument. This is my code: def save_file(request_data): """ """ data = base64.b64decode(request_data.get('file')) file_type = imghdr.what('', h=data) if file_type not in ['pdf', 'txt', 'xls', 'xlsx', 'html']: return ({"msg": "Upload a valid file. The file you uploaded is not acceptable"}, 400) file = tempfile.TemporaryFile() file.write(data) file_size = os.fstat(file.fileno()).st_size name = str(file.name)+"."+str(file_type) content_type = magic.from_file(name, mime=True) uploaded_file = InMemoryUploadedFile(file=file, field_name='path', name=name, content_type=content_type, size=file_size, charset='utf-8') UploadedFile.objects.create(path=uploaded_file, name=request_data.get('name'), meta_info=request_data.get('meta_info', '{}'), status=request_data.get('status', 'I')) file.close() return ({"msg": "File created successfully"}, 200) and I am getting this error: File does not exist: 32.jpeg at this line: content_type = magic.from_file(name, mime=True) Does anyone know how to get content type from base64 string? -
Duplicate Data issue for admin inlines with slug field
I have a main model that includes a submodel in the django admin as a TabularInline. The submodel has a slug field that automatically slugifies the name field if left blank. This slugify function is called in the submodel's save(). The problem is if I try to add multiple new submodel entries and leave the slug field blank the form's verification checks deny the submission because the slug field requires unique values. How do I fix the admin so it doesn't throw this duplicate data error for multiple blank slug fields? -
django: custom RelatedManager on GenericForeignKey
Let there be models: class Author(models.Model): name = models.CharField(max_length=100) comments_on_works = ?? class Book(models.Model): title = models.CharField(max_length=100) year_published = models.IntegerField() author = models.ForeignKey('Author', on_delete=models.CASCADE) class Article(models.Model): title = models.CharField(max_length=100) abstract = models.CharField(max_length=500) author = models.ForeignKey('Author', on_delete=models.CASCADE) class Comment(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) body = models.CharField(max_length=500) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') So that: Book and Article cannot be coerced into one model Comment can be made on either Book or Article - thus the GenericForeignKey Comment cannot be divided into BookComment and ArticleComment models Now I would like to have a manager Author.comments_on_works that would get me all comments on author's Books and Articles. How do I do that? -
django migrate error : 'Microsoft OLE DB Provider for SQL Server', "Cannot insert the value NULL into column 'last_login', table
I have installed below versions Django==1.8 django-mssql==1.8 pypiwin32==220 pytz==2017.3 and my setting.py file is as below. ----------------Start of setting.py------------------ INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases """DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }""" DATABASES = { 'default': { 'NAME': 'shetdb', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': 'ppp@123', 'OPTIONS': { 'provider': 'SQLOLEDB', 'use_legacy_date_fields': 'True', 'use_mars': True } } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -------------------End of setting.py file---------------------------- with these settings , I am not able to create super user/admin for sample application. When i try to createsuperuser using command >python manage,py createsuperuser it asks for username/email and password (2 times) after entering and hitting enter, I am getting below error in console. ---------------------------start----------------------------------------------- Email address: p@123 Error: Enter a valid email address. Email address: p@123.com Password: Password (again): Traceback (most recent call …