Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formatting dates for annotating count in Django + Python 3
I'm currently trying to annotate and count some dates, based on the number of times they appear. visits = Subs.objects.filter(camp=campdata, timestamp__lte=datetime.datetime.today(), timestamp__gt=datetime.datetime.today()-datetime.timedelta(days=30)).\ values('timestamp').annotate(count=Count('timestamp')) If I put this in a for loop like, for a in visits: I would get back the following in Json. {'timestamp': datetime.datetime(2018, 10, 5, 15, 16, 25, 130966, tzinfo=<UTC>), 'count': 1} {'timestamp': datetime.datetime(2018, 10, 5, 15, 16, 45, 639464, tzinfo=<UTC>), 'count': 1} {'timestamp': datetime.datetime(2018, 10, 6, 8, 43, 24, 721050, tzinfo=<UTC>), 'count': 1} {'timestamp': datetime.datetime(2018, 10, 7, 4, 54, 59, tzinfo=<UTC>), 'count': 1} This is kinda the right direction, however, it's counting to the second.. I just need to days, so that the event that happened on 2018, 10, 5 would be count: 2 for example. Can anyone lead me into the right direction? Additionally, whats the most "django" way of converting the dates into something more json / api friendly? My ideal json return would be something like {'timestamp': 2018-10-5, 'count': 2} Thanks! -
potential security vulnerability mail from github
Why I am getting this kind mail from github? I am a Python/Django developer. Most of my project contains django dependencies in a requirements.txt file. And my requirements.txt file contains as follows - Django==1.11.9 pytz==2018.5 Subject: One of your dependencies may have a security vulnerability Body: shahjalalh, We found a potential security vulnerability in a repository for which you have been granted security alert access. -
How to link a select category from template to django model object?
I am learning how to use django and I am a bit stuck with this situation. I have a many to many relationship in my product model (category field). Now, I am able to display the category data in a select box which is a multiple selection. Now, what I want to do is have the user to select one or more categories from the template and then save the data in my product model. Here is my code - if request.method =='POST': print ('entered') name = request.POST['name'] brand = request.POST['brand'] sku = request.POST['sku'] price = request.POST['price'] quantity = request.POST['quantity'] description = request.POST['description'] imageurls = request.POST['urls'] print('imageurls',imageurls) categorylist = request.POST['categories'] print('categorylist',categorylist) categories = re.findall(r"[\w']+", categorylist) print categories imageurls = imageurls.split('~') print('iageurls',imageurls) for x in categories: categoryobj = Category.objects.filter(name=x).values() _id = categoryobj.id print('_id',_id) print ('categoryobj',categoryobj) # Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj) return HttpResponse('success') models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.') description = models.TextField() is_active = models.BooleanField(default=True) meta_keywords = models.CharField("Meta Keywords", max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag') meta_description = models.CharField("Meta Description", max_length=255, help_text='Content for description meta tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog:categories', … -
image url is not showing in browseable api of django rest
Following are the different parts my Django rest API Project structure project structure settings.py ... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ... accounts/models.py/Profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to="images/", null=True, blank=True) contact_number = models.CharField(validators=[contact_number_validator], max_length=16, blank=True, null=True) address = models.CharField(max_length=30, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) USER_TYPES = ( ('o', 'Owner'), ('c', 'Customer'), ('e', 'Employee'), ) user_type = models.CharField( max_length=1, choices=USER_TYPES, blank=True, default='c', help_text='User Role', ) saloon = models.ForeignKey(Saloon, null=True, on_delete=models.CASCADE) def __str__(self): return '{}\'s profile'.format(self.user.username) api/views.py/UpdateUserProfileView class UpdateUserProfileView(generics.RetrieveUpdateAPIView): serializer_class = UserProfileSerializer permission_classes = (permissions.IsAuthenticated, CanUpdateUserProfile) def get_queryset(self): return Profile.objects.filter(user=self.request.user).values( 'user__username', 'user__email', 'user__first_name', 'user__last_name', 'user_type', 'birth_date', 'contact_number', 'address', 'profile_picture', ) def perform_update(self, serializer): profile = get_object_or_404(Profile, user=self.request.user) user = get_object_or_404(User, id=profile.user.id) user.username = serializer.validated_data['user__username'] user.first_name = serializer.validated_data['user__first_name'] user.last_name = serializer.validated_data['user__last_name'] user.email = serializer.validated_data['user__email'] user.save() profile.contact_number = serializer.validated_data['contact_number'] profile.birth_date = serializer.validated_data['birth_date'] profile.address = serializer.validated_data['address'] profile.profile_picture = serializer.validated_data['profile_picture'] profile.save() serializers.py class UserProfileSerializer(serializers.ModelSerializer): profile_picture = serializers.ImageField(max_length=None, use_url=True) username = serializers.CharField(source='user__username') first_name = serializers.CharField(source='user__first_name') last_name = serializers.CharField(source='user__last_name') email = serializers.EmailField(source='user__email') class Meta: model = Profile depth = 1 fields = ( 'username', 'first_name', 'last_name', 'email', 'contact_number', 'birth_date', 'user_type', 'address', 'profile_picture', ) #fields = '__all__' read_only_fields = ('user_type',) project level URLs urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('api.urls')), … -
Counter increment in template outside of for loop
I need to do a counter increment within a loop. I had a look at django for.counter, but unfortunately, my increments dont exactly occur within each iteration of the loop. So is there any way at all that I can implement increment of a variable within django template, without going to great pains to implement a new object in my code to do this without such an increment? In the following code, I am writing the lines {{ count = 0 }}, {{ count += 1 }} just for illustration purpose. I know it wont work. The following is a very simplified form of my template: <div class="jumbotron slotgroup slotavailable mb-1 mt-5" id="jumbo_week_avail"> <div class="slot-header" role="alert"> Headertext </div> {% if weeklyslotsav %} {% for day,daynum in weekzip %} {{ count = 0 }} {% if daynum in weeklyslotsav.day %} {% for weekslotav in weeklyslotsav %} {% if weekslotav.day == daynum %} <div class="row row_week_avail{{ weekslotav.day }}" id="row_week_avail{{ weekslotav.day }}_{{ count }}"> </div> {{ count += 1 }} {% endif} {% endfor %} {% else %} <div class="row row_week_avail{{ daynum }}" id="row_week_avail{{ daynum }}_0"> </div> {% endif %} {% endfor %} {% else %} {% for weekday, weeknum in weekzip %} … -
Creating a list of dictionaries with same keys?
I wanted to create a list that contains x amount of dictionaries all containing the same keys but with different values that's made in a for loop: Something like [{'name': Brenda, 'Age': 22, 'Sex': Female}, {'name': Jorda, 'Age': 32, 'Sex': Male}, {'name': Richard, 'Age': 54, 'Sex': Male}] My code is this: people = [] person = {} humans = gethumans() for human in humans: number_people, people_data = People.data() person['name'] = human.name person['age'] = human.age person['Sex'] = human.name people.append(person) My output is something like this: [{'name': Richard, 'Age': 54, 'Sex': Male}, {'name': Richard, 'Age': 54, 'Sex': Male} {'name': Richard, 'Age': 54, 'Sex': Male}] Since the dictionary values are getting replaced and not added and it's just appending the same dicitnary. How can I get around this? -
cant automatically login with django-axes
i cant log in users automatically after signup and i get no error ???? this is my signup view. class SignUp(CreateView): def form_valid(self, form): recaptcha_response = self.request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } data = parse.urlencode(values).encode() req = myr.Request(url, data=data) response = myr.urlopen(req) result = json.loads(response.read().decode()) if result['success']: form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(request=self.request,username=username, password=raw_password) login(self.request, user) else: messages.add_message(self.request, messages.INFO, "Invalid captcha") return redirect('home') return super(SignUp,self).form_valid(form) what am i missing here?????????? -
Django object-tools button when adding an instance in admin interface
I tried adding a button to the admin interface, when adding a new instance of the model. From what I saw, the body of that page has the class name change-form, so I overwrote the change-form.html, however, this ended up adding the button to the object-tools when editing an existing object and not when creating a new one. I haven't seen the django admin templates having object-tools when creating new objects, so is this even possible? -
Provide an alternative text field for 'other' choice in models.CharField() choices
I've 5 options in choice field as mentioned in the CHOICES variable for a complaint form. I want the user to be able to select an option from 1-4 but for 5th 'other' option, I want to provide the user with an alternative text field like this, but how can I do this in Django(v2.1) forms? My models.py looks like this: class Complaint(models.Model): CHOICES = ( ('1', 'Poor quality material or workmanship'), ('2', 'Alternate is not equal to brand specified'), ('3', 'Not operating properly - needs frequent repair'), ('4', 'Old or discolored stock'), ('5', 'Other'), ) product_type = models.CharField(max_length=100) brand = models.CharField(max_length=100) product_id = models.IntegerField() item_description = models.TextField() choice_field = models.CharField(max_length=100, choices=CHOICES, default='1') complaint_description = models.TextField() purchase_date = models.DateField(blank=False) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_no = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list suggestions = models.TextField() def __str__(self): return f'{self.brand} complaint' and my forms.py is this: class ProductComplaint(forms.ModelForm): class Meta: model = Complaint choice_field = forms.ChoiceField(widget=forms.RadioSelect) fields = ['product_id', 'product_type', 'brand', 'item_description', 'choice_field' ,'complaint_description', 'purchase_date', 'phone_no', 'suggestions'] -
Heroku- "No web Process Running "
I'm trying to upload my site in heroku. But it keeps saying application error..So the logs file says 2018-10-07T07:12:54.329907+00:00 app[api]: Release v10 created by user "mail" 2018-10-07T07:13:08.000000+00:00 app[api]: Build succeeded 2018-10-07T07:13:38.708309+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=blahblah.herokuapp.com request_id=ccb860eb-fc93-4d73-819f-66a756ee1030 fwd="103.200.94.115" dyno= connect= service= status=503 bytes= protocol=https 2018-10-07T07:13:39.926612+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=blahblah.herokuapp.com request_id=0634dc3e-dc65-40f5-aa2b- db18c5e05438 fwd="103.200.94.115" dyno= connect= service= status=503 bytes= protocol=https 2018-10-07T07:21:59.757115+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=blahblah.herokuapp.com request_id=d070a368-ae8e-44ce-a7c8-2a8a74bf1dcb fwd="103.200.94.115" dyno= connect= service= status=503 bytes= protocol=https 2018-10-07T07:22:00.323157+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=blahblah.herokuapp.com request_id=4cc2caca-7ea4-4b23-9d41- 25f824d4f3b2 fwd="103.200.94.115" dyno= connect= service= status=503 bytes= protocol=https My Procfile is: web: gunicorn siteName.wsgi And I've also added the necessary requirements.txt and runtime.txt. After checking a few things I also added the command : heroku ps And it says "No dynos on ⬢ appName" And I tried command heroku ps:scale web=1 But it says Scaling dynos... ! ! Couldn't find that process type. Please Help :) -
Dynamic columns with SingleTableMixin and FilterView in Django
I'm using SingleTableMixin and FilterView in Django to render a filter form and table. On the basic level it works very well. Now, the table has as many columns as the model has fields (as it should), but I would like to render ONLY the columns for which a user has provided input in the filter form and exclude the others columns dynamically. I'm trying to achieve this by using def get_table_kwargs(self): Here is my code: class FactListView(SingleTableMixin, FilterView): table_class = FactTable filterset_class = FactFilter template_name = 'main/table.html' def get_table_kwargs(self): filtered = self.filterset.form.data() columns = {} fact_fields = [ "fact", "category", "subcategory1", "subcategory2", "subcategory3", "subcategory4", "world_region", "country", "country_region", "country_area", "source", "actors", "subactors1", "subactors2", ] for field, value in filtered(): if value is not None: columns.update({field: value}) fact_fields[:] = [x for x in fact_fields if x not in columns] return { 'exclude': fact_fields } I'm currently getting an error saying: "TypeError at /table/ 'dict' object is not callable" That's because I'm a noob. So I would be very grateful for comments on this particular error, which results from filtered = self.filterset.form.data(), as well as on the general logic. Many thanks in advance! -
How to make a field editable=False in DRF
I've a serializer. I want to restrict updating a field. How would I do that? class ABCSerializer(serializers.ModelSerializer): class Meta: """Meta.""" model = ModelA fields = ('colA', 'colB', 'colC',) colA is a required field while creating the object. However, it should not be allowed to update. How can I do that? -
How to create forms in a table in django? to automate reporting
The task is to automate reporting. There are 5 enterprises, they enter data into one form in excel, then in the data center is integrated into a single table. Please tell me how it can be implemented in django? -
Creating new Django Object with newly created user
I'm attempting to auto-load a bulk list of users into a Django application and I'm creating the users as follows... new_user = User.objects.create_user( username='testusername', password='testpassword', email='testemail', first_name='testfirstname', last_name='testlastname' ) new_user.save() new_user_phone = Phone.objects.create( uid = new_user, number = 'phone_number', validated = True, text = True, voice = True, created_on = datetime.now(), validated_on = datetime.now() ) The User object is created successfully, but when the Phone object is attempting to be made it throws an error stating Cannot assign User: testusername, "Phone.uid" must be a "User" instance. But when I check the type it's of 'User' type, and as stated above the User object is successfully created in the DB while the script stops before creating the phone. Any direction on this error would be greatly appreciated. Thanks! -
how to redirect a form error to the form page with validaton errors
i had created a form with user details and written a class view to update users details in my django aapp, everything is working but, instead of form widgets i hand coded form in page through that form i am updating the details. I didn't understand how to redirect a form error from class view to form page with error, in django errors it's showing that doesn't contain aapp/user_form.html template. Html code in "profile.html" page which contain form <div class="row"> <div class="col-md-12"> <form action="{% url 'updatedprofile' user.id %}" method="post"> {% csrf_token %} <div class="modalBox"> <div class="row"> <div class="col-md-11"> <h4>Update Profile</h4> </div> <div class="col-md-1 icon"> <p><a href="{% url 'mprofile' %}"><i class="fas fa-times"></i></a></p> </div> </div> <div class="row"> <div class="col-md-12"> <table class="table table-striped"> <thead> <tr> <td>First Name:</td> </tr> </thead> <tbody> <tr> <td> <input type="text" name="first_name" value="{{user.first_name}}" class="form-control no-border simplebox" placeholder="Enter Your First Name Here..."> </td> </tr> </tbody> <thead> <tr> <td>Last Name:</td> </tr> </thead> <tbody> <tr> <td> <input type="text" name="last_name" value="{{user.last_name}}" class="form-control no-border simplebox" placeholder="Enter Your Last Name Here..."> </td> </tr> </tbody> </table> <table class="table table-striped"> <thead> <tr> <td>Mobile: </td> </tr> </thead> <tbody> <tr> <td><input type="number" name="mobile" value="{{user.mobile}}" class="form-control no-border simplebox" placeholder="Enter Mobile Number Here..."></td> </tr> </tbody> </table> <table class="table table-striped"> <thead> <tr> <td>Profile … -
How mezzanine templating works?
I have a mezzanine website and in that website I am trying to show top stories block in the blog. I am able to show the recent posts but when I am trying to add something for top stories it is not working correctly. I don't have any clue of how to add this module. Any ideas? I am attaching the code for recent posts <div class="section_content"> <div class="grid clearfix"> <div> {% load blog_tags keyword_tags mezzanine_tags i18n %} {% blog_recent_posts 1 as recent_posts %} {% if recent_posts %} {% for recent_post in recent_posts %} <div class="card card_largest_with_image grid-item"> {% spaceless %} <a class="text-capitalize" href="{{ recent_post.get_absolute_url }}"> {% if settings.BLOG_USE_FEATURED_IMAGE and recent_post.featured_image %} <img class="card-img-top" src="{{ MEDIA_URL }}{% thumbnail recent_post.featured_image 610 193 %}"> {% endif %} </a> {% endspaceless %} <div class="card-body"> <div class="card-title"><a href="{{ recent_post.get_absolute_url }}">{{ recent_post.title }}</a></div> <p class="card-text">{{ recent_post.description|safe }}</p> <small class="post_meta"><span>{{ recent_post.publish_date|timesince }} {% trans "ago" %}</span></small> </div> </div> {% endfor %} {% endif %} </div> {% blog_recent_posts 5 as recent_posts %} {% if recent_posts %} {% for recent_post in recent_posts %} <div class="card card_default card_small_with_background grid-item"> {% spaceless %} <a class="text-capitalize" href="{{ recent_post.get_absolute_url }}"> {% if settings.BLOG_USE_FEATURED_IMAGE and recent_post.featured_image %} <div class="card_background" style="background-image:url({{ MEDIA_URL }}{% thumbnail … -
post data give me IntegrityError django
I'm new to django , and I'm trying to post data -key and value for aritcal using DRF : class ArticalMetaData(models.Model): key = models.CharField() value = models.CharField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = ("content_type", "object_id", "key") class MetaDataCreationSerializer(serializers.ModelSerializer): def __init__(self, content_object, *args, **kwargs): self.content_object = content_object super(MetaDataCreationSerializer, self).__init__(*args, **kwargs) class Meta: model = MetaData fields = ('key', 'value','content_object') but this give me this err: Exception Type: IntegrityError Exception Value: null value in column "object_id" violates not-null constraint -
Django, when should i create a new model?
In my Jobs app, i have a model called Job. This model has many fields, and this particular model is used internally by staff. On the website i have a page that displays one of these fields. The field is actually a choice field. INDUSTRIES = ( │ ('BAN', "Banking"), .... When i display this field it show BAN, but i want it in one particular situation to show Banking. How do i go about doing this ? -
How to define a serializer for model with a foreign key (not pointing to a pk field but a unique field)?
I am using django rest-framework There are two modes as below class Service(ResourceModelBase): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) access_key = models.CharField(max_length=200, unique=True, null=False) cluster = models.OneToOneField(Cluster, to_field='_id') class Cluster(ResourceModelBase): _id = models.UUIDField(unique=True, null=False, default=uuid.uuid1) name = models.CharField(max_length=200, unique=True, null=False) The service have a foreign key point to the cluster unique key _id field please be noticed that _id is not the primary key, it is a unique key. This is important to my later question. Then I define a serializer for the service model, so I can create and get the service data. class ServiceSerializer(serializers.ModelSerializer): cluster_id = serializers.SlugRelatedField(queryset=models.Cluster.objects.all(), slug_field='_id') class Meta: model = models.RGW fields = ('_id', 'access_key', 'cluster_id') Please be notice that I define the cluster_id as a SlugRelatedField not the PrimaryKeyRelatedField. The reason to do so is I want to pass the cluster_id a parameter to create service. If I define cluster_id as primary key related field, the framework tend to think the cluster_id foreign key is pointing to a primary key column. But in my case it is not. It is pointing to a unique key field . So I use SlugRelatedField(I `m not sure if this is the right way to do). But another problem shows … -
Reply to a reply in Django
I'm building a small blog system where a person can reply to a post. And another person can reply to a reply of the post. Anyone can reply to anyone's reply. How can I set up this whole system? Any kind of help will be appreciated. class Reply(models.Model): post = models.ForeignKey(Post, on_delete=SET_NULL, related_name='replies') user = models.ForeignKey(User, on_delete=SET_NULL) content = models.TextField() -
How do I make efficient queries in Django?
I have the following models, which are relative to Django's built in models Tag and Site. Given a Site, what is the most efficient way to query all the related Tags class InlineTag(models.Model): tag = models.ForeignKey(Tag, null=False) topic = models.ForeignKey(Topic, null=False) order = models.PositiveIntegerField(null=False, blank=True) class Topic(models.Model): description = models.CharField(max_length=255, blank=False) sites = models.ManyToManyField(Site) I'm doing this way currently, it seems too complex: tags = [] current_site = Site.objects.get_current() topics = Topic.objects.filter(sites=current_site) for topic in topics: inline_tags = InlineTag.objects.filter(topic=topic) for inline_tag in inline_tags: tags.append(inline_tag.tag) -
Quick question about Model() and Model.object.create()
Hello Everyone I saw this code and I was wondering what is the difference and which one is better Model.objects.creat() vs Model() during object creation in django. just wondering -
how to change userprofile object to user(name)?
Hi I am trying to change userprofile object to user in Django admin.. ive tried(models.py): def __str__(self): return self.user.username but to no avail what do I do thanks -
Internal server error with large file in django
I have the following problem; I have a module that reads a 1.5Gb file and then processes it with it. If I run it in the Python console it works normally, however if I make the call from that file read in a django view it returns error 500 before it highlights the entire file load. How to proceed? -
Mobile Peer to Peer Communication using Raspberry Pi (Django Channels, Socket.io Swift, iOS)
I'm building a mobile app on iOS and I wanted to get some advice as to how to proceed on my project. I want to build an app where if I send a button then this would relay an update to all other local devices within the same network/location. I believe in order to make this happen, I need to use Django Channels, Socket.IO for Swift, and a Raspberry Pi server. But I'm unsure of how all of this will work together. I'm aware of various WebSocket realtime networking services (e.g., PubNub) that can simplify this project, however, I'd like my app to be able to communicate with other devices that are also hooked up to the Raspberry Pi without internet. Please let me know if I'm not being clear enough in my question. Thanks.